How to set up a SSL certificate for an Express.js server?

Sometimes, we want to set up a SSL certificate for an Express.js server.

In this article, we’ll look at how to set up a SSL certificate for an Express.js server.

How to set up a SSL certificate for an Express.js server?

To set up a SSL certificate for an Express.js server, we can http.createServer with the certificate and private key files.

For instance, we write

const privateKey = fs.readFileSync('privatekey.pem');
const certificate = fs.readFileSync('certificate.pem');

https.createServer({
  key: privateKey,
  cert: certificate
}, app).listen(port);

to call https.createServer with the key and cert properties set to the privateKey and certificate files respectively.

We read the files synchronously with readFileSync.

Then we call listen with the port that we use to listen for requests.

Conclusion

To set up a SSL certificate for an Express.js server, we can http.createServer with the certificate and private key files.