In this tutorial, we'll take a quick look at how to get a user' IP address in an Express app.
Here's a snippet of code which you can use to check headers of a Request object in Express to get a user's IP:
const ip =
request.headers['cf-connecting-ip'] ||
request.headers['x-real-ip'] ||
request.headers['x-forwarded-for'] ||
request.socket.remoteAddress || '';
The video goes into a bit more detail but essentially where to get the IP address information from (e.g. which header) depends on the server configuration.
Most likely you'll be running nginx with a proxy so the above code and what we use in the video will work for you.
11 сен 2024