i’ve been working with node a lot lately and i’m surprised that i haven’t needed to do this sooner, but i finally needed to set up SSL for one of my node apps and it wasn’t hard to do, but there was no one place where all of the steps were documented on how to setup SSL using express. it actually is pretty straightforward and easy.
first you need to create a certificate for SSL. this can be done by using the command line tool: openssl.
1 2 3 4 |
# first create a certificate for SSL openssl genrsa -out server-key.pem 1024 openssl req -new -key server-key.pem -out server-csr.pem openssl x509 -req -in server-csr.pem -signkey server-key.pem -out server-cert.pem |
once you have the certificate, all you have to do is tell node that you want to use the certificate you made for the SSL requests. what i didn’t know, but is actually very clearly documented in express’ api documentation is that the variable “app” returned by express() is actually a function used as a callback for node’s http to handle requests. so instead of starting up your server via an app.listen() call, you can simply go back to the basics and use node’s http and https APIs to start the server and pass express’ app to it.
if you want the same code to handle both http and https requests, you can simply call http and https’ createServer() method on different ports.
1 2 3 4 5 6 7 8 9 |
# now tell express to use the certificate http.createServer(app).listen(80); var httpsOptions = { key: fs.readFileSync('/path/to/cert/server-key.pem'), cert: fs.readFileSync('/path/to/cert/server-cert.pem') }; https.createServer(httpsOptions, app).listen(443); |
How would you set up one for Express on Windows?
you *could* setup cygwin and install openssl through cygwin, but if i wanted to do node development on windows, i’d install a linux VM. eventually, the node module dependencies that you want to use will require you to compile libraries and it’s too much of a pain for me in windows to bother.