How to get remote client address with Node.js and Express.js?

Sometimes, we want to get remote client address with Node.js and Express.js.

In this article, we’ll look at how to get remote client address with Node.js and Express.js.

How to get remote client address with Node.js and Express.js?

To get remote client address with Node.js and Express.js, we can use the req.headers or req.socket.remoteAddress properties.

For instance, we write

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

to get the client IP address from the x-forwarded-for request header with req.headers['x-forwarded-for'].

If that’s not set, then we use req.socket.remoteAddress to get the client IP address.

Conclusion

To get remote client address with Node.js and Express.js, we can use the req.headers or req.socket.remoteAddress properties.