Background

Getting an IP address of a user/visitor is sinlge line of code. But, it can provide you some unexpected IP addresses like 127.0.0.1 or ::1 or maybe something else but not the IP that you wanted to get i.e. IP address of a visitor.

Lets say your node app is hosted using nginx as a reverse proxy server. You need to add following codes in order to get an correct IP address.

Code in Action

1. Add trust proxy in you express js app.

app.set("trust proxy", true);

2. Add proxy set header in your nginx configuration file. Paste the following code inside server block. 

proxy_set_header X-Forwarded-For $remote_addr

3. Now you can access your IP address inside your route as follows:

const ip = req.ip || req.header('x-forwarded-for') || req.connection.remoteAddress;

Furthermore, you can get more details like, user country, timezone and all using a node package called geoip-lite. You just need to install package using command:

npm i geoip-lite

Now, you can use this package as follows to get visitors ip details.

const router = require("express").Router();
const { lookup } = require("geoip-lite");

router.get("/", (req, res, next) => {
const ip =
req.ip || req.header("x-forwarded-for") || req.connection.remoteAddress;
const _lookup = lookup(ip);
res.send({ ip_details: _lookup });
});

module.exports = router;

Happy Coding ;)


Binod Chaudhary

devcolumn avatar

Software Engineer | Full-Stack Developer

© Copyright 2025. All Right Reserved.

Scroll to Top