Hapi

Returning Custom Headers With Hapi JS


This article refers to an older version of Hapi and the server configuration 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 - <i>especially</i> 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);

javascript
node
architecture
api

A tech native with 20 years of experience across the digital space. Darryl is an evangelist for the power and disruption of blockchain technologies and fosters a passion for bringing ever greater utility and adoption to the masses.

Related Articles

Babel

Fixing Uglify Errors With Babel

npm

Commercial Licenses for NPM Packages

Hapi

API Design: PUT vs PATCH

Copyright © 2016-2024 Bonbon Group Ltd. All Rights Reserved.