Course contentsShow
← Node.js
Lesson 663 of 1,9807. Web Framework Architecture and MiddlewareFree lesson

Proxy-Aware Request Handling

Properly extract client IP addresses and protocol information when behind reverse proxies like Nginx.

In this lesson, you will learn how to accurately identify a client’s true IP address and protocol when your Node.js application sits behind a reverse proxy like Nginx or HAProxy.

Why Proxies Break Identification

When you deploy a Node.js application, it rarely sits directly on the open internet. Instead, it usually hides behind a reverse proxy. When a user sends a request, the proxy receives it first and then forwards it to your server.

By default, your Node.js code sees the proxy's IP address rather than the user's IP. Furthermore, if the user connects via HTTPS to the proxy, but the proxy communicates with your Node.js app over plain HTTP, your server might mistakenly think the entire request is insecure.

Trusted Headers

To solve this, proxies pass the original information in special HTTP headers. The most common is X-Forwarded-For (for the client's IP) and X-Forwarded-Proto (for the original protocol, like 'https').

However, you cannot blindly trust these headers! A malicious user could send their own X-Forwarded-For header to spoof their IP address. To handle this safely, you must tell your application which proxies you trust.

Implementation Example

In an Express-based architecture, you enable "proxy trust" to allow the framework to correctly parse these headers:

// Enable proxy trust to allow detection of X-Forwarded-* headers
// 'loopback' trusts the proxy if it's running on the same machine
app.set('trust proxy', 'loopback');

app.use((req, res, next) => {
  // Now req.ip reflects the real user, not the proxy
  console.log('Client IP:', req.ip);
  
  // Now req.secure correctly reports true if the user used HTTPS
  console.log('Is Secure:', req.secure);
  
  next();
});

By configuring trust proxy, the framework automatically sanitizes the header values, ensuring that req.ip contains the genuine client IP address rather than a spoofed value. This is critical for everything from rate limiting to security logging, as it ensures your middleware stack acts on the actual source of the request.

Key Takeaway: Always configure your framework to trust your specific proxy infrastructure so that your application can safely extract original client metadata from forwarded headers.