Reputation: 2180
How do I create a hapi http
and https
server, listening on both 80 and 443 with the same routing?
(I need a server which should run both on http and https with the exact same API)
Upvotes: 13
Views: 18760
Reputation: 550
In reply to the selected answer: this does not work anymore, removes in version 17 :
https://github.com/hapijs/hapi/issues/3572
You get :
TypeError: server.connection is not a function
Workaround is either using a proxy or creating 2 instances of Hapi.Server()
Upvotes: 0
Reputation: 18009
I was looking for something like this and found out https://github.com/DylanPiercey/auto-sni which has an example usage with Express, Koa, Hapi (untested)
It's basically based on letsencrypt certificates and load hapi server using a custom listener.
Haven't tried it yet.
Upvotes: 0
Reputation: 9191
You can also use the local-ssl-proxy npm package to proxy local HTTPS to HTTP. For local development only.
Upvotes: 0
Reputation: 1273
It may not be usual to handle the https requests directly on the application, but Hapi.js can handle both http and https within the same API.
var Hapi = require('hapi');
var server = new Hapi.Server();
var fs = require('fs');
var tls = {
key: fs.readFileSync('/etc/letsencrypt/live/example.com/privkey.pem'),
cert: fs.readFileSync('/etc/letsencrypt/live/example.com/cert.pem')
};
server.connection({address: '0.0.0.0', port: 443, tls: tls });
server.connection({address: '0.0.0.0', port: 80 });
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
reply('Hello, world!');
}
});
server.start(function () {
console.log('Server running');
});
Upvotes: 24
Reputation:
Visit Link: http://cronj.com/blog/hapi-mongoose
Here is a sample project which can help you with this.
For hapi version earlier than 8.x
var server = Hapi.createServer(host, port, {
cors: true
});
server.start(function() {
console.log('Server started ', server.info.uri);
});
For hapi new version
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: app.config.server.port });
Upvotes: 1
Reputation: 19578
@codelion has given a good answer, but if you still want to listen on multiple ports, you can pass multiple configs for connections.
var server = new Hapi.Server();
server.connection({ port: 80, /*other opts here */});
server.connection({ port: 8080, /*other opts, incl. ssh */ });
But to note again, it would be good to start depreciating http connections. Google and others will soon start marking them insecure. Also, it would probably be a good idea to actually handle SSL with nginx or something, not on node app itself.
Upvotes: 3
Reputation: 1066
You can redirect all http requests to https instead :
if (request.headers['x-forwarded-proto'] === 'http') {
return reply()
.redirect('https://' + request.headers.host + request.url.path)
.code(301);
}
Check out https://github.com/bendrucker/hapi-require-https for more details.
Upvotes: 7