How can I add a middleware in my route?

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."


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.


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');
        }
    }
});

Tags:

Hapijs