I am Hack Sparrow
Captain of the Internets.

Node.js get IP Address

Getting a user's IP address seems pretty straightforward in Node.js, right? Does it need a special post on my blog? Yes it does, we'll find out why in a few seconds.

Conventional wisdom says, this is how you would get the IP address from a request:

var ip = req.connection.remoteAddress;

But there is a problem. If you are running your app behind Nginx or any proxy, every single IP addresses will be :D

Probably you can see the problem now. So what is the solution?

Look for the originating IP address in the X-Forwarded-For HTTP header. You will find it in req.header('x-forwarded-for'). Considering that fact, here is the best way to get the IP address of a user:

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

Now you can be sure the variable ip will catch the IP address of the client, not your proxy's.

4 Responses to “Node.js get IP Address”

  1. Arindam says:

    Thanks for the post.

    What is the solution if you are using socket.io (websocket), where you get the remote address as,
    socket.sockets.on(‘connection’, function(client){
    var ip = client.handshake.address.address


  2. Arindam says:

    var ip = client.handshake.headers[‘x-forwarded-for’] || client.handshake.address.address;

    working for me.

    I am properly getting the remote IP address and not

  3. Captain says:


  4. Bernie says:

    What about multiple proxies?
    X-Forwarded-For: OriginatingClientIPAddress, proxy1-IPAddress, proxy2-IPAddress

    Is req.header(‘x-forwarded-for’) an array or a string I need to split?


Make a Comment