DEV Community

Cover image for Find location using IP address in Node.js
Dexter
Dexter

Posted on • Updated on • Originally published at blog.lamtell.com

Find location using IP address in Node.js

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 your 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 are 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 the IP geolocation is, why it is used, and how it works, we’ll now move to using it with Node.js and Express. I will build an API which returns data about my IP address. I will use ipdata as a data provider and Superface for communication with a 3rd party API.

Setting up the server

Create a new Node.js project in an empty folder:

mkdir IP-Geo
cd IP-geo
npm init -y
npm i express

Enter fullscreen mode Exit fullscreen mode

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",
  }
}
Enter fullscreen mode Exit fullscreen mode

Create index.js file with the following code:

import express from 'express';
const app = express()
app.listen(3000, () => {
    console.log("Server listening on 3000")
})
Enter fullscreen mode Exit fullscreen mode

Now to check if everything works, run the application:


node index.js

Getting client public IP address

Now we need to read an 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 into the index.js file:

app.set("trust proxy", true);
Enter fullscreen mode Exit fullscreen mode

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. To learn more, check Public vs. Private IP Address: What's the Difference.

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")
})
Enter fullscreen mode Exit fullscreen mode

Go to http://localhost:3000 and you see your IP address:

Image description

Integrating API to retrieve geolocation

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 Superface catalog. It’s a tool worth having in your toolbox.

Image description

First, install Superface OneSDK in your app:

npm i @superfaceai/one-sdk
Enter fullscreen mode Exit fullscreen mode

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.

Image description

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/ip-geolocation@1.0.1");

  // 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");
});
Enter fullscreen mode Exit fullscreen mode

Now just run your app with node index.js , go to http://localhost:3000/, and you should see the result.

Image description

You can find the resulting code on CodeSandbox and see it running here: https://forv0o.sse.codesandbox.io/

Checkout out this video to find out more on

Oldest comments (0)