-
-
Notifications
You must be signed in to change notification settings - Fork 21.8k
Description
I set up something like this to troubleshoot an issue with "trust proxy":
app.set('trust proxy', ip => {
console.log({ip})
return true
})I noticed that each time I access req.ip from somewhere in the app, {ip} from the "trust proxy" callback was being logged twice. The first was 127.0.0.1 and the second was my load balancer's IP address.
My express app is behind a load balancer and an nginx reverse proxy. So there are two IP addresses in the x-forwarded-for header: the first is my browser's IP, making the request, and the second is the IP of my load balancer. Perhaps that's why it's being called twice?
The issue is that if I test for 127.0.0.1 or just set "trust proxy" to "loopback", "trust proxy" will not be enabled. This is because the first call returns true as expected, but the second call returns false (the load balancer is not a loopback IP).
I also noticed that there's an undocumented second parameter to the "trust proxy" callback. It appears to be set to the return value from the previous call to the "trust proxy" callback (i.e. if the first call returns true, this will be 1; if the first call returns false, this will be 0).
What I'm trying to do is trust traffic that comes through my nginx reverse proxy (i.e. when ip is 127.0.0.1), but that doesn't work as explained above. Is it reliable to use the second parameter and just return true if it is already true?
Also, why is it being called twice? Why is the value of ip for each call to the callback not the same as the values from x-forwarded-for? Would it be beneficial to update the documentation for "trust proxy" to describe this behavior and the second parameter?