Step 1: NGINX
Changes in /etc/nginx/conf.d/default.conf
file:
server {
# etc.
location / {
proxy_set_header X-Real-IP $remote_addr;
# etc.
}
}
Step 2: Express middlewares
2.1: IP detector middleware
mws/ip-detector.js
module.exports = function (req, res, next) {
// NOTE: http://code-samples.space/notes/601d00a80883d4603bb0e8ab
req.clientIp = req.headers['x-real-ip']
next()
}
2.2: Consumer middleware for example
mws/geoip-lite.js
const geoip = require('geoip-lite')
module.exports = function (req, res, next) {
if (!!req.clientIp) {
// NOTE: https://www.npmjs.com/package/geoip-lite#looking-up-an-ip-address
req.geo = geoip.lookup(req.clientIp)
}
next()
}
2.3: Server script sample
run.js
const app = require('express')()
const PORT = process.env.PORT ? Number(process.env.PORT) : 3000
const ipDetectorMW = require('./mws/ip-detector')
const geoipLiteMW = require('./mws/geoip-lite')
app.use('*', ipDetectorMW, geoipLiteMW)
// NOTE: For example: const ip = req.clientIp; const geo = req.geo;
server.listen(PORT, (err) => {
if (err) throw err
console.log(`> Ready on http://localhost:${PORT}`)
})