Creating a plugin

Let's copy the app folder from our main recipe to the custom-plugin-app and create a plugins folder with an answer.js file:

$ cp -fr app custom-plugin-app
$ cd custom-plugin-app
$ mkdir plugins
$ touch plugins/answer.js

We'll make the contents of plugins/answer.js look like so:

module.exports = answer 
 
function answer (server, options, next) { 
  server.ext('onPreResponse', (request, reply) => { 
    request.response.header('X-Answer', 42) 
    reply.continue() 
  }) 
  next() 
} 
 
answer.attributes = {name: 'answer'} 

The next callback is supplied to allow for any asynchronous activity. We call it to let Hapi know we've finished setting up the plugin. Under the hood Hapi would call the server.register callback once all the plugins had called their respective next callback functions.

Events and Extensions
There are a variety of server events (which we can listen to with server.on) and extensions. Extensions are very similar to server events, except we use server.ext to listen to them and must call reply.continue() when we're ready to proceed. See https://hapijs.com/api#request-lifecycle as a starting point to learn more.

We use the onPreResponse extension (which is very much like an event) to add our custom header. The onPreResponse extension is the only place we can register headers (the onRequest extension is too early and the response event is too late).

We'll add the answer plugin near the top of the index.js file like so:

const answer = require('./plugins/answer') 

Then at the bottom of index.js we'll modify the boot up code to the following:

const plugins = dev ? [answer, inert] : [answer] 
server.register(plugins, start) 
 
function start (err) { 
  if (err) throw err 
 
  routes.index(server) 
   
  if (dev) routes.devStatic(server) 
 
  server.start((err) => { 
    if (err) throw err 
    console.log(`Server listening on port ${port}`) 
  }) 
}