How to fetch Client-IP from cloudfront in the NODE.JS application, when the AWS EC2 has Nginx server in between?
My suggestion would be to use CloudFront provided headers, link - [https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-cloudfront-headers.html]
All you need to do first is Go to Cloudfront -> Select Distribution -> Behaviors -> and do the following in 'Cache key and origin requests'
Select 'CachingDisabled' for 'Cache policy' dropdown, if you don't want anything to get cached. I personally faced problems in my app, if I didn't select this option.
For Origin Request Policy do the following -
Create a new Policy like 'Origin-Policy-For-Cloudfront' and select 'CloudFront-Viewer-Address' and checkout other options as well.
It'll look something like this -
server {
listen 80;
server_name my-server CLOUDFRONT_URL;
location / {
proxy_set_header X-Client-IP $http_CloudFront_Viewer_Address;
proxy_set_header Host $http_host;
proxy_pass "http://127.0.0.1";
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
}
}
On the NodeJs Backend, you can fetch the Client IP in the request as follows -
exports.get = (req, res, next) => {
console.log('Client IP:', req.headers['x-client-ip']);
}
This is an easier method to get the client Ip rather than messing around with Cloudfront CIDR IP ranges and all.