Enable HTTPS With Express

May 7, 2019

Setting up an HTTPS server on localhost is tricky, but doable. You will need to create an HTTPS certificate and configure your browser to trust your new certificate. Thankfully, there's a tool for that.

First, you will need to set up mkcert. The easiest way is to download the prebuilt mkcert binary for your platform. Below are the commands I ran to create a trusted certificate for localhost.

$ wget https://github.com/FiloSottile/mkcert/releases/download/v1.3.0/mkcert-v1.3.0-linux-amd64
$ chmod 0755 ./mkcert-v1.3.0-linux-amd64 
$ ./mkcert-v1.3.0-linux-amd64 -install
Using the local CA at "/home/user/.local/share/mkcert" ✨
The local CA is now installed in the Firefox and/or Chrome/Chromium trust store (requires browser restart)! 🦊

$ ./mkcert-v1.3.0-linux-amd64 localhost
Using the local CA at "/home/val/.local/share/mkcert" ✨

Created a new certificate valid for the following names 📜
 - "localhost"

The certificate is at "./localhost.pem" and the key at "./localhost-key.pem"

Now that you have localhost.pem and localhost-key.pem, let's use them to start an Express server that responds to https://localhost. To do this, you will need to read the localhost.pem and localhost-key.pem files, and pass them to Node.js' native https.createServer() function.

const fs = require('fs');
const https = require('https');

const app = require('express')();
app.get('*', (req, res) => res.send('<h1>Hello, World</h1>'));

const server = https.createServer({
  key: fs.readFileSync(`${__dirname}/localhost-key.pem`, 'utf8'),
  cert: fs.readFileSync(`${__dirname}/localhost.pem`, 'utf8')
}, app);

await server.listen(443);

Want to become your team's Express expert? There's no better way to really grok a framework than to write your own clone from scratch. In 15 concise pages, this tutorial walks you through how to write a simplified clone of Express called Espresso. Get your copy!

Espresso supports:
  • Route handlers, like `app.get()` and `app.post()`
  • Express-compatible middleware, like `app.use(require('cors')())`
  • Express 4.0 style subrouters
As a bonus, Espresso also supports async functions, unlike Express.

Get the tutorial and master Express today!

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Express Tutorials