It’s time! No more procrastination and poor excuses. Let’s secure our Node.js Apps.
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.
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.
Here is the folder structure we will be left with after the dust settles:
The index.js is our app’s main entry file. The certs folder will contain our SSL certificate and key file.
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
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 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
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.
This section of code auto generates the SSL certificate and key file if they do not exist in the certs folder.
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