Search code examples
javascriptnode.jssslhttpswebserver

How to create an HTTPS server in Node.js?


Given an SSL key and certificate, how does one create an HTTPS service?


Solution

  • For Node 0.3.4 and above all the way up to the current LTS (v21 at the time of this edit), https://nodejs.org/api/https.html#httpscreateserveroptions-requestlistener has all the example code you need:

    const https = require('node:https');
    const fs = require('node:fs');
    
    const options = {
      key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
      cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),
    };
    
    https.createServer(options, (req, res) => {
      res.writeHead(200);
      res.end('hello world\n');
    }).listen(8000); 
    

    Note that if want to use Let's Encrypt's certificates using the certbot tool, the private key is called privkey.pem and the certificate is called fullchain.pem:

    const certDir = `/etc/letsencrypt/live`;
    const domain = `YourDomainName`;
    const options = {
      key: fs.readFileSync(`${certDir}/${domain}/privkey.pem`),
      cert: fs.readFileSync(`${certDir}/${domain}/fullchain.pem`)
    };