wizplum wizplum - 4 months ago 74
Node.js Question

Migrating HTTPS server from Express to Hapi

I'm trying to migrate an HTTPS server from Express to Hapi. The server is running fine on Express, but when I try to run it in Hapi I get messages saying "Invalid server options" and "TLS is not allowed".

This is my (simplified) code with Express:

var fs = require('fs');
var https = require('https');
var app = require('express')();
var options = {
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.crt')
};

app.get('/', function (req, res) {
res.send('Hello World!');
});

https.createServer(options, app).listen(8081);


And this is my (simplified) code with Hapi:

var fs = require('fs');
var Hapi = require('hapi');

var options = {
tls: {
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.crt')
}
};
var server = new Hapi.Server(options);

server.connection({ host: 'localhost', port: 8081 });

server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
return reply('Hello world!');
}
});

server.start();


I'm using a self-signed certificate, but I guess that should be fine? It does work in Express.

Answer

Your code looks pretty close. I believe all you have to do to get Hapi to use your certificate and key is to just move it over to the server.connection call, such as:

server.connection({
  host: 'localhost', 
  port: 8081,
  tls: {
    key: fs.readFileSync('server.key'),
    cert: fs.readFileSync('server.crt')
  }
});