JavaScript
hapi v16 vs. hapi v17

by Benny Neugebauer

// "hapi": "16.6.2",
// "inert": "4.2.1"

const Hapi = require('hapi');
const Inert = require('inert');
const path = require('path');

const server = new Hapi.Server();
server.connection({port: 3000});

const route = {
  method: 'GET',
  path: '/',
  config: {
    handler: (request, reply) => {
      reply('<a href="/pages/test.html">Test</a>');
    },
  }
};

const routeUsingInert = {
  method: 'GET',
  path: '/{param*}',
  config: {
    handler: (request, reply) => {
      reply.file(path.join(process.cwd(), 'pages', 'test.html'));
    }
  },
};

server.route([
  route,
  routeUsingInert
]);

server.register({
  register: Inert,
}, (error) => {
  if (error) throw error;
  server.start((error) => {
    if (error) throw error;
    console.log(`Server running at: ${server.info.uri}`);
  });
});

// "hapi": "17.0.1",
// "inert": "5.0.1"

const Hapi = require('hapi');
const Inert = require('inert');
const path = require('path');

const server = Hapi.Server({port: 3000});

const route = {
  method: 'GET',
  path: '/',
  options: {
    handler: (request, h) => {
      const html = '<a href="/pages/test.html">Test</a>';
      return h.response(html)
        .type('text/html')
        .code(200);
    },
  }
};

const routeUsingInert = {
  method: 'GET',
  path: '/{param*}',
  options: {
    handler: (request, h) => {
      return h.file(path.join(process.cwd(), 'pages', 'test.html'));
    }
  },
};

server.route([
  route,
  routeUsingInert
]);

server.register([{
  plugin: Inert
}])
.then(() => server.start())
.then(() => console.log(`Server running at: ${server.info.uri}`));

Hapi v16.x supports promises if no callback is provided, so really there's no difference in these examples concerning the Hapi versions.

Andrew Turner

@Andrew Turner, I can spot quite a few differences. Just to give some examples:

  • Instantiating a new server with new Hapi.Server became Hapi.Server

  • The server.connection() method has been replaced with options passed directly to Hapi.Server

  • Route configuration has been renamed from 'config' to 'options'

  • The reply method of a route handler has been replaced with a new response toolkit called h

  • A handler needs to return something

  • Plugin registration has been renamed from register to plugin

  • server.register & server.start support JavaScript's async await

Benny Neugebauer

Sign in to comment!