Returning Custom Headers With Hapi JS

This article refers to an older version of Hapi and the server configuation is now handled differently, but the gist is still the same.

I am probably the biggest fanboy around when it comes to Hapi JS. I also recommend the excellent Joi validation and Swagger API documentation generator plugins too. I have used Hapi to build all of my recent API's and I think it works quicker and easier than comparable frameworks like Express - especially once I refactored it down into auto-loading new routes.

Anyway, when creating an endpoint to paginate a GET request I found a useful little tidbit of information I wanted to share. I needed to return the total results as part of the response header. The common consensus for this is to use a x-total-count parameter with this value.

To allow Hapi to return these headers though, you need to add them to the server configuration like so;

var server = new Hapi.Server({
  connections: {
    routes: {
      cors: {
        credentials: true,
        exposedHeaders: ['x-total-count']
      }
    }
  }
});

In your handler for a route, remember to set the header in the reply you send back to the client, I used a snippet like this;

reply(json)
  .header('X-Total-Count', totalCount);