When developing locally, using HTTPS can be essential for testing secure connections. However, setting up HTTPS for localhost can be challenging due to certificate trust issues. This is where mkcert comes in handy. In this post, I’ll walk you through how I used mkcert to generate an HTTPS certificate for localhost.

What is mkcert?

mkcert is a simple tool that makes locally trusted development certificates. It automatically creates and installs a local Certificate Authority (CA) in your system, allowing you to generate certificates that are trusted by your browser and operating system.

Installing mkcert

To get started, you need to install mkcert. On macOS, you can use Homebrew:

brew install mkcert
brew install nss # If you use Firefox

Setting Up mkcert

After installation, you need to set up the local CA:

mkcert -install

This command creates and installs a local CA in your system’s trust store. It’s a one-time setup.

Generating a Certificate for Localhost

To generate a certificate for localhost, run the following command:

mkcert localhost

This will create two files in the current directory:

  • localhost.pem: The certificate file.
  • localhost-key.pem: The private key file.

You can also generate certificates for multiple domains by specifying them as arguments:

mkcert localhost 127.0.0.1 ::1

Using the Certificate

Once the certificate is generated, you can use it in your local development server. For example, if you’re using a Node.js server, you can configure it like this:

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

const options = {
  key: fs.readFileSync('localhost-key.pem'),
  cert: fs.readFileSync('localhost.pem')
};

https.createServer(options, (req, res) => {
  res.writeHead(200);
  res.end('Hello, HTTPS!');
}).listen(443);

Verifying the Setup

After starting your server, open your browser and navigate to https://localhost. You should see the secure connection indicator without any certificate warnings.

Conclusion

Using mkcert simplifies the process of setting up HTTPS for local development. It eliminates the hassle of dealing with untrusted certificates and ensures a smooth development experience. If you haven’t tried it yet, give it a go!

I hope this guide helps you set up HTTPS for your local projects. If you have any questions or feedback, feel free to reach out!