Categories
JavaScript Answers

How to force SSL and HTTPS in Express.js?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *