Setup HTTPS for local development using node.js and express.
February 2, 2021
In this article we are going to test our site locally in https using mkcert in node & express app. mkcert is a great tool to automatically generate and install SSL certificates.
Make sure we have node.js installed in our machine. You can download it here
🔧 Installation & Steps
- Install Homebrew (package manager for mac os)
# only for mac users
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"- Install mkcert to generate all TLS certificates.
For mac
brew install mkcert
brew install nss # if you use FirefoxFor windows : Follow this instructions to install the mkcert.
- Generate trusted cerificate locally
$ mkcert -install
# Created a new local CA
$ mkcert [domain name]
# In our case, we will use localhost
$ mkcert localhostAbove step will generate couple of files [domainname]-key.pem, [domainname].pem.
- Create an node app and create server js file.
npm init
touch server.js- Install express js
npm install express- Copy these files created in step 3
[domainname]-key.pem,[domainname].pemand paste it in this folder. - Include this below code in server.js
"use strict"
const https = require("https")
const express = require("express")
const fs = require("fs")
// load the self-signed certificates
const options = {
key: fs.readFileSync("[domainname]-key.pem"),
cert: fs.readFileSync("[domainname].pem"),
}
const app = express()
app.get("/", (req, res, next) => {
res.send("Localhost hosted in https !")
})
https.createServer(options, app).listen(3000)- Start the server
node server.js- Test the application by opening the browser and hitting the URL
https://localhost:3000/
💽 Test output in the browser