Running express.js server over HTTPS

February 27, 2020 (4y ago)

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 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.