Search code examples
node-moduleshapi.js

What is the difference between hapi.js plugins and nodejs modules


Just started familiarizing myself with Hapi. Hapi uses plugins to add components to your application. I'm having a hard time understanding why i would use plugins when i could just do something like:

var lib = require('whatever lib from npm');

What are the differences between the two?


Solution

  • Hapi Plugins are also node modules, but they are node modules which were built according to the Hapi Plugin API (they expose a register method that register the plugin with your Hapi pack/server)

    Plugins can automatically add routes to your server, change the request, payload and response, and in general can change how Hapi behaves.

    So in short Plugins are Node modules written specifically to augment Hapi.

    Lets look at two packages lout and Lo-Dash. Lo-Dash module as you might know is high performence js tool set. lout is a Hapi plugin that will add a /doc route to your app and. you can find both on npm and lets start with lout -

    var Hapi   = require('hapi'),
        lout   = require('lout'),      
        server = new Hapi.Server(80);  
    
    server.pack.register({ 
            plugin: lout
        }, function() {
            server.start();
        }
    );
    

    As you can see All we need to do is register lout with our server pack and all its magic is available to us (some plugins will require more options)

    now lets use lodash in our code

    var Hapi   = require('hapi'),
        lout   = require('lout'),
        _      = require('lodash'),
        preset = { app: { name: "myApp"}},
        server;
    
    if (process.env.DEBUG) {
        _.extend(preset, {debug: {request: ['error']});
    }
    
    server = new Hapi.Server(80, preset);
    
    _.extend(preset, { endpoint: '/lout'});
    server.pack.register({ 
            plugin: lout
        }, function() {
            server.start();
        }
    );
    

    here we use lodash to extend our server setting and configure our server to log errors to the console if we set the DEBUG environment parameter when running the server. note that lodash has no idea about our Hapi server and how it works it just uses as an helper and the programmer needs to know how to stitch them together.

    Calling lodash with server.pack.register will have no meaning and would result in an error. So this wont work -

    server.pack.register({ 
            plugin: require('lodash')
        }, function() {
            server.start();
        }
    );