How to create an Https server on Hapi.js?

Hapi.js can handle both Http and Https while creating the server by default. But you can also use some plugin called https or http2 to create https. I will share with you those external plugins next posts. For now, let’s start with the Hapi default server.

First, you need to install the @hapi/hapi and fs plugins to your project.

$ npm install @hapi/hapi
$ npm install fs

Then, use the following sample code to create an Https server in server.js.

'use strict';
const Hapi = require('@hapi/hapi');
var fs = require('fs');
var tls = {
  key: fs.readFileSync('/certs/127.0.0.1.key'),
  cert: fs.readFileSync('/certs/127.0.0.1.cert')
};
const init = async () => {
    const server = Hapi.server({
        port: 443,
        host: '0.0.0.0',
        tls : tls
    });
  
    server.route({
        method: 'GET',
        path: '/',
        handler: (request, h) => {
            return 'Hello World!';
        }
    });
    await server.start();
    console.log('Server running on %s', server.info.uri);
};
process.on('unhandledRejection', (err) => {
    console.log(err);
    process.exit(1);
});
init();

Finally, run this command and hit it.

$ npm start server.js

That’s it. I hope this will help. ?

Leave a Reply

Your email address will not be published. Required fields are marked *