Setting up a Certificate for localhost

Stephen Cooper - Jan 7 '22 - - Dev Community

(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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

This will create the following two files for you.

mv ./localhost.pem
mv ./localhost-key.pem
Enter fullscreen mode Exit fullscreen mode

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);

Enter fullscreen mode Exit fullscreen mode

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

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .