Self-Signed, Trusted Certificates for Node.js &  Express.js

Get Your Express.js App Working on https://localhost

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.

Create a key and certificate

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.

Configure Express.js to use our self-signed SSL certificate

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 );
} );

Accept the certificate on your host machine

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.

Mac OS X

  1. Open the “Keychain Access” application, in Finder > Applications > Utilities
  2. Drag and drop the cert file into the application window
  3. Select “Always Trust” in the dialog box which appears, or alternatively double click on the certificate with the name localhost under the “Certificates” category
  4. Restart your browser and open up https://localhost to see your trusted, SSL localhost setup in action

Meet the Author

Kevin Leary, WordPress Consultant

I'm a custom WordPress web developer and analytics consultant in Boston, MA with 17 years of experience building websites and applications. View a portfolio of my work or request an estimate for your next project.