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 get GIT repository URL from source folder
There are several ways to get the link to a GIT repository from the directory... Read more
·1 min. read
Giran Castle Town paper model
Found it on the internet. Author unknown... 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