How do I setup a SSL certificate for an express.js server?


Before, in an older version of express, I could do this:

express.createServer({key:'keyFile', cert:'certFile'});

However, in newer versions of express this no longer works:

var app = express();

Should I call app.use() to set the certs? If so how?

8/27/2017 9:03:48 AM

Accepted Answer

See the Express docs as well as the Node docs for https.createServer (which is what express recommends to use):

var privateKey = fs.readFileSync( 'privatekey.pem' );
var certificate = fs.readFileSync( 'certificate.pem' );

    key: privateKey,
    cert: certificate
}, app).listen(port);

Other options for createServer are at:

12/17/2014 5:29:22 PM

I was able to get SSL working with the following boilerplate code:

var fs = require('fs'),
    http = require('http'),
    https = require('https'),
    express = require('express');

var port = 8000;

var options = {
    key: fs.readFileSync('./ssl/privatekey.pem'),
    cert: fs.readFileSync('./ssl/certificate.pem'),

var app = express();

var server = https.createServer(options, app).listen(port, function(){
  console.log("Express server listening on port " + port);

app.get('/', function (req, res) {
    res.end("hello world\n");

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow