Configuring SSL Certificates with nodejs

2 minute read | By Edison Garcia

How to configure a SSL Certificate for NodeJS

In specific scenarios you are looking for creating a https server within nodejs as described in the following reference: Https Server

You will need at least a self signed certificate for dev/test into localhost or one signed by a ‘Certificate Authority’. In this example we are going to use one is signed by CA bought from GoDaddy and setup everything inside a Linux VM.

Steps

  1. In your Linux VM ssh session, you can use openssl to create the csr (Certificate signing request) with the following command:
openssl req -new -newkey rsa:2048 -nodes -keyout yourdomainname.key -out yourdomainname.csr
  1. You will need to update the required information and for your fully-qualified domain name just put your custom domain or wildcard if you are using one.
  2. Once the .csr is generated, you can open this file and copy the content and go your SSL certificate provider and find the CSR part to paste it. In some SSL providers you need to setup the common name in their website as well.

In this example I am using GoDaddy since I have one already there. csr

  1. After get the ssl certificate, you can download and select the type of servers, try to select other types, we will not use nginx or apache here. ssl

  2. Most SSL providers will provide the following structure, where you can have the certificate (.crt) and (pem) and the bundle where is the intermediate certificate used as proxy for root CA. structure

  3. Copy these files to your app location and you can use the following code, this is just an example , basically you will use the generated key from step 1, the crt and gd(bundle) as a ca:

var express = require('express');
var http = require('http');
var https = require('https');
var fs = require('fs');
var server = express();
var port = process.env.PORT || 3001;

var sslOptions = {
    key: fs.readFileSync('certificates/domainname.key','utf8'),
    cert: fs.readFileSync('certificates/domainname.crt','utf8'),
    ca: fs.readFileSync('certificates/domainname-ca.crt','utf8'),
  };

server.get('/', function (req, res) {
    res.send("Hello World!");
});

https.createServer(sslOptions, server).listen(port);

*This should work at this point. Note: There are some conditions where nodejs requires to separate the gd bundle into different files as following:

var sslOptions = {
    key: fs.readFileSync('certificates/domainname.key','utf8'),
    cert: fs.readFileSync('certificates/domainname.crt','utf8'),
    ca: [
        fs.readFileSync('certificates/domainname-gd1.crt','utf8'), 
        fs.readFileSync('certificates/domainname-gd2.crt','utf8'),
        fs.readFileSync('certificates/domainname-gd3.crt','utf8')
    ]
  };

Additional Reference can be found Here