This article will explain how to setup a SSL certificate for all your HTTPS development needs.
Note: This is for development environments ONLY!
We will explore how to setup a certificate, tell our computer to trust it, how to use it in a basic NodeJS server, and how to delete the certificate from our trust store after we are done.
Step 1 (Installation)
We will be using a tool called mkcert:
Windows:
Via Chocolatey:
choco install mkcert
Via Scoop
scoop bucket add extras
scoop install mkcert
MacOS:
Via Brew
brew install mkcert
and (Firefox)
brew install nss
Other installation methods for macOS and Linux are on the mkcert github repo
Step 2 (Create the certificate)
The following command will create 2 files depending on your input
mkcert %your-domain-here%
Replace %your-domain-here% with the domain you would like to secure for your computer. As we are going to be using this for development, I shall use localhost as such:
mkcert localhost
For my command, the following 2 files were created:
That's it! Its as simple as that for creating the certificate.
Step 3 (Trusting the certificate)
Time to tell our computer that our certificate is alright to trust!
In the same directory as both of your files, run the following command regardless of your domain:
mkcert -install
On Windows, mkcert will kindly warn us of the danger:
The redacted information will be specific to your computer.
Done! Now our computer has no problem whatsoever with our certificate.
Step 4 (Using it!)
The following implementation is in NodeJS and uses the Express framework.
The following code will sum up exactly what we need:
const express = require('express');
const https = require('https');
const fs = require('fs');
const path = require('path');
const certificate = {
key: fs.readFileSync(path.resolve('./localhost-key.pem')),
cert: fs.readFileSync(path.resolve('./localhost.pem'))
}
const app = express();
app.get('/', function (req, res) {
res.end('Am I secure?');
});
const server = https.createServer(certificate, app);
server.listen(443, () => {
console.log('HTTPS server is UP! https://localhost/');
});
Run this server:
node server.js
We are officially using
HTTPS in a development environment!
You should be able to go to localhost and see that beautiful lock.
After every development session, I highly suggest you tell the computer to not trust the certificate just in case the certificate is accidently pushed to Git or the project is abandoned because we do not want to leave random certificates trusted.
The command to remove the certificate from the trust store is as below regardless of your domain:
mkcert -uninstall
NOTE: I had to restart my browser for the certificate to not be trusted
Well, that's it for SSL certificates for development. This is my first dev.to article so I hope this helped someone. I can be contacted at humanfriend22@gmail.com. Check out my github profile.
Bye! ✌
Top comments (1)
Very useful, thanks for sharing :)