Ignat Ospadov Ignat Ospadov - 19 days ago 5
Node.js Question

Express - Accessing Client's IP when Index.html is Requested

I am service static files to the client on request via:

app.use(express.static('public'));


I would like to access the IP address of the client on request of index.html (which is in the public folder). Is it possible to do this by customizing the
express.static
method? If so, how? If it is not, what is the best way to do this?

Edit: I need to do this as a fallback in case HTML5 Geolocation API is not allowed/supported by the client. The IP address is sent to 1 API from which longitude and latitude position are received. Afterwards, the longitude and latitude are sent to a second API to receive the data that is essential to the app I am building. This data will then be served to the client.

Answer

You can use req.ip to get the remote IP address:

req.ip
// => "127.0.0.1"

From the docs: http://expressjs.com/en/api.html#req.ip

Just create a middleware that processes the request before the static route and call next() at the end.

app.use(function (req, res, next) {
  console.log(req.ip);
  next();
});

app.use(express.static('public'));