If you want to fully replicate an https/SSL Node.js/Express app server locally you’ll need a self-signed AND trusted certificate setup. More often than not I see dev’s settle with an untrusted state for their localhost, which is an annoying and frustrating work around. I don’t want to tell Chrome and Safari that I trust the website every single time I open it up. Luckily there’s a way around this, just follow the steps below on your mac to get https://localhost
serving your Express.js Node app loading with SSL locally.
First we’ll need to generate a key and corresponding certificate. Open up Terminal and use the following commands to do this.
openssl genrsa -out localhost.key 2048
openssl req -new -x509 -key localhost.key -out localhost.cert -days 3650 -subj /CN=localhost
If you want to use a host other than localhost
then replace every reference to “localhost” above witb your custom domain.
Now that we have a self-signed SSL certificate setup for our localhost we can configure our Express 4.x server for https using the following snippet.
#!/usr/bin/env node
var https = require('https');
var fs = require('fs');
var express = require('express');
var options = {
key: fs.readFileSync( './localhost.key' ),
cert: fs.readFileSync( './localhost.cert' ),
requestCert: false,
rejectUnauthorized: false
};
var app = express();
var port = process.env.PORT || 443;
var server = https.createServer( options, app );
server.listen( port, function () {
console.log( 'Express server listening on port ' + server.address().port );
} );
In order to make the self-signed certificate trusted we need to accept it as a valid certificate on our machine. Doing this will replace red warning (“Unsecured”) notices with a green lock, fully replicating a https/SSL website on localhost for testing.