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

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 context 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 contemplate 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 you 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 Jamie Street on Unsplash

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s