Wexoni Wexoni - 2 months ago 7
Javascript Question

Hapi.js -- Set X-Authorization header

I would like to implement X-Authorization to my routes in Hapi.js. So when I make a request, I will create a X-Auth header and I would like Hapi to check it before allowing some code execution:

Based on this code example from Hapi documentaiton, how Do I implement it?

server.route({
method: 'GET',
path: '/hello/{user?}',
handler: function (request, reply) {
const user = request.params.user ? encodeURIComponent(request.params.user) : 'stranger';
reply('Hello ' + user + '!');
},
config: {
description: 'Say hello!',
notes: 'The user parameter defaults to \'stranger\' if unspecified',
tags: ['api', 'greeting']
}
});

Answer

You can use headers property of request object to get X-Authorization value. However, it should be request.headers['x-authorization'] (all lowercase).

Please refer to http://hapijs.com/api#request-properties for document.