How to Get User’s IP Details in ExpressJS

Oyetoke Tobiloba Emmanuel
codeburst
Published in
3 min readJul 2, 2018

--

Looking up user’s IP is very useful in different aspect of web and mobile applications. It can be used to get the user’s country, then serve a content, section related to that country e.g setting a default language for a user.

Well there are many techniques you can employ to achieve that. One technique you can employ is using a Rest API like IpStack to get details about user’s IP.

On NodeJS, you can use a module like geoip-lite or node-where to get user’s geolocation and IP details. With these modules, you can easily get user’s IP information.

Now lets say you are working with ExpressJS, and you only want a single line of code to achieve the same feature, you can go for Express-IP. With express-ip, you can get all the information you need on a user IP. You can get the country, city, radius, latitude and longitude.

Express-IP: How It Works

Express-IP is definitely an npm module that you can use in your ExpressJS projects to lookup user’s IP information. It utilizes the Express middleware layer functionality.

Middlewares are functions executed in the middle after the incoming request then produces an output which could be the final output passed or could be used by the next middleware until the cycle is completed. They have access to the request (req) object, response (res) object and next function which will either be passed into the response object or next middleware.

In this case, for every request, it’ll lookup the user’s ip using geoip-lite, then store it in order to be passed to the response object.

You also have the option to not use the middleware and just call the method directly to do a IP lookup.

How to Use

You need to install first:

npm install express-ip

Now lets create a simple express app that shows the user’s country and city:

node app.js

Note: This won’t work if you are localhost, since it needs to get the IP to do a lookup. So to test it, I had to use ngrok to expose http://localhost:5000. You can install and run ngrok on node by:

npm install ngrok
ngrok http 5000

That’s it, thanks for your time.

Hope you enjoyed this article? Clap and share to others.

✉️ Subscribe to CodeBurst’s once-weekly Email Blast, 🐦 Follow CodeBurst onTwitter, view 🗺️ The 2018 Web Developer Roadmap, and 🕸️ Learn Full Stack Web Development.

--

--