Using an SSL Certificate in a Node.js App

This guide explains how to use an SSL certificate in a Node.js app to enable secure (HTTPS) connections.


Prerequisites

To use an SSL certificate in a Node.js app, you need the following files:

  • Certificate file (.pem or .crt)

  • Private key file (.pem)

  • Certificate Authority (CA) file (.pem or .crt)

Upload these files to the server where your Node.js app is stored if you haven’t done so already.


Loading the SSL Certificate in a Node.js App

You load SSL certificate files by passing their paths to the https.createServer() function. The following example demonstrates a basic HTTPS server running on port 9876:

const fs = require('fs');
const https = require('https');

const port = 9876;

const certFile = fs.readFileSync('/path/to/certificate.pem');
const caFile = fs.readFileSync('/path/to/ca_certificate.pem');
const keyFile = fs.readFileSync('/path/to/privatekey.pem');

let options = {
   cert: certFile,
   ca: caFile,
   key: keyFile
};

const httpsServer = https.createServer(options, (req, res) => {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    const message = 'It works!\n';
    const version = 'NodeJS ' + process.versions.node + '\n';
    res.end([message, version].join('\n'));
});

httpsServer.listen(port);

Running the App

  1. Copy the code above into a file, for example server.js.

  2. Update the certFile, caFile, and keyFile paths to point to your SSL certificate files.

  3. Start the application:

node server.js
  1. Open your browser and visit:

https://localhost:9876

You should see:

It works!
NodeJS <version>

Important: Make sure to use https:// in the browser address bar; using http:// will cause the connection to fail.


More Information

Was this answer helpful? 0 Users Found This Useful (0 Votes)

Powered by WHMCompleteSolution