JavaScriptJavaScript

Running express.js server over HTTPS

Oct 27, 2017 · Updated: Dec 01, 2021 · by

HTTPS is everywhere and more often than not we need to spin an https server or two. Here's how you can do it for your local express.js dev server:

1. Generate a self-signed certificate

openssl req -nodes -new -x509 -keyout server.key -out server.cert

2. Enable HTTPS in Express

Add something like this to your index.js

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

app.get("/", function (req, res) {
  res.send("hello world");
});

https
  .createServer(
    {
      key: fs.readFileSync("server.key"),
      cert: fs.readFileSync("server.cert"),
    },
    app
  )
  .listen(3000, function () {
    console.log(
      "Example app listening on port 3000! Go to https://localhost:3000/"
    );
  });

Now run a command node index.js and your server should be available at address https://localhost:3000.

Please be aware that browsers reject self-signed certificates by default, so when you open https://localhost:3000 for the first time, you'll see a browser warning instead of an expected page. If you don't like this, there's a way to force your browser to trust any self-signed certificate. I described it in my other tutorial . Don't freak out, the tutorial is for Django devs, but if you follow what's written in Step 1 you should be good. The approach is generic and works for any framework.

Hey, if you've found this useful, please share the post to help other folks find it:

There's even more:

Subscribe for updates