How to create an HTTPS server in Node.js? How to create an HTTPS server in Node.js? javascript javascript

How to create an HTTPS server in Node.js?


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.http.createServer(app).listen(80);// Create an HTTPS service identical to the HTTP service.https.createServer(options, app).listen(443);


I found following example.

https://web.archive.org/web/20120203022122/http://www.silassewell.com/blog/2010/06/03/node-js-https-ssl-server-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.setSecure(credentials);server.addListener("request", handler);server.listen(8000);


Found this question while googling "node https" but the example in the accepted answer is very old - taken from the docs of the current (v0.10) version of node, it should look like this:

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