Issue
I have a NestJS server that is deployed on an EC2 instance with nginx. I want to get the client ip address from where request is originating but i get "127.0.0.1" as ip in every request no matter where its coming from.
i have tried getting ip directly from request headers and used @Ip decorator from nestjs as well. but still getting same ip.
i have tried setting headers in nginx config as well like this.
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
proxy_pass http://127.0.0.1:5001;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
Solution
In your main.ts
's bootstrap
method, add this line before app.listen()
app.getHttpAdapter().getInstance().set("trust proxy", true);
This will tell express to trust the proxy IPs and allow you to properly use req.ip
or the @Ip()
decorator
Answered By - Jay McDoniel Answer Checked By - Timothy Miller (WPSolving Admin)