Skip to content

Instantly share code, notes, and snippets.

@romainl
Created August 9, 2018 19:19
Show Gist options
  • Save romainl/f265f6ab644f39c5bfe109f89fb74a5d to your computer and use it in GitHub Desktop.
Save romainl/f265f6ab644f39c5bfe109f89fb74a5d to your computer and use it in GitHub Desktop.
HTTPS support in Express

Create path/to/cert.template

[req]
distinguished_name = req_distinguished_name
x509_extensions = v3_req
prompt = no
  [req_distinguished_name]
C = XX
ST = XX
L = XX
O = XX
OU = XX
CN = localhost
  [v3_req]
keyUsage = critical, digitalSignature, keyAgreement
extendedKeyUsage = serverAuth
subjectAltName = @alt_names
  [alt_names]
DNS.1 = localhost
IP.1 = 127.0.0.1
  • C means "Country", a two-letters country code like US or FR
  • ST means "State", a string
  • L means "Locality", a string
  • O means "Organization", a string
  • OU means "Organization Unit", a string
  • CN means "Common Name", a string

Create a cert directory in your app

$ cd path/to/myapp
$ mkdir cert

Generate certificate in cert/ from the template

$ openssl req -x509 -nodes -days 730 -newkey rsa:2048 -keyout localhost.key -out localhost.cert -config path/to/cert.template -sha256

You should get two files:

cert/localhost.cert
cert/localhost.key

Use them in app.js

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

const app = express();

// Start HTTP server
http.createServer(app).listen(3100, () => {
	console.log(`HTTP Server listening on port 3100...`);
});

// Start HTTPS server
https.createServer({
	key: fs.readFileSync('cert/localhost.key').toString(),
	cert: fs.readFileSync('cert/localhost.cert').toString()
}, app).listen(443, () => {
	console.log('HTTPS Server listening on port 443...');
});

Tell your system to trust your self-signed certificate

MacOS

$ sudo security add-trusted-cert -d -r trustAsRoot -k /Library/Keychains/System.keychain cert/localhost.cert

Debian/Ubuntu

$ sudo cp cert/localhost.cert /usr/local/share/ca-certificates/
$ sudo update-ca-certificates
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment