SSL certificates have got a lot cheaper, not as cheaper as domain names or cloud hosting, but yes they have. And while an SSL certificate was previously thought to be a payments (or e-commerce) only requirement, the thought surely has changed after Google announced that it will give secure sites a rank boost.

Okay, so the thought has changed, SSL certificates are cheaper than ever and Google gives us a boost if we have one installed on our site, but how do we install it? How to generate one? What about the HTTP traffic?

This article will guide you through the how-tos of SSL installation on a Linux machine running Node.js. We will assume you are familiar with Linux terminal commands and Node.js. Let's get started!

---

We start off with express installation. The following command will install express and save it in node_modules folder.

npm i express -g --save

Once done, we will create a new .js file, (whatever name you wish to give it) app.js. In the file, we will add these few lines. Here the require function helps us by including the express module in our file for further usage. An instance of express is created as app. The same goes with fsfs (file system) is an API provided by Node.js to read/write files from/to directories. We will use fs to read our SSL certificate files.

var express = require('express');
var app = express();
var fs = require('fs');
view rawNodeHTTPs1.js hosted with ❤ by GitHub

Now, the most important part of all. Get an SSL certificate. A standard SSL certificate comes with two important files, Primary certificate, and Intermediate certificate. To get an SSL, you will have to generate a CSR from your server for validation. Also, we need to generate a key (private key) to maintain an HTTPS connection with the server. Running the following command in a Linux environment will get us our desired mydomain.csr and private.key files.

openssl req -new -newkey rsa:2048 -nodes -out mydomain.csr -keyout private.key

Use the .csr to generate your certificates and save the generated certificate files (.crt) and the private.key file in a directory in the root (say encryption).

Now we need to read these files and get our HTTPS server started. The following will do the reading and save the buffer in respective variables. Keep in mind that you read your files with readFileSync function and not readFile. The latter tends to block the io while reading files ensuring that all certificate files are read before attempting to create a connection.

var key = fs.readFileSync('encryption/private.key');
var cert = fs.readFileSync( 'encryption/primary.crt' );
var ca = fs.readFileSync( 'encryption/intermediate.crt' );
view rawNodeHTTPs2.js hosted with ❤ by GitHub

Once done, we will create an options variable using our certificate files like this,

var options = {
key: key,
cert: cert,
ca: ca
};
view rawNodeHTTPs3.js hosted with ❤ by GitHub

and create our server using the options and app (the express instance we created earlier, remember?) which will listen to all connections on port 443 (https’ default port).

var https = require('https');
https.createServer(options, app).listen(443);
view rawNodeHTTPs4.js hosted with ❤ by GitHub

Save your file and run

node app.js

If everything was properly followed and certificates were correctly generated for the domain you are using to point to your server, you will see a green https bar on the left of the address bar. However, there’s a catch. We haven’t yet made sure that our HTTP traffic is directed to HTTPS. Let’s do that.

We will create another server which runs alongside HTTPS and will redirect to it.

var http = require('http');
http.createServer(app).listen(80);
view rawNodeHTTPs5.js hosted with ❤ by GitHub

This will create an HTTP server listening on port 80 (HTTP's default port), and now your domain runs on both HTTP and HTTPS web protocol. To force HTTPS, we will check if the request was made through a TLS connection (using HTTPs protocol). If it is secure, we forward the request, else we send a redirect response back to the client which will force the client to request again but this time securely. 

app.use(function(req, res, next) {
if (req.secure) {
next();
} else {
res.redirect('https://' + req.headers.host + req.url);
}
});
view raw NodeHTTPs6.js hosted with ❤ by GitHub

We will use app.use(...)  to bind our redirect middleware to express. You can also use app.all(...) in case you're planning to have specific routes where the redirects should take place.

That’s it. Express will now know that we wish to direct our HTTP traffic and will transform such requests into an HTTPs one using our middleware.

You can find the complete gist here.