Node.js: Get client's IP

req.ip is the straightforward way to get the client's IP address in Express. You can see the logic it uses (which involves grabbing the first item from the array of proxy addresses req.ips, where that array is constructed from the x-forwarded-for headers) here.


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

As other's have noted, due to the use potential use of proxies, you really should use req.ip and NOT use the X-Forwarded-For header like so many people are recommending. As long as you properly configure a proxy as a trusted proxy, req.ip will always return the end-user's IP address.

e.g. If you had a proxy that was connecting from 8.8.8.8, you'd do:

var express = require('express');
var app = express();
app.set('trust proxy', '8.8.8.8');

Since you trust the proxy, this would now make it so what is passed in the X-Forwarded-For header will be stored in req.ip, but ONLY if it originates from one of the trusted proxies.

More on trust proxy can be found here.

Now, as others have noted in the comments; especially when developing locally you may get the ip in the format of "::ffff:127.0.0.1".

To always get the IPv4 Address I have:

getClientAddress = function (req) {
    return req.ip.split(":").pop();
};