d
Amit DhamuSoftware Engineer
 

Redirect to HTTPS in Express

2 minute read 00000 views

This example uses Node directly for a web server. It assumes you are using port 80 for regular HTTP and 443 for HTTPS.

app.js

let express = require('express')
let app = express()
let http = require('http')
let https = require('https')
let fs = require('fs')

// Middleware which will perform the redirect
app.all('*', function (req, res, next) {
  if (req.secure) {
    return next()
  }
  res.redirect('https://' + req.hostname + req.url)
})

// Setup your app to listen on both ports 80 and 443
https
  .createServer(
    {
      key: fs.readFileSync('path/to/key/file'),
      cert: fs.readFileSync('path/to/certificate/file'),
      ca: fs.readFileSync('path/to/chain/file'),
    },
    app
  )
  .listen(443)

http.createServer(app).listen(80)

In a production environment, it's probably more robust to use NGINX which would let you accomplish this without creating two servers. It's also worth noting that you'd have to modify your server to allow "Non-root port binding" or play with iptables if you were to use ports 80 and 443 directly from your Node app.