How to determine a user's IP address in node [api]


var ip = req.headers['x-forwarded-for'] || 
     req.connection.remoteAddress || 
     req.socket.remoteAddress ||
     (req.connection.socket ? req.connection.socket.remoteAddress : null);

Note that sometimes you can get more than one ip address in req.headers['x-forwarded-for'].

The general format of the field is:

x-forwarded-for: client, proxy1, proxy2, proxy3

where the value is a comma+space separated list of IP addresses, the left-most being the original client, and each successive proxy that passed the request adding the IP address where it received the request from. In this example, the request passed through proxy1, proxy2, and then proxy3. proxy3 appears as remote address of the request.

This is the solution suggested by Arnav Gupta:

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


How can I determine the IP address of a given request from within a controller? For example (in express):'/get/ip/address', function (req, res) {
    // need access to IP address here

How to Get ip address of client using our website using nodejs?

Its a part of the request


you can get it like this

var app = require('express')();

app.get('/', function(req, res) {
  res.send('your IP is: ' + req.connection.remoteAddress);


Express.js: how to get remote client address

If you are running behind a proxy like NGiNX or what have you, only then you should check for 'x-forwarded-for':

var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;

If the proxy isn't 'yours', I wouldn't trust the 'x-forwarded-for' header, because it can be spoofed.

In nginx.conf file:
proxy_set_header X-Real-IP $remote_addr;

In node.js server file:
var ip = req.headers['x-real-ip'] || req.connection.remoteAddress;

note that express lowercases headers

// Get client IP address from request object ----------------------
getClientAddress = function (req) {
        return (req.headers['x-forwarded-for'] || '').split(',')[0] 
        || req.connection.remoteAddress;