How to create an HTTPS server in Node.js?


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

5/1/2018 10:57:04 AM

Accepted Answer

I found following example.

This works for node v0.1.94 - v0.3.1. server.setSecure() is removed in newer versions of node.

Directly from that source:

const crypto = require('crypto'),
  fs = require("fs"),
  http = require("http");

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

var credentials = crypto.createCredentials({key: privateKey, cert: certificate});

var handler = function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');

var server = http.createServer();
server.addListener("request", handler);
6/16/2018 3:43:45 PM

The Express API doc spells this out pretty clearly.

Additionally this answer gives the steps to create a self-signed certificate.

I have added some comments and a snippet from the Node.js HTTPS documentation:

var express = require('express');
var https = require('https');
var http = require('http');
var fs = require('fs');

// This line is from the Node.js HTTPS documentation.
var options = {
  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.cert')

// Create a service (the app object is just a callback).
var app = express();

// Create an HTTP service.
// Create an HTTPS service identical to the HTTP service.
https.createServer(options, app).listen(443);

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow