HAPI JS Node js creating https server

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');
});

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.

Tags:

Node.Js

Hapijs