How to use an SSL certificate in a Node.js app

This article demonstrates how to use an SSL certificate in a Node.js app. By using an SSL certificate in your app, you can support secure (HTTPS) connections.

Prerequisites

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

  • Certificate file for the SSL certificate. Typically this file has a .pem or .crt extension.
  • Private key file for the SSL certificate. Typically this file has a .pem extension.
  • Certificate Authority (CA) file for the SSL certificate. Typically this file has a .pem or .crt extension.

If you have not already done so, upload these files to the server where your Node.js app is stored.

Loading the SSL certificate in the app

To load your SSL certificate files in a Node.js app, you must pass their paths as parameters to the https.createServer() function.

The following code sample demonstrates how to do this. It creates a basic server that supports secure HTTPS connections on port 9876 by passing the file locations (certificate file, private key file, and CA file) to the https.createServer() function:

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'});
    var message = 'It works!\n',
        version = 'NodeJS ' + process.versions.node + '\n',
        response = [message, version].join('\n');
    res.end(response);
});

httpsServer.listen(port);

If you want to run this app, copy the code and paste it into a file. Modify the certFile, caFile, and keyFile variables to point to your own SSL certficate files.

Start the application, and then use your web browser to go to https://localhost:9876. You should see “It works!” in your web browser.

Make sure you type https:// in the browser address bar (not http://), or the connection will fail.

More Information

Did you find this article helpful? Then you'll love our support. Experience the A2 Hosting difference today and get a pre-secured, pre-optimized website. Check out our web hosting plans today.

We use cookies to personalize the website for you and to analyze the use of our website. You consent to this by clicking on "I consent" or by continuing your use of this website. Further information about cookies can be found in our Privacy Policy.