Express.js is a fast and minimalist web application framework for Node.js. It provides a simple and robust set of features for building web applications and APIs. With Express.js, you can easily handle HTTP requests, define routes, and manage middleware functions. It is known for its flexibility, scalability, and ease of use, making it a popular choice for developing server-side applications in JavaScript. Express.js also has a vibrant ecosystem with a wide range of plugins and extensions that help developers build web applications quickly and efficiently.
Redirecting all requests from HTTP to HTTPS is an important measure for ensuring website security. If your website runs on Node.js and Express, then you can easily enable this feature with the help of middleware.
When creating web applications in Node.js and Express, it is important that all requests are redirected from an unsecured HTTP connection to a secure HTTPS connection. This will ensure that your website is secure and all data sent over the internet is encrypted.
In this tutorial, we will show you how to redirect all requests from HTTP to HTTPS in Node.js and Express.
It starts by creating a middleware for your Express app that will check for a secure connection and redirect if necessary.
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 them always.
Add this block right after const app = express();. If you add it at the end, probably another declared route will response and our block won’t be executed.
// 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