Introduction
The @supercharge/request-ip
package provides a function to retrieve a request’s IP address.
Installation
npm i @supercharge/request-ip
Usage
const RequestIp = require('@supercharge/request-ip')
const ip = RequestIp.getClientIp(request)
Depending on your used web framework, you may use it in a middleware or route handler:
simple Express example
const { getClientIp } = require('@supercharge/request-ip')
const expressMiddleware = function (req, res, next) {
req.ip = getClientIp(req)
next()
}
simple hapi route handler example:
const Hapi = require('@hapi/hapi')
const { getClientIp } = require('@supercharge/request-ip')
const server = new Hapi.Server({
host: 'localhost'
})
server.route({
method: 'GET',
path: '/login',
handler: (request, h) => {
const ip = getClientIp(request)
return h.response(ip)
}
})
Detecting the IP Address
The client’s IP address may be stored in different locations of the request instance varying between services.
Here’s the order of locations in which the packages searches for the requesting IP address:
- Checks HTTP request headers
x-forwarded-for
: this header may contain multiple IP address for (client/proxies/hops). This package extracts and returns the first IP address.x-forwarded
, forwarded
, forwarded-for
as variants from x-forwarded-for
possibly configured by proxiesx-client-ip
possibly configured by nginxx-real-ip
possibly configured in nginxcf-connecting-ip
from Cloudflarefastly-client-ip
from Fastly and Firebasetrue-client-ip
from Akamai and Cloudflarex-cluster-client-ip
from Rackspace
- Checks the HTTP connection in
request.connection
and request.connection.socket
- Checks the HTTP socket in
request.socket
- Checks the HTTP info in
request.info
- Checks the raw HTTP request instance in
request.raw
- Checks the request context used by AWS API Gateway/Lambda in
request.requestContext
Credits
A huge thank you to Petar Bojinov for his request-ip package. I was using Petar’s package for two years in my hapi-rate-limitor plugin. It seems Petar is busy with other work and I felt the need to create my own package providing the functionality to retrieve a request’s IP address.
Contributing
Do you miss a way to find the request’s IP? We very much appreciate your contribution! Please send in a pull request 😊
- Create a fork
- Create your feature branch:
git checkout -b my-feature
- Commit your changes:
git commit -am 'Add some feature'
- Push to the branch:
git push origin my-new-feature
- Submit a pull request 🚀
License
MIT © Supercharge
superchargejs.com ·
GitHub @supercharge ·
Twitter @superchargejs