How to enable HTTPS in Express.js

In this tutorial, we will learn how to enable HTTPS in Express JS.

You require an SSL certificate and an SSL key to do it. We create a self-signed SSL certificate and add it to the Trusted Root Certificate Authorities Store in this tutorial. Create a folder and open the terminal in it.

Generating self-signed SSL key and SSL certificate

Requirements

  • openssl

In Linux (Bash)

Run the below command and fill in the necessary details to generate an SSL key(tutorial.key) and SSL certificate(tutorial.crt). Make sure that the common name is localhost.

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

In Windows (Command Prompt/Powershell)

To create a key (tutorial. key), run the below command.

openssl genrsa -out tutorial.key 2048

Creating a Certificate Signing Request (CSR). Fill in the required details. Make sure that the common name is localhost.

openssl req -new -key tutorial.key -out tutorial.csr

Creating a self-signed certificate (tutorial.crt)

openssl x509 -in tutorial.csr -out tutorial.crt -req -signkey tutorial.key -days 365

Enable HTTPS in Express JS

Create a file named server.js and write the below code in it.

const express = require('express')
const https = require('https')
const fs = require('fs')

let app = express()

let key = fs.readFileSync(__dirname+'https://cdn.codespeedy.com/tutorial.key','utf-8')
let cert = fs.readFileSync(__dirname+'https://cdn.codespeedy.com/tutorial.crt','utf-8')

const port = 8443
const parameters = {
  key: key,
  cert: cert
}

app.get('/',(req,res)=>{
  res.send('HTTPS in ExpressJS')
})

let server = https.createServer(parameters,app)

server.listen(port,()=>{
  console.log(`Server is listening at port ${port}`)
})

We used readFileSync() instead of fs.readFile() because fs.readFile() allows us to read a file in a non-blocking asynchronous manner, whereas fs.readFileSync() allows us to read files in a synchronous manner, that is we’re telling node.js to block other parallel processes and focus on the current file reading process.

Follow this external link to add the generated certificate(tutorial.crt) to Trusted Root Certification Authorities.

OUTPUT

Run the below command to start the HTTPS server in the Express app.

node server.js

How to enable HTTPS in Express.js

It is showing HTTPS in red because we are using localhost here.

Because our certificate is self-signed, you may receive a warning while opening the server URL in your browser. The browser asks us to confirm before proceeding (however, the HTTPS connection still works) to the site.

Leave a Reply

Your email address will not be published.