Set trust proxy to the number of proxies in front of your app, then read req.ip.
const express = require("express");
const app = express();
// One reverse proxy (for example a load balancer) sits in front of this app.
app.set("trust proxy", 1);
app.post("/sign/:requestId", express.json(), (req, res) => {
const auditEntry = {
requestId: req.params.requestId,
signedAt: new Date().toISOString(),
ip: req.ip,
userAgent: req.get("user-agent"),
};
// Persist auditEntry alongside the signature record here.
res.json(auditEntry);
});
module.exports = app;
Why this works
Express derives req.ip from the socket's remote address by default, so behind a load balancer every signer appears to come from the proxy. Setting trust proxy to a number tells Express to count that many hops from the right of the X-Forwarded-For header and treat the next address as the client.
Send X-Forwarded-For: 1.2.3.4, 203.0.113.7 with one trusted proxy and req.ip is 203.0.113.7, so the forged leftmost value is ignored. With trust proxy set to true, the same request returns 1.2.3.4.
Caveats
Match the number to your real topology. Express's docs warn that if some paths to your app skip a proxy, a client can supply any value. Count every hop: CDN, load balancer, ingress.
Treat the IP as supporting evidence, not proof of identity. Store it with the timestamp and user agent next to the signature record, and avoid trust proxy set to true unless your outermost proxy overwrites X-Forwarded-For.
Back to All Questions