23
votes

I have my express server running on port 3000 with nginx for the reverse proxy.

req.ip always returns 127.0.0.1 and req.ips returns an empty array

app.enable('trust proxy');

With/without enabling trust proxy, x-forwarded-for doesn't work:

var ip_addr = req.headers['X-FORWARDED-FOR'] || req.connection.remoteAddress;

nginx configuration:

server {
    listen 80;
    server_name localhost;
    access_log /var/log/nginx/dev_localhost.log;

    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

How do i get the IP address of the requesting client?

2
What does your nginx config look like?mscdex
Added nginx configurationwdphd

2 Answers

31
votes

You need to pass the appropriate X-Forwarded-For header to your upstream. Add these lines to your upstream config:

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
8
votes

According to the express documentation:

Express behind proxies

When running an Express app behind a proxy, set (by using app.set()) the application variable trust proxy to one of the values listed in the following table.

You can set it to a boolean, ip address, number or a custom function. If you want to just get the client's proxy to your express app's req.ip, you can just set it to true.

app.set('trust proxy',true); 
app.get("/", (req, res)=>{
    console.log(req.ip); 
});