Redirect all requests from HTTP to HTTPS in Node.js and Express

How to redirect all non secure requests to HTTPS in Node.js and Express


Jun 15, 2020
featured image

The first step will be to create a method to guess if the HTTP request comes from HTTP or HTTPS (secure or not secure). In some contexts like AWS or Heroku, you will have to ask by the header x-forwarded-proto instead of req.secure.

Have in mind that req.secure will return always false if there is a load balancer that redirects internally through HTTP. So let's cover both scenarios


/**
 * @param req express http request
 * @returns true if the http request is secure (comes form https)
 */
function isSecure(req) {
  if (req.headers['x-forwarded-proto']) {
    return req.headers['x-forwarded-proto'] === 'https';
  }
  return req.secure;
};

And then add this code in your app.js. Have in mind we are not redirecting to HTTPS if we are in our development or testing environment but you can skip them if you want and redirect always.


// redirect any page form http to https
app.use((req, res, next) => {
  if (process.env.NODE_ENV !== 'development' && process.env.NODE_ENV !== 'test' && !isSecure(req)) {
    res.redirect(301, `https://${req.headers.host}${req.url}`);
  } else {
    next();
  }
});

Now all requests will be redirected to HTTPS if you access through HTTP regardless the full URL

Photo by Artem Beliaikin on Unsplash

nodejs express dev