How to setup an HTTPS Express.js server#

The instructions in this article is for educational purposes only. For production servers, you should use a paid Certificate authority or Let's Encrypt for generating the SSL certificate and use a front-facing proxy for handling the HTTPS traffic.

Generating SSL certificate#

Before we can enable HTTP on our Express server, we need to have our SSL certificates ready. Let's generate one.

$ openssl genrsa -out hacksparrow-key.pem 1024
$ openssl req -new -key hacksparrow-key.pem -out certrequest.csr
... bunch of prompts
$ openssl x509 -req -in certrequest.csr -signkey hacksparrow-key.pem -out hacksparrow-cert.pem

In the second command, when prompted for "Common Name (eg, YOUR name) []:", give the domain name of your website (likely to be localhost, if you want to try locally), else trying to use the certificate will result in "domain mismatch" errors.

Configuring the HTTPS server#

Now that we have our SSL certificate, it is just a matter of loading the https Node.js module and passing it a configuration with the details about the SSL certificate we just generated.

var app = require('express');
var https = require('https');
var fs = require('fs');

var hskey = fs.readFileSync('hacksparrow-key.pem');
var hscert = fs.readFileSync('hacksparrow-cert.pem')

var options = {
  key: hskey,
  cert: hscert
};

var server = https.createServer(options, app);
server.listen(5000, function () {
  console.log('HTTP Express server is up!');
});

Start the app.

Now you can access your HTTPS Express.js app at https://localhost:5000. When you try to load the website for the first time you will be greeted with a privacy error.

It is safe to ignore it. Click on "Advanced" and then on "Proceed to localhost (unsafe)" to see your HTTP website.

Conclusion#

Enabling HTTP in Express.js requires the https Node module and an SSL certificate. Once configured with the SSL certificate details, and started; the HTTPS server will serve its pages and other contents via the encrypted HTTPS protocol.

References#

  1. Node.js - https
  2. Let's Encrypt
  3. WikiPedia - TLS/SSL