HTTP X-Forwarded-For Header Parser

0.2.0 · maintenance · verified Tue Apr 21

The `forwarded` package is a minimalist Node.js utility designed to robustly parse the `X-Forwarded-For` HTTP header. It extracts a list of IP addresses from the request, including the direct socket address, and returns them in reverse proxy order, where index `0` represents the immediate client (the socket address) and the last index is the furthest origin (typically the end-user's IP). This is crucial for applications running behind proxies or load balancers, where `req.ip` or `req.connection.remoteAddress` would only reflect the proxy's IP. The current stable version is 0.2.0, released in May 2021. Being part of the `jshttp` organization, `forwarded` adheres to a philosophy of creating small, single-purpose, and highly performant modules. Its release cadence is exceptionally slow, with only four releases since its initial launch in 2014, which underscores its stability and the mature nature of its functionality. It has no external runtime dependencies, making it a lightweight and reliable choice for foundational HTTP parsing tasks.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to use the `forwarded` function with a mock HTTP request object, showing how it parses the `X-Forwarded-For` header and includes the socket's remote address in the correct reverse proxy order, even when the header is absent.

import forwarded from 'forwarded';

const mockRequest = {
  headers: {
    'x-forwarded-for': '203.0.113.195, 70.41.3.18, 150.172.238.1'
  },
  socket: {
    remoteAddress: '192.0.2.4'
  }
};

const addresses = forwarded(mockRequest);

console.log('Parsed addresses (reverse proxy order):', addresses);
// Expected output: ['192.0.2.4', '150.172.238.1', '70.41.3.18', '203.0.113.195']

const mockRequestWithoutHeader = {
  headers: {},
  socket: {
    remoteAddress: '10.0.0.1'
  }
};

const addressesNoHeader = forwarded(mockRequestWithoutHeader);
console.log('Addresses without X-Forwarded-For:', addressesNoHeader);
// Expected output: ['10.0.0.1']

view raw JSON →