Recover client IP information
An Express server runs behind a reverse proxy and must identify the originating client.
Express.js · Const
trust proxy configures whether and how Express trusts a front-facing proxy and its X-Forwarded-* headers. It affects client IP and related request properties.
Set this application option when Express is behind a front-facing proxy and should interpret forwarded connection details. Its value controls which proxy hops are trusted, so Express can derive client IP-related request properties and other proxy-aware values.
app.set('trust proxy', value)| Name | Type | Description |
|---|---|---|
value | Boolean | String | Number | Function | Array | Boolean, string, number, function, or array defining which proxy hops or addresses to trust. |
The configured application setting; its effects are observed through proxy-aware request properties such as req.ip and req.ips.
const express = require('express');
const app = express();
app.set('trust proxy', 'loopback');
app.get('/debug', (req, res) => {
res.json({ ip: req.ip, ips: req.ips, protocol: req.protocol });
});
app.listen(3000);This runnable Express app trusts loopback as a proxy network and exposes the proxy-aware request values.
An Express server runs behind a reverse proxy and must identify the originating client.
A deployment uses known proxy subnets or named private networks.
A fixed proxy chain has a known maximum hop count.
HTTPS termination occurs before requests reach Express.
It is an application setting that tells Express the app is behind a front-facing proxy and permits use of X-Forwarded-* information. It is disabled by default.
Follow-up: What does a numeric value mean? It trusts the nth hop from the front-facing proxy as the client.
A boolean true treats the leftmost forwarded entry as the client, while false treats the app as directly internet-facing and uses the connection's remote address. An IP, subnet, or array limits trust to specified proxy addresses or networks.
Follow-up: Which policy is safer than a blanket true in a known topology? Specify trusted proxy addresses, subnets, or an appropriate hop count.
When enabled, Express derives req.ip and req.ips using the socket address and X-Forwarded-For, stopping at the first untrusted address. It also derives req.hostname from X-Forwarded-Host and reflects X-Forwarded-Proto through req.protocol.
Follow-up: Why must forwarded headers be controlled by the proxy? Because client-controlled headers can otherwise influence these request values.
app.set()req.ipreq.ipsreq.hostnamereq.protocolX-Forwarded-ForX-Forwarded-HostX-Forwarded-Proto