Express req.protocol Property
What you’ll learn
- How
req.protocolreportshttpvshttps. - How reverse proxies and
trust proxyaffect protocol detection. - How to use
req.securefor HTTPS-only logic. - How to build absolute URLs using request protocol data.
Usage syntax
javascript
req.protocol
req.secure1
Redirect HTTP traffic to HTTPS
javascript
app.use(function (req, res, next) {
if (!req.secure) {
return res.redirect('https://' + req.get('host') + req.originalUrl);
}
next();
});2
Build absolute URL from request
javascript
app.get('/self', function (req, res) {
var url = req.protocol + '://' + req.get('host') + req.originalUrl;
res.send(url);
});❓ FAQ
It indicates the request protocol, typically http or https.
Express uses connection info and, with trust proxy enabled, forwarded protocol headers.
req.secure is a boolean shortcut equivalent to req.protocol === 'https'.
Usually trust proxy is not configured, so Express cannot trust forwarded protocol headers.
Yes, combine req.protocol with req.get('host') for full URL generation.
Did you know?
req.protocol returns http or https; behind proxies it depends on proper trust proxy configuration.
4 people found this page helpful
