Course contentsShow
← Node.js
Lesson 543 of 1,9806. Networking and HTTP FundamentalsFree lesson

Proxy Behavior and X-Forwarded-For

Extract original client IP addresses when Node.js is deployed behind a reverse proxy like Nginx.

In this lesson, you will learn how to identify the true source IP address of a client when your Node.js application is hidden behind a reverse proxy like Nginx.

The Proxy Identity Crisis

When a user visits your website, they don’t always connect directly to your Node.js server. Often, they connect to a "reverse proxy" (like Nginx) which then forwards the request to your application.

From the perspective of your Node.js http server, the connection is coming from the proxy's IP address, not the user's. If you check request.socket.remoteAddress, you will only ever see the local address of the proxy. This makes logging, security filtering, and geo-location impossible.

Using the X-Forwarded-For Header

To solve this, proxies are configured to add a special HTTP header to the request: X-Forwarded-For (XFF). When the proxy forwards the request to you, it appends the original user's IP address to this header.

The X-Forwarded-For header is a comma-separated list. If a request passes through multiple proxies, the list grows: client-ip, proxy1-ip, proxy2-ip. The first IP in that list is usually the original client.

Implementation Logic

In your Node.js code, you can extract this information by inspecting the headers:

const http = require('http');

http.createServer((req, res) => {
  // Check for the X-Forwarded-For header
  const forwarded = req.headers['x-forwarded-for'];
  
  // If the header exists, the first IP is the client
  const clientIp = forwarded ? forwarded.split(',')[0] : req.socket.remoteAddress;

  console.log(`Request received from: ${clientIp}`);
  res.end('IP identified.');
}).listen(3000);

A Note on Trust

Be cautious! Because headers are just text, a malicious user could spoof the X-Forwarded-For header by sending their own value. Always ensure your Node.js server only accepts these headers from your trusted proxy, and configure your proxy to overwrite any incoming X-Forwarded-For header from the client to prevent header injection.

Key Takeaway: Since a proxy masks the true origin of a request, you must look to the X-Forwarded-For header to recover the original client's IP address.