How to do it...

We want to enable HTTPS connections, so we'll have to do a bit of work to install everything we need.

The first step in this installation will be getting yourself a certificate that properly validates the site that you own. Buying it goes beyond this book, so let's do a workaround by generating our own self-signed certificates—which, of course, aren't really secure, but will let us do all of the required configuration!

Let's assume that we want to set up our www.modernjsbook.com site. Working in Linux, you can create the necessary certificate files by executing the following commands and answering some questions:

openssl req -newkey rsa:4096 -nodes -keyout modernjsbook.key -out modernjsbook.csr
openssl x509 -signkey modernjsbook.key -in modernjsbook.csr -req -days 366 -out modernjsbook.crt

After doing this, you will end up with three files: a Certificate Signing Request (CSR), a KEY (Private Key), and a self-signed certificate (CRT) file, as follows; in real life, a Certificate Authority (CA) would be the actual signer:

> dir
-rw-r--r-- 1 fkereki users 1801 May 14 22:32 modernjsbook.crt
-rw-r--r-- 1 fkereki users 1651 May 14 22:31 modernjsbook.csr
-rw------- 1 fkereki users 3272 May 14 22:31 modernjsbook.key

Now, when you set up your server, you must read in those files (which should reside in a safe, read-only directory for added security) and pass their contents as options. We will use the fs module to do this, as in previous examples, and since reading the files is done only when the server is loaded, fs.readFileSync() can be used. Take look at the following code: 

// Source file: src/https_server.js

/* @flow */
"use strict";

const express = require("express");
const app = express();
const https = require("https");

const fs = require("fs");
const path = require("path");

const keysPath = path.join(__dirname, "../../certificates");

const ca = fs.readFileSync(`${keysPath}/modernjsbook.csr`);
const cert = fs.readFileSync(`${keysPath}/modernjsbook.crt`);
const key = fs.readFileSync(`${keysPath}/modernjsbook.key`);

https.createServer({ ca, cert, key }, app).listen(8443);
Why port 8443? The reason has to do with security, and we saw why in the Checking Node's setup section of the previous chapter; it's the same motive that we had behind using port 8080 instead of port 80.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset