In express I have something like this:
router.get('/foo', middlewareFunction, function (req, res) {
res.send('YoYo');
});
What is the form for a middleware in hapi? When I have this:
server.route({
method: 'GET',
path: '/foo',
handler: function (request, reply) {
reply('YoYo');
}
})
The route pre option allows defining such pre-handler methods, please have a look at http://hapijs.com/api#route-prerequisites
const Hapi = require('hapi');
const server = new Hapi.Server();
server.connection({ port: 80 });
const pre1 = function (request, reply) {
return reply('Hello');
};
const pre2 = function (request, reply) {
return reply('World');
};
const pre3 = function (request, reply) {
return reply(request.pre.m1 + ' ' + request.pre.m2);
};
server.route({
method: 'GET',
path: '/',
config: {
pre: [
[
// m1 and m2 executed in parallel
{ method: pre1, assign: 'm1' },
{ method: pre2, assign: 'm2' }
],
{ method: pre3, assign: 'm3' },
],
handler: function (request, reply) {
return reply(request.pre.m3 + '\n');
}
}
});
You can use the server.ext property to register an extension function in one of the available extension points.
For example:
server.ext('onRequest', function (request, reply) {
// do something
return reply.continue();
});
This feature might be useful. It all depends in what you want to do with the middleware.
In Hapi v17 and above, you can use following code
const server = new Hapi.Server({
host: settings.host,
port: settings.port,
routes: {cors: {origin: ['*'] } }
});
server.ext('onRequest',async (req, h)=>{
req.firebase = 'admin'; // This adds firebase object to each req object in HAPI
return h.continue; // This line is important
})
Now access the req.firebase object in your routes like this:
{
method: 'POST',
path: '/helper/admin-object',
options: {
handler: async (req, h)=>{
console.log(req.firebase); // Prints admin
return true;
},
}
},
In addition to @gastonmancini answer, if you are using v17 and above, you might want to use:
server.ext('onRequest', (request, h) => {
// do something
return h.continue;
});
According to hapi docs:
"Return h.continue instead of reply.continue() to continue without changing the response."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With