How to enable HTTPS on localhost for Node.js

ยท2 min. readยท

Sometimes, you may need to secure your localhost to test certain things, such as OAuth. Let's figure out how to create and install a fake HTTPS certificate to see the ๐Ÿ”’ "coveted lock" of a secure connection in the browser.

mkcert is an utility for making locally-trusted development certificates. It requires no configuration.

I suggest using NPM or Yarn for installing this tool, but you can also download binaries from the github releases page.

npm install -g mkcert
  1. Open your target directory, eg. C:/
  2. Create a Root certificate using this command:
mkcert create-ca
  1. Create a localhost certificate using this command:
mkcert create-cert

As a result, the following files should be created in the target folder: ca.crt, ca.key, cert.crt, cert.key.

Before we start our node.js application, it is necessary to properly install certificates in your system.

Windows 10 recognizes *.crt files, so you can right-click on ca.crt to open the import dialog:

  1. Click on [Install Certificate...]
  2. Leave "Current User" by default and click [Next]
  3. Select "Place all certificates in the following store", then click [Browse]
  4. Select "Trusted Root Certification Authorities" from the list
  5. Click [Next] and then [Finish]

This should be enough to make it work in Chrome, Edge and IE11.

If you wish to work with Firefox browser, try one of these solutions:

Solution 1:

  • Open about:config page in Firefox and set security.enterprise_roots.enabled to true

Solution 2:

  • Open about:preferences#privacy and navigate to Certificates > Import, then select ca.crt and click [Confirm for websites]

Let's create a simple node.js application server.js to test the HTTPS.

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

const port = 3001;
const options = {
  key: fs.readFileSync("cert.key"),
  cert: fs.readFileSync("cert.crt"),
};

const app = function (req, res) {
  res.writeHead(200);
  res.end("Hello HTTPS!");
};

https.createServer(options, app).listen(port);
console.log(`Server is running on port ${port}`);

As you noticed, we import certificate files from the same directory, so put the cert.key and cert.crt files in the same folder as the server.js file.

Run the server:

node server.js

Navigate to https://localhost:3001 to see the Hello HTTPS! text. If there are no certificate warnings from your browser, then we're done ๐Ÿ˜‰!

You may also like

How to use PM2 with Node.js

PM2 is a tool for managing Node.js processes, allowing for application... Read more
ยท2 min. read

How to reinitialize multiple TinyMCE editors

At some point, there was a need to reload multiple TinyMCE editors on one page,... Read more
ยท1 min. read

Killing Floor monsters in Counter-Strike

Sorry, I don't have IPs of these servers. ๐Ÿ˜ณ Gorefast (XMAS) in Counter-Strike... Read more
ยท1 min. read

ยฉ geekrainian.com.