Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HAPI JS Node js creating https server

Tags:

node.js

hapijs

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)

like image 956
Sathish Avatar asked Jan 03 '15 04:01

Sathish


People also ask

Can you create an HTTPS Web server with node js?

To create an HTTPS server, you need two things: an SSL certificate, and built-in https Node. js module. We need to start out with a word about SSL certificates. Speaking generally, there are two kinds of certificates: those signed by a 'Certificate Authority', or CA, and 'self-signed certificates'.


2 Answers

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');
});
like image 146
Fernando Avatar answered Sep 22 '22 04:09

Fernando


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.

like image 29
codelion Avatar answered Sep 25 '22 04:09

codelion