Jan 7 '22 ~ 6 ~ 1 mins

Setting up a Certificate for localhost

(This post is mainly a public note for myself but maybe will help others too.)

Self Signed Not Enough

We had a requirement to run our site using https locally due to changing security requirements. It was possible to create a self signed certificate with the following command to enable the site to load but it is still not trusted by the browsers.

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout ./selfsigned.key -out ./selfsigned.crt

This means you will have the red padlock and on Chrome you can run into issues like this.

localhost/:35 GET https://localhost:8000/commons.css net::ERR_TOO_MANY_RETRIES

For me this meant that my local environment would just not load important scripts making development impossible. The solution is to create and use a proper certificate.

Using mkcert

These steps are for Mac.

brew install mkcert
mkcert localhost
mkcert -install

This will create the following two files for you.

mv ./localhost.pem
mv ./localhost-key.pem

You could move these somewhere easy to reference for your dev server as you will need them when creating the https server.

const key = fs.readFileSync('PATH_TO_FILES/localhost-key.pem, 'utf8');
const cert = fs.readFileSync('PATH_TO
_FILES/localhost.pem', 'utf8');

const credentials = {
    key: key,
    cert: cert
};

const httpsServer = https.createServer(credentials, app).listen(EXPRESS_HTTPS_PORT);

Following these steps you should be able to use https on localhost and the browsers will trust the certificate.


Headshot of Stephen Cooper

Hi, I'm Stephen. I'm a senior software engineer at AG Grid. If you like my content then please follow / contact me on 🦋 Bluesky or 𝕏 (X) and say hello!