Reverse proxies & trust in expressjs

advance · Express.js — Web APIs & middleware

In a production environment, an Express application rarely talks directly to the internet. Instead, it typically sits behind a Reverse Proxy , such as Nginx or an AWS Application Load Balancer. This setup provides security and performance benefits but changes how the application perceives client data. 1. The Theory: What is a Reverse Proxy? Theory: A reverse proxy is an intermediary server that receives client requests and forwards them to the internal web server. Security: It masks the internal IP address of the application server. SSL Termination: It handles HTTPS encryption, allowing the Node.js application to process standard HTTP and save CPU resources. Load Balancing: It distributes incoming traffic across multiple instances of the application. 2. The "Trust" Problem Theory: When a request passes through a proxy, the req.ip detected by Express is the IP of the Proxy rather than the actual user. The Consequence: Security features like rate limiting will mistakenly identify all users as a single entity (the proxy) and potentially block all traffic. The Solution: Proxies attach an X-Forwarded-For header containing the original user's IP. However, Express ignores this header by default to prevent "IP spoofing," where an attacker fakes their identity. 3. Configuring trust proxy in Express Theory: You must explicitly tell Express to trust the proxy so it accurately reads the X-Forwarded-* headers. const express = require('express'); const app = express(); // Enabling trust so Express reads X-Forwarded-For headers app.set('trust proxy', 1); // '1' represents the number of trusted hops (e.g., Nginx) app.get('/check-ip', (req, res) => {   // Shows the real user IP instead of the proxy IP   res.send(`Your IP is: ${req.ip}`);  }); 4. Security Risks of Misconfiguration Theory: Setting trust proxy to true globally is a significant security risk. IP Spoofing: If you trust any proxy, a malicious actor can send a fake X-Forwarded-For header to bypass security protocols. Access Control: Attackers could gain unauthorized access by pretending to be a whitelisted internal IP. Best Practice: Only trust the specific number of "hops" or the known static IP addresses of your load balancers.

Back to Express.js — Web APIs & middleware

Browse all study material on Careeroza