Build host-aware responses
Generate canonical URLs or host-aware redirects from the incoming request hostname.
Express.js · Pipe
req.hostname returns the request hostname without its port. With proxy trust enabled, Express derives it from X-Forwarded-Host instead of Host.
req.hostname is a read-only request property containing the hostname extracted from the HTTP Host header. If the app trusts the proxy, Express instead derives it from X-Forwarded-Host; with multiple forwarded values, it selects the first value.
req.hostnameA string containing the request hostname, derived from Host or, when proxy trust is enabled, X-Forwarded-Host; the port is stripped.
Host header.X-Forwarded-Host, which may be supplied by the client or proxy; configure proxy trust only for infrastructure you control.X-Forwarded-Host headers do not produce a combined hostname; Express uses the first header.const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.json({ hostname: req.hostname });
});
app.listen(3000);Run the app and request the root path; the response contains the hostname Express derived from the request headers.
Generate canonical URLs or host-aware redirects from the incoming request hostname.
Select tenant or site configuration based on the requested hostname.
Log the hostname associated with an incoming request.
req.hostname return?It is a string property on the Express request object. Normally it contains the hostname from the Host header, with the port excluded.
Follow-up: What changes behind a trusted proxy? Express reads X-Forwarded-Host instead, so proxy trust must match the deployment topology.
req.hostname?When trust proxy does not evaluate to false, Express uses X-Forwarded-Host rather than Host. That header can be set by either the client or the proxy.
Follow-up: How does Express handle multiple forwarded-host values? It uses the first header, and for comma-separated values it uses the first value.
req.hostname differ from req.host?req.hostname is the current property for obtaining the hostname. The related req.host property is a deprecated alias and includes the port-stripped host value described by the documentation.
Follow-up: Which property should new code use? Use req.hostname, not the deprecated req.host alias.
req.hosttrust proxyreq.protocolreq.ipreq.ips