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,

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  npm self update - Selfupdate your global NPM package

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:


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

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

const requestIp = require('request-ip');

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

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

Leave a Comment