Make all HTTP Requests to HTTPS Using Express & NodeJs

Time to secure your web applications by adding S after HTTP! austin-distel-21GWwco-JBQ-unsplash.jpg Photo by Austin Distel on Unsplash

Ever thought of what does a single S does to your web application?

Indeed it can do a lot!!! Many of us create some beautiful web applications while learning web development and deploy them online. Agree with it or not everybody have that excitement to showcase our work with our friends. Before giving the link to your application ensure it is an HTTPS site. If your app is user interactive then it must be HTTPS. otherwise, any script kiddie(not even a hacker! lol) can tamper with your data and see what's going around.

Now let us get into Actual lines that can add the extra S to our site.

Before proceeding further I am assuming you are using the Express server for your application.

The basic express server will look like

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log('Hey this a simple Express server!')
})

And Here comes the magical function to convert HTTP request to HTTPS

app.enable('trust proxy');

app.use (function (req, res, next) {
    if (req.secure) { 
            // request was via https, so do no special handling
            next();
    } else {
            // request was via http, so redirect to https.
            res.redirect('https://' + req.headers.host + req.url);
    }
});

add the above lines after creating the app

The final code will look like

const express = require('express');

const app = express();

app.enable('trust proxy');

app.use (function (req, res, next) {
    if (req.secure) {
            // request was via https, so do no special handling
            next();
    } else {
            // request was via http, so redirect to https.
            console.log('https://' + req.headers.host + req.url+'------------');
            res.redirect('https://' + req.headers.host + req.url);
    }
});
app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log('Hey this a simple Express server!')
})

Tada!!! All the HTTP request now will be redirected to HTTPS. Simple right :)

So, from now onwards always ensure you add this function to your express server before you deploy them online 😉

This is my first post😃. Suggestions are welcomed😉.