How to Create HTTPS Server in Node Js

How do I create an HTTPS server for Node Js? This is the most frequent question asked by node js developers. For various security reasons, many popular modules ask to enable HTTPS protocol.

What is HTTPS protocol? If you remove S from HTTPS, we get HTTP, a standard protocol for accessing web applications. It’s not secure; anyone can intercept your data packets connected to the same network.

While HTTPS is a secure protocol for web applications, here, all the communication between your browser and the server is encrypted and decrypted by only using a private key. This makes communication more secure and private.

This makes communication more secure and private. SSL certificates from a reputed certificate authority should be installed on the Node.js server. For the lowest price, a site owner should buy RapidSSL, Comodo SSL, or AlphaSSL certificates, which provide strong encryption but at a low price.

How to Install and Run Node Js in Linux

Today, you will learn to create an SSL certificate to start an HTTPS server for Express in Node Js.

Step 1: Standard Node Js Template

Let us take a look at the standard Node Js template. Below is the code we mostly write to create a regular server running on an HTTP.

const express = require("express"),
      app = express()

app.get("/", (req, res) => {
    res.send("Hello, TREND OCEANS!")
})

app.listen(3000, console.log(`Server started on port 3000`))

Running the above script using node js will start the webserver with standard HTTP protocol and display a “Hello, TREND OCEANS!” message.

Standard HTTP server
Standard HTTP server

For instance, you can take the above code as an example and create a new file in a new directory and save it with name app.js and also, don’t forget to run npm init command to initiate node modules in the current directory.

Step 2: Create an SSL Certificate

To use HTTPS, we have to first create an SSL certificate. SSL certificates can be generated in Windows, Linux, and macOS using OpenSSL.

OpenSSL is available by default for all Linux systems without installing any other package. Execute below command to create cert.pem and key.pem in your Linux system.

$ openssl req -x509 --newkey rsa:4096 --out cert.pem --keyout key.pem --days 365

For windows users, you can install Git Bash. OpenSSL is available within the console of Git Bash.

When you execute the above command, it will ask a few things. First, the passphrase for your key pem file to make it more secure. I recommend setting a secure password.

Generating SSL Certificate
Generating SSL Certificate

Next, it will ask general questions like country name in 2 letter code, email, organization name, etc. It’s up to you which information you want to provide they are not required.

Country Name (2 letter code) [AU]:US
State or Province Name (full name) [Some-State]:
Locality Name (eg, city) []:
Organization Name (eg, company) [Internet Widgits Pty Ltd]:
Organizational Unit Name (eg, section) []:
Common Name (e.g. server FQDN or YOUR name) []:
Email Address []:

Once you are done, you will see two files created in the current directory with name cert.pem and key.pem.

SSL Certificate
SSL Certificate

Now we have to place these files in the new directory. If you were using a standard template from step 1. Then create a new folder inside your current project with name cert and place both files there to make it more structured.

Moving certificate inside cert directory
Moving certificate inside cert directory

Step 3: Modifying Node App

Now we have to make a few changes inside app.js from step 1. Below are the few changes we made. You can spot differences by revisiting step 1 to understand our changes.

const express = require("express"),
      app = express(),
      fs = require("fs"),
      path = require("path"),
      https = require("https")


certfile = fs.readFileSync(path.join(__dirname, "cert", "cert.pem"))
keyfile = fs.readFileSync(path.join(__dirname, "cert", "key.pem"))

const secureserver = https.createServer({ cert: certfile, key: keyfile, passphrase: "trendoceans" }, app)

app.get("/", (req, res) => {
    res.send("Hello, TREND OCEANS!")
})

secureserver.listen(3000, console.log(`Server started on port 3000`))

Let’s talk about the changes we made from step 1.

First, we included a few more modules in our current project, like fs, path, and HTTPS.

fs: We included this library to read the content of the certificates.

path: It helps us to locate certificates in our project. [Which we moved in cert directory]

HTTPS: This main module allows us to create an HTTPS server using the certificate generated from step 2.

Next, we have just created a few variables specifying the location of the certificate and to read them using fs and path modules.

certfile = fs.readFileSync(path.join(__dirname, "cert", "cert.pem"))
keyfile = fs.readFileSync(path.join(__dirname, "cert", "key.pem"))

Now we use the above variables to read the SSL certificates to create an HTTPS server using the HTTPS module. Don’t forget to replace the passphrase. In my case, it’s trendoceans; replace it with the one you specified while generating an SSL certificate.

const secureserver = https.createServer({ cert: certfile, key: keyfile, passphrase: "trendoceans" }, app)

Finally, don’t forget to replace the last variable from the app to secureserver to start the listener in HTTPS protocol.

secureserver.listen(3000, console.log(`Server started on port 3000`))

Once you made the required changes. Next, save your file and open the command prompt or terminal in your project directory to start the express server using the below command.

$ node app.js

Now open your browser and visit https://localhost:3000, and for the first time, it will show a warning message connection is not private. We are getting this because we used a self-signed SSL certificate, and our browser doesn’t know the authority.

Avoiding the warning message
Avoiding the warning message

For now, click on advance and then Proceed to localhost (unsafe) to access your site.

Secure Node Js Server
Secure Node Js Server

Tada, you have successfully created an HTTPS server for express in node js.

Final Thought

I understand in the beginning, it may seem a little bit tricky. But if you were facing any difficulty or are unable to create a secure server. Let us know in the comment section.

Leave a Reply

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.