Search code examples
proxylegacyhapi.js

Check existing routes in Hapi proxy handlers


Scenario: I have an existing legacy application which has lots of routes. I am developing HAPI API which has all new routes. I will convert all existing routes into hapi over time. If incoming route does not match with existing HAPI routes, I will forward those into legacy system.

How can i check my all current hapi routes for incoming route request before forwarding it to other legacy system? Any kind of example, advice will be appreciable.


Solution

  • This is a good use case for the h2o2 plugin. It's a proxy handler plugin for hapi.

    Register the plugin:

    const Hapi = require('hapi');
    const server = new Hapi.Server();
    
    server.register({
        register: require('h2o2')
    }, function (err) {
    
        if (err) {
            console.log('Failed to load h2o2');
        }
    
        server.start(function (err) {
    
            console.log('Server started at: ' + server.info.uri);
        });
    });
    

    Create a hapi route that will forward requests to another:

    server.route({
        method: 'GET',
        path: '/',
        handler: {
            proxy: {
                uri: 'https://some.upstream.service.com/that/has?what=you&want=todo'
            }
        }
    });
    

    You can also add more complicated route handling if you need it. Check out the documentation.