request-ip

repository·master·Indexed 21 days ago

https://github.com/pbojinov/request-ip

A lightweight Node.js module (v3.3.0) to reliably retrieve a client's IP address from an incoming request. It supports manual extraction via getClientIp() and can be used as Connect or Express middleware via mw() to attach the IP to the request object. The module accounts for various proxy headers and environments, including Cloudflare, Fastly, Akamai, Nginx, and Google App Engine, by checking headers like X-Forwarded-For and X-Real-IP in a prioritized order.

Tokens
2.3K
Snippets
9
Records
10
Agent score
72%

What's inside request-ip

  1. How request-ip determines the client IP

    master

    The module determines the user's IP by checking specific request headers in a prioritized order. If no IP can be found, it returns null.

    The lookup order is:

    1. X-Client-IP
    2. X-Forwarded-For (Takes the first IP in a comma-separated list)
    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 (Nginx proxy/FastCGI)
    7. X-Cluster-Client-IP (Rackspace LB, Riverbed Stingray)
    8. X-Forwarded, Forwarded-For and Forwarded (Variations of #2)
    9. appengine-user-ip (Google App Engine)
    10. req.connection.remoteAddress
    11. req.socket.remoteAddress
    12. req.connection.socket.remoteAddress
    13. req.info.remoteAddress
    14. Cf-Pseudo-IPv4 (Cloudflare fallback)
    15. request.raw (Fastify)
  2. Retrieve client IP using getClientIp()

    master

    You can manually retrieve the client's IP address from a request object by calling requestIp.getClientIp(req). This is useful when you want to extract the IP inside a custom middleware handler without attaching it to the request object.

    const requestIp = require('request-ip');
    
    // inside middleware handler
    const ipMiddleware = function(req, res, next) {
        const clientIp = requestIp.getClientIp(req); 
        next();
    };
  3. Use request-ip as Connect Middleware

    master

    To automatically attach the client IP to the request object, use requestIp.mw() as middleware in your Express or Connect application. Once applied, the IP address is accessible via req.clientIp.

    const requestIp = require('request-ip');
    
    // Use as middleware
    app.use(requestIp.mw());
    
    app.use(function(req, res) {
        const ip = req.clientIp;
        res.end(ip);
    });
  4. Get the client IP with getClientIp()

    master

    Use getClientIp(req) to extract the client's IP address from a request object. The function inspects various headers and connection properties in a specific order of precedence to find a valid IP address.

    It checks the following headers (in order):

    1. x-client-ip
    2. x-forwarded-for (parsed via getClientIpFromXForwardedFor)
    3. cf-connecting-ip (Cloudflare)
    4. fastly-client-ip (Fastly)
    5. true-client-ip
    6. x-real-ip
    7. x-cluster-client-ip
    8. x-forwarded
    9. forwarded-for
    10. forwarded
    11. x-appengine-user-ip (Google App Engine)
    12. Cf-Pseudo-IPv4 (Cloudflare)

    If no valid header is found, it falls back to checking connection properties like req.connection.remoteAddress, req.socket.remoteAddress, req.info.remoteAddress, or req.requestContext.identity.sourceIp.

    const { getClientIp } = require('request-ip');
    
    // Example usage in an Express-like environment
    app.get('/', (req, res) => {
      const ip = getClientIp(req);
      console.log('Client IP:', ip);
      res.send(`Your IP is ${ip}`);
    });
  5. Parse x-forwarded-for headers with getClientIpFromXForwardedFor()

    master

    Use getClientIpFromXForwardedFor(value) to parse the X-Forwarded-For header string.

    This function handles the standard format "client IP, proxy 1 IP, proxy 2 IP" by attempting to find the first valid IP address in the list. It also handles cases where IPs might include ports (e.g., ip:port) by stripping the port, and it skips non-IP values like "unknown".

    • Input: A string representing the header value.
    • Returns: The first valid IP address found as a string, or null if no valid IP is present.
    • Throws: TypeError if the input is not a string.
    const { getClientIpFromXForwardedFor } = require('request-ip');
    
    const headerValue = '203.0.113.195, 70.41.3.18, 150.172.238.178';
    const clientIp = getClientIpFromXForwardedFor(headerValue);
    // clientIp === '203.0.113.195'
  6. Determine client IP with getClientIp()

    master

    Use getClientIp(req) to extract the originating client's IP address from a request object. The function implements a priority-based search through various HTTP headers used by different cloud providers and proxies, including:

    • x-client-ip (Amazon EC2, Heroku)
    • x-forwarded-for (AWS ELB, proxies)
    • cf-connecting-ip (Cloudflare)
    • do-connecting-ip (DigitalOcean)
    • fastly-client-ip (Fastly, Firebase)
    • true-client-ip (Akamai, Cloudflare)
    • x-real-ip (Nginx)
    • x-cluster-client-ip (Rackspace, Riverbed)
    • x-appengine-user-ip (Google Cloud App Engine)
    • Cf-Pseudo-IPv4 (Cloudflare fallback)

    It also checks remote address properties on req.connection, req.socket, req.info, and req.requestContext.identity.sourceIp (AWS API Gateway + Lambda). For Fastify users, it can recursively call itself on req.raw.

    Returns the IP address as a string if found, or null if the IP cannot be determined.

    const { getClientIp } = require('request-ip');
    
    // Example usage in an Express-like environment
    function handleRequest(req, res) {
        const ip = getClientIp(req);
        console.log(`Client IP: ${ip}`);
        res.send(`Your IP is ${ip}`);
    }
  7. Use request-ip as middleware

    master

    The mw(options) function returns a middleware function that augments the request object with the detected client IP address.

    Configuration

    Pass an options object to mw():

    • options.attributeName (string, optional): The name of the property to add to the req object. Defaults to 'clientIp'.

    Behavior

    The middleware calculates the IP using getClientIp(req) and defines it as a getter on the request object using Object.defineProperty. This ensures the property is configurable: true.

    Example

    const express = require('express');
    const { mw } = require('request-ip');
    
    const app = express();
    
    // Use default attribute name 'clientIp'
    app.use(mw());
    
    // Or use a custom attribute name
    app.use(mw({ attributeName: 'ipAddress' }));
    
    app.get('/', (req, res) => {
        // Access via the default name
        console.log(req.clientIp);
        
        // Access via custom name if configured
        // console.log(req.ipAddress);
        
        res.send('IP logged');
    });
    const { mw } = require('request-ip');
    
    // Standard Express middleware usage
    app.use(mw());
    
    // Custom attribute name usage
    app.use(mw({ attributeName: 'myCustomIpField' }));
  8. Use request-ip as middleware with mw()

    master

    The mw(options) function returns a middleware function that attaches the detected client IP to the req object.

    Options

    • attributeName (string): The name of the property to attach to the req object. Defaults to 'clientIp'.

    If options is provided but is not an object, it throws a TypeError.

    Usage

    const requestIp = require('request-ip');
    const express = require('express');
    const app = express();
    
    // Use default attribute name 'clientIp'
    app.use(requestIp.mw());
    
    // Or use a custom attribute name
    app.use(requestIp.mw({ attributeName: 'ip' }));
    
    app.get('/', (req, res) => {
      // Access the IP via the attribute name defined in middleware
      const ip = req.clientIp;
      res.send(ip);
    });
    const requestIp = require('request-ip');
    const express = require('express');
    const app = express();
    
    app.use(requestIp.mw({ attributeName: 'clientIp' }));
    
    app.get('/', (req, res) => {
      const ip = req.clientIp;
      res.send(ip);
    });
  9. Parse X-Forwarded-For with getClientIpFromXForwardedFor()

    master

    The getClientIpFromXForwardedFor(value) function parses the X-Forwarded-For header string. It splits the string by commas, trims whitespace, and returns the first valid IP address found in the list.

    If the value is not a string, it throws a TypeError. If no valid IP is found, it returns null.

    const { getClientIpFromXForwardedFor } = require('request-ip');
    
    const header = '192.168.1.1, 10.0.0.1';
    const ip = getClientIpFromXForwardedFor(header);
    // returns '192.168.1.1'