Enabling https in a node js app on windows

Whilst developing my knockout dependency tracking application I realised I had to support access to it over https instead of http. This is because the website we’re currently developing and all of the web services it talks to are secured via federated identity. Ideally we would be able to simply flick a switch to use http during development, but unfortunately I don’t believe this is possible.

The application I’m building doesn’t really need to be secure because there’s no sensitive content being accessed, plus it’s intended to be hosted and browsed to locally without being exposed over the internet. Therefore we can just use a self-signed certificate (these are often used in development before being replaced by one issued by an external authority for use in production).

If you’re using windows and want to enable SSL in your node app there’s a few simple steps to take. Firstly create the self-signed certificate:

  1. Open IIS manager
  2. Open Server Certificates
  3. Click Create Self-Signed Certificate
  4. Enter a friendly name
  5. Press OK
  6. Click export
  7. Choose the directory of your application and give it a simple password. IIS manager creates it as a .pfx and you can read more about the different types here

Now that you have the certificate you need to write the server-code to read it. The following is taken from the node api site.

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

var options = {
  pfx: fs.readFileSync('server.pfx'),
  passphrase: 'password' //Enter the password that you chose when creating the certificate
};

https.createServer(options, function (req, res) {
  res.writeHead(200);
  res.end("hello world\n");
}).listen(8000);

And voila! Browse to your site using https and you’re good to go.

Leave a comment