How to configure HTTPS in Node.js

See how to setup a secure environment in our local machine to test HTTPS

Jul 27, 2020
featured image

Sometimes we need to configure a secure environment locally to test how our application reacts to HTTPS.

To configure HTTPS in Node.js is pretty easy, only a couple of steps and you will be able to use https://localhost:3000

I will assume you are using Linux or Mac

The first step is to create a folder to keep our generated files safe. This folder shouldn’t belong to our project.

$ mkdir some/folder
$ cd some/folder
From here I will assume you are at the folder you created

Create the private key and the certificate

$ openssl req -x509 -newkey rsa:2048 -keyout keytmp.pem -out cert.pem -days 365
Generating a 2048 bit RSA private key
writing new private key to 'keytmp.pem'
Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
It will ask you some data such as country, city, organization etc. You can introduce whatever you want because you will use this stuff locally. If you are configuring a production environment, of course you will have to write real data.

IMPORTANT: Remember the passphrase you used because you will need in the following step

List the current directory to see the generated files

$ ls
cert.pem    keytmp.pem
Get decrypted keys
$ openssl rsa -in keytmp.pem -out key.pem
List files
$ ls
cert.pem    key.pem     keytmp.pem
Now we can use our files in our app

I created two environment configs to keep the keys in a different directory rather than in my project: KEY_PEM and CERT_PEM

const fs = require('fs');
const key = fs.readFileSync(process.env.KEY_PEM); //absolute path to the key.pem file
const cert = fs.readFileSync(process.env.CERT_PEM); //absolute path to the cert.pem file
Configure Express to use the key and certificate
const express = require('express');
const https = require('https');
const app = express();
const server = https.createServer({key: key, cert: cert }, app);

After running your server, 99% you will get a big warning from your browser: image

Don’t worry, you can click on Advanced and then click on Proceed to localhost (unsafe)

That’s because the browser does not recognize your certificate as trusted. Remember we created it and it comes from our machine and not from an established certificate authority

Guide based on this

Photo by Florian Klauer on Unsplash

nodejs express https dev