On this page

    M

    https.createServer

    History
    https.createServer(options?, requestListener?): https.Server
    Attributes
    requestListener:Function
    A listener to be added to the 'request' event.
    Returns:https.Server
    // curl -k https://localhost:8000/
    import { createServer } from 'node:https';
    import { readFileSync } from 'node:fs';
    
    const options = {
      key: readFileSync('private-key.pem'),
      cert: readFileSync('certificate.pem'),
    };
    
    createServer(options, (req, res) => {
      res.writeHead(200);
      res.end('hello world\n');
    }).listen(8000);
    // curl -k https://localhost:8000/
    const https = require('node:https');
    const fs = require('node:fs');
    
    const options = {
      key: fs.readFileSync('private-key.pem'),
      cert: fs.readFileSync('certificate.pem'),
    };
    
    https.createServer(options, (req, res) => {
      res.writeHead(200);
      res.end('hello world\n');
    }).listen(8000);

    Or

    import { createServer } from 'node:https';
    import { readFileSync } from 'node:fs';
    
    const options = {
      pfx: readFileSync('test_cert.pfx'),
      passphrase: 'sample',
    };
    
    createServer(options, (req, res) => {
      res.writeHead(200);
      res.end('hello world\n');
    }).listen(8000);
    const https = require('node:https');
    const fs = require('node:fs');
    
    const options = {
      pfx: fs.readFileSync('test_cert.pfx'),
      passphrase: 'sample',
    };
    
    https.createServer(options, (req, res) => {
      res.writeHead(200);
      res.end('hello world\n');
    }).listen(8000);

    To generate the certificate and key for this example, run:

    openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \
      -keyout private-key.pem -out certificate.pem

    Then, to generate the pfx certificate for this example, run:

    openssl pkcs12 -certpbe AES-256-CBC -export -out test_cert.pfx \
      -inkey private-key.pem -in certificate.pem -passout pass:sample