express 4.x redirect http to https

I have the following code :

var https        = require('https');
var http         = require('http');
var express      = require('express');
var app          = express();
var router       = express.Router();

app.use("", router);

//have 'server' listen for https
var server = https.createServer(config.sslCredential, app);

//listen server on http, and always redirect to https
var httpServer = http.createServer(function(req,res){

but somehow I can’t get the https request to be redirected into https request, how should I do this correctly on node.js with express 4.x ?

Quoting a middleware solution from my own answer (which btw was on express 3.0)

app.all('*', ensureSecure); // at top of routing calls

https.createServer(sslOptions, app).listen(443)

function ensureSecure(req, res, next){
    // OK, continue
    return next();
  // handle port numbers if you need non defaults
  // res.redirect('https://' + + req.url); // express 3.x
  res.redirect('https://' + req.hostname + req.url); // express 4.x

You can do redirection to https like this:

app.enable('trust proxy')
app.use((req, res, next) => { ? next() : res.redirect('https://' + + req.url)

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   Access variables in jsFiddle from Javascript console?

Similar Posts