Enforcing HTTPS in Express.js
When a website runs on HTTPS but loads resources (scripts, images, styles) over HTTP, browsers flag it as “mixed content,” causing security warnings or blocking requests. This approach improves security, and enhances SEO ranking.
const express = require("express");
const app = express();
// Middleware to redirect HTTP to HTTPS
app.use((req, res, next) => {
if (!req.secure) {
return res.redirect(301, "https://" + req.headers.host + req.url);
}
next();
});
app.listen(3000, () => console.log("Server running on port 3000"));