I need assistance with the code below which is meant to redirect all http
traffic to https
.
// Implement redirect logic to ensure usage of https in production, staging, and development environments
app.use((req, res, next) => {
// Do not redirect to https if NODE_ENV is 'local', only for deployed server environments
if(!['development', 'staging', 'production'].includes(process.env.NODE_ENV)) return next()
if(!req.secure) {
return res.redirect(301, `https://${req.headers.host}${req.originalUrl}`)
}
next()
})
/**
* Initialize routes
*/
require('./routes')(app)
However, when testing it in the browser with a URL like http://example.com
, I encounter a warning of a redirect loop and observe multiple console.log repetitions in my papertrail logs.
Is there something simple that I am overlooking? Any guidance would be greatly appreciated.