Table Of Contents
Problem
You need to get the actual IP address of clients making requests to your Express.js server, but req.ip
might show proxy or load balancer IPs instead of the real client IP.
Solution
const express = require('express');
const app = express();
// Trust proxy if behind load balancer/reverse proxy
app.set('trust proxy', true);
// Method 1: Using req.ip (recommended)
app.get('/api/ip', (req, res) => {
const clientIP = req.ip;
res.json({
ip: clientIP,
method: 'req.ip'
});
});
// Method 2: Check multiple headers for real IP
app.get('/api/real-ip', (req, res) => {
const clientIP = req.ip ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
(req.connection.socket ? req.connection.socket.remoteAddress : null);
res.json({
ip: clientIP,
headers: {
'x-forwarded-for': req.headers['x-forwarded-for'],
'x-real-ip': req.headers['x-real-ip'],
'x-client-ip': req.headers['x-client-ip']
}
});
});
// Method 3: Custom function for complex scenarios
function getClientIP(req) {
return req.ip ||
req.headers['x-forwarded-for']?.split(',')[0]?.trim() ||
req.headers['x-real-ip'] ||
req.headers['x-client-ip'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
'unknown';
}
app.get('/api/custom-ip', (req, res) => {
const clientIP = getClientIP(req);
res.json({ ip: clientIP, method: 'custom function' });
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Explanation
app.set('trust proxy', true)
tells Express to trust proxy headers like X-Forwarded-For
, which is crucial when behind load balancers or reverse proxies.
req.ip
automatically handles proxy headers when trust proxy is enabled. For complex setups, check multiple headers since different proxies use different header names. The x-forwarded-for
header can contain multiple IPs (comma-separated), so take the first one for the original client IP.
Share this article
Add Comment
No comments yet. Be the first to comment!