Generate protocol-aware URLs
Choose secure or non-secure URL construction based on the incoming request.
Express.js · Pipe
req.protocol gives the request’s protocol as http or https. With proxy trust enabled, Express can derive it from X-Forwarded-Proto.
req.protocol is a read-only request property containing the protocol used for the request. It normally reports http or https; if proxy trust is enabled, Express may instead use the X-Forwarded-Proto header when that header is present.
req.protocolString: http or https for TLS requests; with a non-false trust proxy setting, the present X-Forwarded-Proto value is used.
http for ordinary requests and https when the request uses TLS.const express = require('express');
const app = express();
app.get('/scheme', (req, res) => {
res.json({ protocol: req.protocol });
});
app.listen(3000);Run the server and request /scheme; the response reports the request protocol, such as http.
Choose secure or non-secure URL construction based on the incoming request.
Apply behavior that differs for TLS and non-TLS requests.
Inspect the protocol seen by an Express app behind a reverse proxy.
req.protocol return?req.protocol contains the request protocol as a string: http or https for TLS requests. It is useful when application behavior depends on whether a request arrived securely.
Follow-up: How can proxy deployment change it? When trust proxy does not evaluate to false, Express uses X-Forwarded-Proto if present.
trust proxy affect req.protocol?With proxy trust enabled, Express checks X-Forwarded-Proto when that header is present. The header may be supplied by either the client or the proxy, so the trust configuration must match the deployment topology.
Follow-up: What security concern follows? An incorrectly trusted proxy configuration can allow an untrusted client to influence the value observed by the application.
The property is a string rather than a Boolean. To test for a TLS request, compare it with https, for example req.protocol === 'https'.
Follow-up: What related request property can be used for the same TLS check? req.secure is the Boolean equivalent documented by Express.
req.securereq.get()req.hostnameapp.set('trust proxy')