or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-request-ip

A small Node.js module to retrieve the request's IP address

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/request-ip@3.3.x

To install, run

npx @tessl/cli install tessl/npm-request-ip@3.3.0

index.mddocs/

Request IP

Request 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.

Package Information

  • Package Name: request-ip
  • Package Type: npm
  • Language: JavaScript/Node.js
  • Installation: npm install request-ip

Core Imports

const requestIp = require('request-ip');

For ES modules (using dynamic import):

const requestIp = await import('request-ip');

Basic Usage

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);
});

Architecture

Request IP uses a prioritized header checking approach:

  • Header Priority System: Checks headers in a specific order based on reliability and common proxy configurations
  • Fallback Strategy: Falls back to connection-level IP detection when headers are unavailable
  • Framework Support: Works with Express, Connect, Fastify, and other Node.js web frameworks
  • Middleware Integration: Provides both functional API and middleware factory pattern

Capabilities

Client IP Detection

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');
}

X-Forwarded-For Header Parsing

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"

Middleware Factory

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)

Header Priority Order

The getClientIp function checks headers in the following priority order:

  1. x-client-ip - Standard header used by Amazon EC2, Heroku, and others
  2. x-forwarded-for - Load-balancers (AWS ELB) or proxies (parsed via getClientIpFromXForwardedFor)
  3. cf-connecting-ip - Cloudflare
  4. fastly-client-ip - Fastly CDN and Firebase hosting
  5. true-client-ip - Akamai and Cloudflare
  6. x-real-ip - Default nginx proxy/FastCGI
  7. x-cluster-client-ip - Rackspace LB and Riverbed Stingray
  8. x-forwarded - Alternative forwarded header
  9. forwarded-for - Alternative forwarded header
  10. forwarded - RFC 7239 forwarded header
  11. x-appengine-user-ip - Google Cloud App Engine
  12. Connection fallbacks: req.connection.remoteAddress, req.socket.remoteAddress, etc.
  13. cf-pseudo-ipv4 - Cloudflare IPv6 fallback
  14. req.raw - Fastify framework support

Error Handling

// 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);
}

Platform Support

  • Node.js: All versions (compiled from ES6 source)
  • Web Frameworks: Express, Connect, Fastify, and others
  • Cloud Platforms: AWS, Google Cloud, Azure, Heroku
  • CDNs: Cloudflare, Fastly, Akamai
  • Reverse Proxies: Nginx, Apache, HAProxy