0

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.

  • Possible duplicate of [How to get client's IP address using javascript only?](http://stackoverflow.com/questions/391979/how-to-get-clients-ip-address-using-javascript-only) – jmargolisvt Nov 18 '16 at 21:26
  • @jmargolisvt Definitely not a duplicate. I need to get the IP address of the client that is requesting the index.html file to make a request to a third-party API and serve that API's response data along with the index.html file. The IP address is needed for geolocation which is passed on to the API. This is a fallback in case the html5 geolocation API is not allowed by the client. –  Nov 18 '16 at 21:33
  • @Ignat If you are saying you want to inject the ip or the location on to the index.html page then you are not serving a static page at that point. You will need a template that has a placeholder for where that information will go. – Ryan Nov 18 '16 at 22:15

1 Answers1

0

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'));
kevintechie
  • 1,441
  • 1
  • 13
  • 15
  • Yes, that is indeed the way to access the ip address. The problem is that how do you access it when you only have the `app.use(express.static('public'));`? –  Nov 18 '16 at 21:51