Express 3.0 HTTPS

Express 3.0 HTTPS

Problem

I have a Node.js Express 3.0 application which listens on port 3000 locally and 80 online, that’s fine. What I need to do now however is introduce an SSL certificate.

I’ve looked at many sources online however they’re all dated, or only work on port 443 or nothing. What I need to do however is listen on both 443 and 80 and re-direct any requests to 80 back to 443.

Are they any up to date examples of this?

Problem courtesy of: James

Solution

I would do this with 2 distinct processes: an insecure proxy server and a secure server.

The insecure proxy listens on port 80 and responds to all requests with a 302 redirect to the secure server

Insecure Proxy

var http = require('http')
var port = 80
var server = http.createServer(function (req, res) {
  // change this to your secure sever url
  var redirectURL = 'https://www.google.com'
  res.writeHead(302, {
    Location: redirectURL
  });
  res.end();
}).listen(port, function () {
  console.log('insecure proxy listening on port: ' + port)
})

Secure Server

var https = require('https')
var express = require('express')
var fs = require('fs')
var keyFilePath = '/path/to/key.pem'
var certFilePath = '/path/to/cert.pem'

var app = express()
// put your express app config here
// app.use(...) etc.

var port = 443 // standard https port
var options = {
  key: fs.readFileSync(keyFilePath, 'utf8'),
  cert: fs.readFileSync(certFilePath, 'utf8')
}

var server = https.createServer(options, app)
server.listen(port, function () {
  console.log('secure server listening on port: ' + port)
})

Note that you could run both of these servers within a single process but it is more maintainable to separate the concerns into distinct processes.

Solution courtesy of: Noah

Discussion

Leave a Reply

Your email address will not be published. Required fields are marked *