How to use HTTPS on localhost

Sometimes you want to have your application running on HTTPS even when testing it out locally. One common approach is to use a self-signed certificate, but this method has some pitfalls - most notably that any browser will frown upon your certificate and start shouting that it is insecure. A more robust approach is to use a certificate generated by a Certificate Authority (CA). How? Enter mkcert, which lets you act as your own CA. Using it is very straightforward.

Preparations

First you need to install mkcert itself. Do so using homebrew, or otherwise follow the instructions.

brew install mkcert

Additionally install nss if you are using Firefox:

brew install nss

Now we can create our very own CA!

mkcert -install

You might need to restart your browser for its trust store to include your new CA.

Certificate generation

Finally we are ready to generate our actual certificate:

mkcert localhost

Or, if you want to control where the naming and storage path of the certificate files:

mkcert -key-file certs/localhost-key.pem -cert-file certs/localhost.pem localhost

And we’re done! All that’s left is to tell your application to launch using HTTPS, and where to find its certificate.

Vue example

Here’s a quick example of how to make your Vue.js application run using HTTPS. Add the following snippet to your vue.config.js file:

const fs = require("fs");

module.exports = {
  
  ...

  devServer: {
    https: {
      key: fs.readFileSync('./certs/localhost-key.pem'),
      cert: fs.readFileSync('./certs/localhost.pem')
    }
  }
};

That’s it! Enjoy using your app over HTTPS without trust warnings in the browser.