Express.js: Getting Client IP Behind Proxies

· 2 min read · 264 Words · -Views -Comments

In real projects you may run into corporate networks that sit behind multiple proxies. When I grabbed the IP address on the server, the value sometimes came back empty.

Here’s what happens: once the app trusts a proxy, calling req.ip should give you the real client IP. The proxy, however, is free to modify the X-Forwarded-For header. In my case the proxy rewrote the header and stripped out the client IP, so req.ip returned nothing. We can’t recover the true client address once it’s been removed, but we can still capture the proxy’s IP. I wrapped a helper to do exactly that:

/**
 * Get the requester IP address.
 * req.ips looks like ["client", "proxy1", "proxy2"].
 * Prefer the real client IP, or fall back to the proxy closest to the client.
 */
util.getClientIP = function (req) {
    let ip = req.ip;
    if (!ip) {
        for (let item in req.ips) {
            if (item) {
                ip = item;
                break;
            }
        }
        logger.info('req.ips');
        logger.info(JSON.stringify(req.ips));
    }
    return ip;
};

This fills the gap when req.ip alone returns empty.

You could disable proxy trust, but then you would only ever see the direct client IP and never any proxy hops. Whether you enable trust depends on your deployment environment.

app.enabled('trust proxy')

When trust proxy is enabled, Express reads the IP addresses attached by the upstream proxies.

req.ip

Use req.ip to fetch the requestor’s IP. When trust proxy is enabled, Express pulls the leftmost value from the X-Forwarded-For header.

req.ip
// => "127.0.0.1"

req.ips

With trust proxy enabled, req.ips becomes an array of IP addresses, e.g. ["client", "proxy1", "proxy2"].

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover