How to enable HTTPS on Express.js and Node.js?

Sometimes, we want to enable HTTPS on Express.js and Node.js.

In this article, we’ll look at how to enable HTTPS on Express.js and Node.js.

How to enable HTTPS on Express.js and Node.js?

To enable HTTPS on Express.js and Node.js, we can read the certificate files and use them when we create the server.

For instance, we write

const fs = require('fs');
const http = require('http');
const https = require('https');
const privateKey = fs.readFileSync('sslcert/server.key', 'utf8');
const certificate = fs.readFileSync('sslcert/server.crt', 'utf8');

const credentials = {
  key: privateKey,
  cert: certificate
};
const express = require('express');
const app = express();

const httpServer = http.createServer(app);
const httpsServer = https.createServer(credentials, app);

httpServer.listen(8080);
httpsServer.listen(8443);

to read the private key and certificate file with readFileSync.

Then we call createServer with the credentials object to let us run our web server with our certificate and key files via HTTPS.

And then we listen to the for HTTP and HTTPS requests with listen with different ports.

Conclusion

To enable HTTPS on Express.js and Node.js, we can read the certificate files and use them when we create the server.