Learn to build a microservice for IP lookup using NodeJS

Extract user’s location, timezone and much more.

Photo by **Wendy van Zyl** from **Pexels**

In this demo, we will be building a microservice to extract details from the user IP address using NodeJS and ExpressJS. There may be situations when we need to get some information about the users of our application to provide them a better user experience, like delivering location-based content and so on.

Without wasting much time, let’s get our hands dirty!

Implementing the service :

First, let us initialize our project by running the npm init -y command.

Now, we need to install the dependencies.

npm install express geoip-lite --save

Express module will be used for handling http requests from the client.

Geoip-lite will be used for IP lookup. We can use this library to fetch various information by passing the IP address.

After installing the dependencies, go ahead and create a file “app.js” in the project’s root directory. Add the following contents in the app.js file.

Save the file.

You can refactor this endpoint as per your need. For the sake of simplicity, I’m just returning the city, state, and country of the user.

Run node app.js from your terminal.

Your output should display the message: IP Lookup service started!

If we try to retrieve the IP address without using proxies, we will get the IP address something like this ::ffff:

We cannot test this application on localhost without using proxies. Hence we will use NGROK. You can install and configure NGROK by referring to this link.

You can start ngrok by running the command -./ngrok http 5000. Make sure that the node application is Up and running on port 5000.

If everything is ok, the ngrok output will be something like this.

Now, open the browser and navigate to your ngrok root URL followed by /lookup endpoint.

In my case, the root url is https://50bb377c3857.ngrok.io so the full URL is https://50bb377c3857.ngrok.io/lookup

The output will look like this :

If req.ip didnt work, you can try the following code to get the IP address from the request.

const ip = (req.headers["x-forwarded-for"] || "") .split(",").pop() || req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress;

> Note: If you want to host this service on a cloud service provider like AWS EB, you need to configure the nginx.config file inorder to retrieve the request source IP.

That’s all folks.Happy coding!✨✨