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!
These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.
Heya,
Modify your
proxy.js
to explicitly pass theX-Forwarded-For
header:Using
xfwd: true
ensures thatX-Forwarded-For
,X-Forwarded-Host
, andX-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: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:
For multiple proxies, use an array:
Also, you can change how you extract
req.clientIp
:This ensures:
X-Forwarded-For
contains multiple IPs, it extracts the first IP (which is the real client IP).req.socket.remoteAddress
.