How to get client IP address with WebSocket (websockets/ws) library in Node.js?

After a bit of messing around trying to figure out which one gives the client (web browser’s) IP address, the answer is:

ws._socket.remoteAddress

Or if you have access to req via wss.on('connection', (ws, req) => {}):

req.socket.remoteAddress

You can use this, for example, to GeoIP locate where the user is connecting from.

Edit:

If you’re running Node behind an Nginx reverse proxy (or any other reverse proxy for that matter), you may need to use:

req.headers['x-forwarded-for'] || req.socket.remoteAddress

A note on security: If your Node server is available directly as well as through the reverse proxy, you might like to check the remoteAddress before trusting x-forwarded-for. The remote address should be your reverse proxy’s IP. There’s the odd chance someone could call your service directly and spoof x-forwarded-for.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)