Ever wondered why Google shows you content based on your location, or ads you see on websites are customized to your location? All this happens because of geolocation which makes it possible to identify the country, state, and sometimes even the city based on the IP address of your device.
To get a device geolocation from an IP address, we can use services with access to different databases that have this information. One of the most used ones is Regional Internet Registries. There are five of these registries, each responsible for various parts of the world. Other than that, there are companies further improving this data (secondary sources).
Now we know what IP geolocation is, why it is used, and how it works, we’ll now move to use it with Node.js and Express. I will build an API that returns data about my IP address. I will use ipdata as a data provider and Superface for communication with a 3rd party API.
Create a new Node.js project in an empty folder:
mkdir IP-Geo
cd IP-geo
npm init -y
npm i express
Since we are using ES6, go to package.json file and add "type": "module" . The result should look something like this:
{
"name": "ip-geo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.1",
}
}
Create index.js file with the following code:
import express from 'express';
const app = express()
app.listen(3000, () => {
console.log("Server listening on 3000")
})
Now to check if everything works, run the application:
node index.js
Now we need to read the IP address of the device connecting to our application. Express can read it from headers if it runs behind a proxy, which is a very common setup. To enable this, add the following line to the index.js file:
app.set("trust proxy", true);
Note: I am using Codesandbox for this example because if I run the server on my PC, it would see me connecting from localhost or local IP address.
We can read the IP address from the ip property of the incoming request (req). Replace index.js with the following code:
import express from 'express';
const app = express();
app.set('trust proxy', true)
app.get('/', async (req, res) => {
const ip = req.ip
res.send(ip);
})
app.listen(3000, () => {
console.log("Server listening on 3000")
})
Now we will integrate the API in our app to get geolocation from the IP we have extracted.
I am going to use Superface for API integration as it makes the integration super easy. I don’t have to deal with API docs, and I can use many providers using the same interface. Furthermore, I can use more ready-made API use cases from the Superface catalog. It’s a tool worth having in your toolbox.
First, install Superface OneSDK in your app:
npm i @superfaceai/one-sdk
Then choose your use case. We are going to use IP geolocation lookup.
Now we have to pick a provider to use. I will use ipdata. Create an account on ipdata.co to get your API key.
Back in Superface, copy and paste the code from the example into your index.js file. Replace with the API key you got from ipdata and the public IP address you have extracted into the ipAddress property.
Here is the resulting code:
import express from "express";
import { SuperfaceClient } from "@superfaceai/one-sdk";
const app = express();
app.set("trust proxy", true);
const sdk = new SuperfaceClient();
async function run(ip) {
// Load the profile
const profile = await sdk.getProfile("address/[email protected]");
// Use the profile
const result = await profile.getUseCase("IpGeolocation").perform(
{
ipAddress: ip
},
{
provider: "ipdata",
security: {
apikey: {
apikey: "9a511b6fc8334e1852cfbbd4ff3f1af3c42ed6abc75e96a1648b969a"
}
}
}
);
// Handle the result
try {
const data = result.unwrap();
return data;
} catch (error) {
console.error(error);
}
}
app.get("/", async (req, res) => {
res.send(await run(req.ip));
});
app.listen(3000, () => {
console.log("SERVER RUNNIHG AT PORT 3000");
});
Now just run your app with node index.js
You can find the resulting code on
and see it running here: https://forv0o.sse.codesandbox.io/Checkout out this video to find out more on - Find Location Using IP Address - YouTube
Also published here.