Hapi.js load plugins in order

You will want to use server.dependency as a solution.

With it, you can declare a plugin dependent upon another and if the dependency is missing (or you accidentally create a circular dependency) your server will throw.

With this, you have an opportunity to use the after function to delay execution of code in Plugin2 that must wait until Plugin1 is loaded.

You can also see discussion titled "Inconsistent plugin load order" on the glue github repo or this one called "Server start can fail due to plugins not loaded in the right order" from aqua for additional info and details.


You have a few options available to you.

You could take a look at Glue. You can use the array syntax for plugins to load plugins in a specific order:

var Glue = require('glue');

var manifest = {
    server: {
        cache: 'redis'
    },
    connections: [
        {
            port: 8000,
            labels: ['web']
        },
        {
            port: 8001,
            labels: ['admin']
        }
    ],
    plugins: [
        { 'Plugin1': null },
        { 'Plugin2': null }
    ]
};


var options = {
    relativeTo: __dirname
};

Glue.compose(manifest, options, function (err, server) {

    if (err) {
        throw err;
    }
    server.start(function () {

        console.log('Hapi days!');
    });
});

This is same as doing the following without the use of Glue:

server.register(require('Plugin1'), function (err) {

    server.register(require('Plugin2'), function (err) {

        server.start(function () {

            console.log('Hapi days!');
        });
    });
});

Having order-dependent plugins is messy though and hapi offers a better way to fix this. You can use server.dependency() to explictly express a plugin's dependency on another plugin. So inside Plugin2 you could do:

var ready = function (server, next) {

    server.route({
        ...
    });

    next();
};

exports.register = function (server, options, next) {

    server.dependency('Plugin1', ready);
    next();
};

exports.register.attributes = { 
    name: 'Plugin2',
    version: '0.0.1'
};

With this approach, it doesn't matter about the plugin registration order. This is great for big apps where there's lot of plugins worked on by different people or teams.