Get User’s IP address in Node.js (Express.js)

Getting User’s IP  or Request IP address sound’s pretty complex right? But It’s pretty Straight forward using Node.js and if you’re using Express.js, then it becomes even easier. We will discuss both methods below to get the IP address in node js and express js.

First, we will discuss how to get IP address of user or client or request in node js,

Article Contents

How to Get  User’s IP Address in Node JS

According to Nodejs Documentation, to get the IP address, they suggest following method:

var ip = req.connection.remoteAddress;

But, there is a catch, if your Node app running on NGINX or any other proxy for that matter, then you will get the local ip address for every request i.e, 127.0.0.1.

To solve this problem, we need to catch real ip address of the user from where the request is made.For achieving this we will look for the originating ip address in the X-Forwarded-For  HTTP Header. So the final and best method to get the ip address of request user will be:

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

That’s how you’ll get the real ip address of a user using nodejs, not proxy’s ip address.By using an OR statement, in the order above, you check for the existence of an x-forwarded-for header and use it if it exists otherwise use the request.connection.remoteAddress.

 

How to User’s get IP address in Express JS

First, you need to add the following line, if your server is behind a proxy,

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

Add following line in nginx.conf file:

See also  Find the host's cloud provider using Node.Js

proxy_set_header X-Real-IP $remote_addr;

and then req.ip for getting user’s ip address and you can also use above code to get ip address here too.

 

And if you want a simple solution, without having to do all this stuff then use:

 https://github.com/pbojinov/request-ip

 

const requestIp = require('request-ip');
// inside middleware handler
const ipMiddleware = function(req, res, next) {
    const clientIp = requestIp.getClientIp(req); 
    next();
};

// on localhost you'll see 127.0.0.1 if you're using IPv4 
// or ::1, ::ffff:127.0.0.1 if you're using IPv6
As Connect Middleware

const requestIp = require('request-ip');
app.use(requestIp.mw())

app.use(function(req, res) {
    const ip = req.clientIp;
    res.end(ip);
});

That’s it, folks, if you any suggestions or queries, please comment below.

Leave a Comment