Express provides user’s IP information in the request object. If you are using a reverse proxy in the front of Express web server ( You should in the production server ) you can retrieve the IP address in the x-forwared-for header, assuming you have configured your reverse proxy server correctly.

Here is how you can extract the IP address in the Express router.

const express = require('express');
const app = express();
const router = express.Router();

router.get('/someroute', (req,res) => {
  const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
  console.log(ip); // ip address of the user
});

app.use('/', router);
app.listen(5000);

In order to extract the user’s information such as location, you can use a free node module such as geoip-lite.

Install the module using a node package manager.

npm install --save geoip-lite

To extract location detail, pass the IP of the user in the lookup function.

const express = require('express');
const app = express();
const { lookup } = require('geoip-lite');
const router = express.Router();

router.get('/someroute', (req,res) => {
  const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
  console.log(ip); // ip address of the user
  console.log(lookup(ip)); // location of the user
});

app.use('/', router);
app.listen(5000);

If you are running it in the local machine, you will not be able to get the location data. To test it out, just hardcode your IP address in the ip variable.