Using an SSL certificate in a Node.js application is illustrated in this article. You may enable secure (HTTPS) connections in your application by utilizing an SSL certificate.
The following files are required in order to utilize an SSL certificate in a Node.js application:
The SSL certificate's certificate file. This file usually ends in either.pem or.crt.
The SSL certificate's private key file. This file usually has a.pem extension.
Upload these files to the server hosting your Node.js application if you haven't already.
The https.createServer() method requires the locations of your SSL certificate files as arguments in order to import them in a Node.js application.
The code example that follows shows you how to accomplish this. By providing the file locations (certificate, private key, and CA files) to the https.createServer() method, it generates a simple server that facilitates secure HTTPS connections on port 9876:
fs = require('fs');
const
require( ' https ) ;
https =
const
const
port
= 9876;
certFi1e = fs.readFi1eSyncC /path/to/certificate.pem' ) ;
const
caFi1e = fs.readFi1eSync( ' /path/to/ca_certificate.pem' ) ;
const
keyFi1e = fs.readFi1eSync( /path/to/privatekey.pem' ) ;
const
let options -
cert: certFi1e,
ca: caFi1e,
key: keyFi1e
= https.createServer(options, (req, res)
const httpsServer
res.writeHead(2ee, {'Content-Type': 'text/ plain' } ) ;
var message = 'It works! ,
version = 'NodeJS ' + process. versions.node + '\n',
[message, version] .join('\n');
response =
res . end (response) ;
httpsServer.listen(port);
To launch this application, copy and paste the code into a file. To point to your own SSL certificate files, change the certFile, caFile, and keyFile variables.
Launch the program, then navigate to https://localhost:9876 in your browser. "It works!" ought to appear in your web browser.
To learn more about the function https.createServer(), please visit
https://nodejs.org/api/https.html#httpscreateserveroptions-requestlistener.
To learn more about the https.createServer() function's SSL settings, please visit
(http://https://nodejs.org/api/https.html#httpscreateserveroptions-requestlistener)