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 😀

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.

6 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?


  5. LandonPowell says:

    The X-FORWARDED-FOR for an IP!? You’re using a header to get an IP, you moron. Those can be spoofed with browser plugins. You can literally set your X-FORWARDED-FOR to any string. I’ve got mine set to it.stings.when.ip, and used to have it set to ‘ OR ” == 1. You should change your blog’s name from hacksparrow to hackedsparrow, because you’re obviously security illiterate.

  6. Ronnie Garcia says:

    Landon, you’re a total neckbeard. People at work (if you have a job) might like you more if you present information in a more constructive way instead of calling people morons. If I was your manager, you’d be fired immediately.

Make a Comment