In this article I will talk about nodejs and listening to a ssl (https) port. To make a selfsigned certificate execute the command below:
openssl req -nodes -new -x509 -keyout server.key -out server.cert -days 3650
Remember that browsers will complain about an invalid certificate. For most browsrs you can add a security exception for the certificate.
Now we have to tell nodejs to make use of this certificate when starting the https server. We have to create an option object with two properties: ‘key’ and ‘cert’. When we create the https server we pass in this option object:
var options = {
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.cert')
};
https.createServer(options, app).listen(3030);
The complete code for a https server with nodejs is shown below
const https = require('https');
const fs = require('fs')
const express = require('express')
const app = express()
const port = 3030
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.set('view engine', 'pug')
app.get('/', (req, res) => {
res.render('index')
}
)
var options = {
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.cert')
};
https.createServer(options, app).listen(3030);
console.log(`Listening on port ${port}`);
The pug template that is served:
html
head
body
p SSL site