Search code examples
node.jshapi.js

Returning 401 error for all routes with hapijs


We're using Hapi JS for our rest server. We store the authentication tokens for the users on Redis. Now, if for some reason node loses connection with Redis, we need to return 401 Authorization failed error to all the clients from all the routes so the clients can logout automatically.

So, is there a way to return 401 from all routes without changing the code in the route handler functions?


Solution

  • You can make use of the Hapi server extension event 'onRequest'.

    var hapi = require('hapi');
    var Boom = require('boom');
    
    var server = new hapi.Server();
    //Configure your server
    
    //Add an extension point
    
    server.ext('onRequest', function (request, reply) {
        var status;
        //Check status of redis instance
    
        if (status) {
            //Redis is running, continue to handler
            return reply.continue();
        } else {
            //Redis is down, reply with error
            return reply(Boom.unauthorized('Auth server is down'));
        }
    });
    

    This is probably not how you will verify the status your redis instance, but I hope you get the point.

    One can look up various other extension points here.