Beginner LevelExpress JS
How do you retrieve the client IP address using req.ip and trust proxy settings?
❓ Interview Prompt: Explain req.ip, X-Forwarded-For headers, and configuring app.set("trust proxy", 1) behind reverse proxies.
Accessing 'req.ip' retrieves the client's IP address.
The Reverse Proxy Problem:
When Express runs behind a reverse proxy (NGINX, Cloudflare, AWS ALB), 'req.ip' will return the proxy server's internal IP address by default!
Solution:
Configure 'app.set("trust proxy", 1)' to instruct Express to read the client's true remote IP address from the 'X-Forwarded-For' HTTP header sent by the reverse proxy.
Code Implementation Example
javascript
import express from 'express';
const app = express();
// Instruct Express to trust the first hop reverse proxy (e.g. NGINX or AWS ALB)
app.set('trust proxy', 1);
app.get('/api/client-ip', (req, res) => {
// req.ip now contains the true remote client IP address!
res.json({ clientIp: req.ip });
});💡Extracting client IP address behind reverse proxies using trust proxy.
🎯 Interview Key Takeaway
Set app.set("trust proxy", 1) when running behind NGINX or AWS ALB so req.ip returns the true client IP address.
#req.ip#trust proxy#Reverse Proxy#Beginner
Back to all Express JS Questions→