A small Node.js module to retrieve the request's IP address
npx @tessl/cli install tessl/npm-request-ip@3.3.0Request IP is a small Node.js module for retrieving a request's IP address from HTTP requests. It systematically checks various HTTP headers and connection properties to determine the client's real IP address, handling proxy configurations, CDN scenarios, and various web server environments.
npm install request-ipconst requestIp = require('request-ip');For ES modules (using dynamic import):
const requestIp = await import('request-ip');const requestIp = require('request-ip');
// Inside middleware handler
const ipMiddleware = function(req, res, next) {
const clientIp = requestIp.getClientIp(req);
console.log('Client IP:', clientIp);
next();
};
// As Connect/Express middleware
app.use(requestIp.mw());
app.use(function(req, res) {
const ip = req.clientIp;
res.end(ip);
});Request IP uses a prioritized header checking approach:
Core functionality for extracting client IP addresses from HTTP request objects.
/**
* Determine client IP address from request object
* @param {Object} req - HTTP request object
* @returns {string|null} Client IP address or null if not found
*/
function getClientIp(req);Usage Example:
const requestIp = require('request-ip');
// Basic usage
const ip = requestIp.getClientIp(req);
if (ip) {
console.log('Client IP:', ip);
} else {
console.log('Unable to determine client IP');
}Specialized function for parsing X-Forwarded-For headers which may contain multiple IP addresses.
/**
* Parse x-forwarded-for headers to extract first valid IP
* @param {string} value - The header value to be parsed
* @returns {string|null} First known IP address, if any
* @throws {TypeError} When value is not a string
*/
function getClientIpFromXForwardedFor(value);Usage Example:
const requestIp = require('request-ip');
// Parse X-Forwarded-For header manually
const forwardedHeader = req.headers['x-forwarded-for'];
if (forwardedHeader) {
const ip = requestIp.getClientIpFromXForwardedFor(forwardedHeader);
console.log('Parsed IP:', ip);
}
// Handle multiple IPs in header
const multipleIps = "203.0.113.195, 70.41.3.18, 150.172.238.178";
const firstValidIp = requestIp.getClientIpFromXForwardedFor(multipleIps);
// Returns: "203.0.113.195"Creates Express/Connect middleware that automatically adds client IP to request objects as a computed property.
/**
* Create middleware that adds client IP to request object as a computed property
* @param {Object} [options] - Configuration options
* @param {string} [options.attributeName='clientIp'] - Property name to add to request
* @returns {Function} Middleware function (req, res, next) => void
* @throws {TypeError} When options is not an object
* @note Uses Object.defineProperty with getter - IP is computed on each access
*/
function mw(options);Usage Examples:
const requestIp = require('request-ip');
const express = require('express');
const app = express();
// Default usage - adds req.clientIp
app.use(requestIp.mw());
app.get('/', (req, res) => {
res.send(`Your IP is: ${req.clientIp}`);
});
// Custom attribute name
app.use(requestIp.mw({ attributeName: 'userIp' }));
app.get('/user', (req, res) => {
res.send(`User IP: ${req.userIp}`);
});
// Note: The IP property is computed on each access via getter
// Multiple accesses to req.clientIp will re-run getClientIp(req)The getClientIp function checks headers in the following priority order:
x-client-ip - Standard header used by Amazon EC2, Heroku, and othersx-forwarded-for - Load-balancers (AWS ELB) or proxies (parsed via getClientIpFromXForwardedFor)cf-connecting-ip - Cloudflarefastly-client-ip - Fastly CDN and Firebase hostingtrue-client-ip - Akamai and Cloudflarex-real-ip - Default nginx proxy/FastCGIx-cluster-client-ip - Rackspace LB and Riverbed Stingrayx-forwarded - Alternative forwarded headerforwarded-for - Alternative forwarded headerforwarded - RFC 7239 forwarded headerx-appengine-user-ip - Google Cloud App Enginereq.connection.remoteAddress, req.socket.remoteAddress, etc.cf-pseudo-ipv4 - Cloudflare IPv6 fallbackreq.raw - Fastify framework support// TypeError exceptions
class TypeError extends Error {
// Thrown by getClientIpFromXForwardedFor when value is not a string
// Thrown by mw when options is not an object
}Error Examples:
const requestIp = require('request-ip');
try {
// This will throw TypeError: Expected a string, got "number"
requestIp.getClientIpFromXForwardedFor(123);
} catch (error) {
console.error('Invalid input:', error.message);
}
try {
// This will throw TypeError: Options must be an object!
const middleware = requestIp.mw("invalid");
} catch (error) {
console.error('Invalid options:', error.message);
}