1) To create and start https server first, you will have to import https, http and fs modules which are inbuilt Node.js. You will also need to install express to create Node.js server.
const express = require(‘express’)
const app = express();
const https = require(‘https’);
const http = require(‘http’);
const fs = require(‘fs’);
2) Get certificate file(cert1.pem), private key(privkey1.pem) and two SSL certificate chain files(chain1.pem, fullchain1.pem) from AWS/GCP/Azure and save in your project directory where your main server file is located. Then create an object as below.
const options = {
key:fs.readFileSync(‘privkey1.pem’),
cert:fs.readFileSync(‘cert1.pem’),
ca: [fs.readFileSync(‘chain1.pem’), fs.readFileSync(‘fullchain1.pem’)]
};
3) Now you can create your https and http server as shown below
if (env == ‘production’) {
https.createServer(options, app).listen(port, () => {
console.log(`Server started on ${env} environment on port ${port}`);
});
} else {
http.createServer(app).listen(port, () => {
console.log(`Server started on ${env} environment on port ${port}`);
});
}