How to force SSL and HTTPS in Express.js?

Sometimes, we want to force SSL and HTTPS in Express.js.

In this article, we’ll look at how to force SSL and HTTPS in Express.js.

How to force SSL and HTTPS in Express.js?

To force SSL and HTTPS in Express.js, we can call res.redirect to redirect to the HTTPS URL if the request wasn’t made with HTTPS.

For instance, we write

const requireHTTPS = (req, res, next) => {
  if (!req.secure && req.get('x-forwarded-proto') !== 'https' && process.env.NODE_ENV !== "development") {
    return res.redirect(`https://${req.get('host')}${req.url}`);
  }
  next();
}

to define the requireHTTPS middleware to check if a secure request isn’t made with

!req.secure && req.get('x-forwarded-proto') !== 'https'

And we check if the environment the app is running in isn’t development with

process.env.NODE_ENV !== "development"

If they’re both true, then we call res.redirect to redirect to the HTTPS URL.

Otherwise, we call next to call the next middleware.

Conclusion

To force SSL and HTTPS in Express.js, we can call res.redirect to redirect to the HTTPS URL if the request wasn’t made with HTTPS.