I use an HTTP Proxy to host two domains on a single server. I lost visibility to the client’s IP address when I did this. In my proxy.js code, I enable forwarding, i.e., const proxy = httpProxy.createProxyServer({fwd: true }); and in my server, I instruct it to trust the proxy (i.e., app.set(‘trust proxy,’ true); ). I have middleware to retrieve the client IP address: req.clientIp = req.headers[“x-forwarded-for”] || req.socket.remoteAddress.
However, I can only get access to my service provider’s edge IP address. How can I ensure that the client’s IP address is being forwarded?
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Heya,
Modify your proxy.js
to explicitly pass the X-Forwarded-For
header:
const httpProxy = require('http-proxy');
const proxy = httpProxy.createProxyServer({
xfwd: true
});
Using xfwd: true
ensures that X-Forwarded-For
, X-Forwarded-Host
, and X-Forwarded-Proto
are included in the request.
You already have app.set('trust proxy', true);
in your Express app, but it may not be strict enough. Try setting it explicitly:
app.set('trust proxy', 'loopback');
If your proxy and backend are on the same machine, this ensures only loopback connections are trusted.
If your proxy is on a different server, set a specific IP address:
app.set('trust proxy', '192.168.1.100');
For multiple proxies, use an array:
app.set('trust proxy', ['192.168.1.100', '192.168.1.101']);
Also, you can change how you extract req.clientIp
:
app.use((req, res, next) => {
const forwarded = req.headers['x-forwarded-for'];
req.clientIp = forwarded ? forwarded.split(',')[0].trim() : req.socket.remoteAddress;
console.log(`Client IP: ${req.clientIp}`);
next();
});
This ensures:
X-Forwarded-For
contains multiple IPs, it extracts the first IP (which is the real client IP).req.socket.remoteAddress
.Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.