Search code examples
node.jshapi.js

Cannot read property 'register' of undefined after installing inert in hapi


I started working with Hapi framework of nodejs. I am using Hapi "version": "16.0.0". I was trying to load static pages and content with Hapi and for that i installed "inert" plugin with the help of command npm install --save inert. Here is my code which i included in my server.js file as given below.

    server.register(require('inert'), (err) => {
        if (err) {
            throw err;
        }
        server.route({
            method: 'GET',
            path: '/hello',
            handler: function (request, reply) {
                reply.file('./public/hello.html');
            }
        });
    });

After running project with node server.js I am getting following error.

/Library/WebServer/Documents/pro_hapi/node_modules/hapi/lib/plugin.js:219
        if (plugin.register.register) {                             // Required plugin
                            ^

TypeError: Cannot read property 'register' of undefined
    at module.exports.internals.Server.internals.Plugin.register (/Library/WebServer/Documents/pro_hapi/node_modules/hapi/lib/plugin.js:219:29)
    at Object.<anonymous> (/Library/WebServer/Documents/pro_hapi/server.js:16:8)
    at Module._compile (module.js:635:30)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at Function.Module.runMain (module.js:676:10)
    at startup (bootstrap_node.js:187:16)
    at bootstrap_node.js:608:3

Solution

  • I searched for that and i found a solution which conclude following things

    1. Installing inert plugin with command npm install inert --save will install inert version 5.x by default.
    2. Inert version 5.x has breaking changes for hapi v17 support. That means for hapi "version": "16.0.0", like I am using will need to use Inert v4.x or, to use Inert v5 you will need to update to hapi v17.
    3. For installing npm older package version we need to run following command. npm install <package>@<version>

    In my case i run sudo npm install [email protected] --save which overwrite existing inert package(5.x) with inert version 4.2.1.

    1. Finally I again run my project with node server.js and this time it worked.