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
Section titled “Prerequisites”To use an SSL certificate in a Node.js app, you need the following files:
- Certificate file (
.pemor.crt) - Private key file (
.pem) - Certificate Authority (CA) file (
.pemor.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
Section titled “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
Section titled “Running the App”- Copy the code above into a file, for example
server.js. - Update the
certFile,caFile, andkeyFilepaths to point to your SSL certificate files. - Start the application:
node server.js- Open your browser and visit:
https://localhost:9876You 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.