How to set up HTTPS on localhost for macOS

Jon Samp
2 min readJun 11, 2017

--

tl:dr: you can copy/paste this script in your command line and just be done with it.

SSL is needed on localhost to use some browser features, like Speech Recognition. Getting it set up is tough because many articles (rightly) explain concepts and ideas behind why you do something, but they miss explaining the how. This article explains how, and doesn’t worry about any of the whys. So, without further ado:

Generating the keys

  1. Make a .localhost-ssl folder in your home directory. Do this by opening a command line (Terminal, iTerm, …) and typing cd ~/. Once there, create the folder by typing mkdir .localhost-ssl.
  2. Next, we need to create a self signed key and certificate(understanding of these files not required). Do this by typing (you’ll be asked to type in your password):
  sudo openssl genrsa -out ~/.localhost-ssl/localhost.key 2048

3. Now, copy and paste this code. It will create a certificate for you:

sudo openssl req -new -x509 -key ~/.localhost-ssl/localhost.key -out ~/.localhost-ssl/localhost.crt -days 3650 -subj /CN=localhost

4. Finally, you need to add these keys to the Keychain.app. Do it with:

sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ~/.localhost-ssl/localhost.crt

Starting a server

Now that you have your certificate and key, you need to start a server with https. It’s easiest to use the very fine npm package http-server. Install it with npm install -g http-server.

Once installed, open up your .bash_profile in a text editor. If you use Atom, type this in your command line: atom ~/.bash_profile. Then save this function inside it:

function https-server() {
http-server --ssl --cert ~/.localhost-ssl/localhost.crt --key ~/.localhost-ssl/localhost.key
}

This function starts an http-server with the credentials you set above.

Head back to your command line, type source ~/.bash_profile, then navigate to the root directory of a project of yours. Now all you have to type is https-server and you have a fancy https server running on localhost ✨

--

--