Running Express over HTTPS in localhost

There are times when you want to expose your Express server via HTTPS for local development.

Let’s take a super simple Express code:

const express = require("express");

const app = express();

app.get("/", (req, res, next) => {
  res.send("Hello World\n");
});

app.listen(3001);

This will return “Hello World” when you hit http://localhost:3001

$ curl http://localhost:3001
Hello World

To run this in HTTPS, we need to install a tool called mkcert. Follow the installation instructions or if you’re using macOS and Homebrew, run this command:

$ brew install mkcert

Create a local CA and create certificate for localhost:

$ mkcert -install
$ mkcert localhost

This will create a certificate file localhost.pem and key file localhost-key.pem in the current directory.

Update the Express code as follows:

+ const fs = require("fs");
+ const https = require("https");

const express = require("express");

+ const key = fs.readFileSync("localhost-key.pem", "utf-8");
+ const cert = fs.readFileSync("localhost.pem", "utf-8");

const app = express();

app.get("/", (req, res, next) => {
  res.send("Hello World\n");
});

- app.listen(3001);
+ https.createServer({ key, cert }, app).listen(3001);

And you’re done!

$ curl https://localhost:3001
Hello World

You can find the full codebase in this repo.