{G}eekrainian

How to enable HTTPS on localhost for Node.js

4 min. read

Читать на Русском.

Programming

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.

Install mkcert

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

Generate certificates

  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.

Install certificates on your machine

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

Windows 10

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]

Testing Node.js application

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 😉!

Enjoyed the story? 🤔

If this article was useful for you, please consider supporting me by making a donation.

BuyMeACoffee

Ko-Fi

Share

You may also like

How to install Node.js on Ubuntu 20.04

Step-by-step guide for Node.js installation on Linux Ubuntu 20.04... Read more

© geekrainian.com

  • Русский
  • English
RSSSitemap