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/'),
  cert: fs.readFileSync('/certs/')
const init = async () => {
    const server = Hapi.server({
        port: 443,
        host: '',
        tls : tls
        method: 'GET',
        path: '/',
        handler: (request, h) => {
            return 'Hello World!';
    await server.start();
    console.log('Server running on %s',;
process.on('unhandledRejection', (err) => {

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 *