Search code examples
node.jsurl-routinghapi.js

HapiJS global path prefix


I'm writing an API on HapiJS, and wondering how to get a global prefix. For example, all requests should be made to:

https://api.mysite.com/v0/...

So I'd like to configure v0 as a global prefix. The docs (here) don't seem to mention it -- is there a good way to do this in HapiJS?


Solution

  • If you put your API routing logic inside a Hapi plugin, say ./api.js:

    exports.register = function (server, options, next) {
    
        server.route({
            method: 'GET',
            path: '/hello',
            handler: function (request, reply) {
                reply('World');
            }
        });
    
        next();
    
    };
    
    exports.register.attributes = {
        name: 'api',
        version: '0.0.0'
    };
    

    You register the plugin with a server and pass an optional route prefix, which will be prepended to all your routes inside the plugin:

    var Hapi = require('hapi');
    
    var server = new Hapi.Server()
    server.connection({
        port: 3000
    });
    
    server.register({
        register: require('./api.js')
    }, {
        routes: {
            prefix: '/v0'
        }
    },
    function(err) {
    
        if (err) {
            throw err;
        }
    
        server.start(function() {
            console.log('Server running on', server.info.uri)
        })
    
    });
    

    You can verify this works by starting the server and visiting http://localhost:3000/v0/hello.