In this article, I am going to walk you through a practical example of how to install SSL certificates to your Express.js server.

Let’s start with a short review.

SSL, TLS, HTTPS

Let’s start with a quick recapitulation of protocols that allows you to secure your client-server connections.

SSL stands for Secure Sockets Layer. It was developed in mid-90ties by Netscape and was quickly superseded by TLS.

TLS stands for Transport Layer Security. It is a standard maintained by IETF and addresses many shortcomings and security vulnerabilities of the SSL protocol.

Both SSL and TLS operate at the level of TCP socket streams, they provide means for switching a plaintext stream into a fully encrypted channel.

HTTPS, or HTTP Secure, is a combination of HTTP protocol communicating over a SSL/TLS channel.

We’ll be using OpenSSL to generate all of our certificates.

Setting up the folder structure

Here is the folder structure we will be left with after the dust settles:

Folder structure of Node.js SSL configuration

The index.js is our app’s main entry file. The certs folder will contain our SSL certificate and key file.

Dependencies

Express

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications and APIs.

npm install express --save

Chalk

When making any kind of node.js project that may involve output to the command line interface, it may be desired to style that output, for the sake of adding emphases, or just to make it look nice. You might want to check out chalk.

npm install chalk — save

Nodemon

nodemon is a tool that helps develop node.js based applications by automatically restarting the node application when file changes in the directory are detected.

npm install — save-dev nodemon

Configuring Node.js Server

By default, Node.js serves content over HTTP. But there’s also an HTTPS module which we have to use in order to communicate over a secure channel with the client. This is a built-in module, and the usage is very similar to how we use the HTTP module.

index.js

index.js source code

This section of code auto generates the SSL certificate and key file if they do not exist in the certs folder.

auto generate ssl

Generate custom certificate by tweaking the below options

openssl req certificate request generating utility

-new generatesa new certificate request

-key specifies the file to read the private key from

-out specifies the output filename

-subj sets certificate subject

C=Country Code GB

ST=State London

L=Location London

O=Organization Global Security

OU=Organizational Unit IT Department

CN=Common Name example.com

package.json