Search code examples
node.jsglobal-variablesuser-agentsails.jscontrollers

Global variable across all controllers in Node JS


I am trying to have a variable which can be accessible by all controllers in my node project. Currently in one controller I have:

        var ua = req.headers['user-agent'];
        var isMobile = "no";
        if(/mobile/i.test(ua))
            isMobile="yes";

It's pointless to copy past all of this for all my controllers and pass the isMobile variable to the view. I'd like to get the value of isMobile set once, and then pass it wherever I want from my controllers.

Is there an easy way to do this rather than have those 4 lines of code copy pasted in every controller?

Thanks


Solution

  • You'll want to use a Sails policy for this:

    // /api/policies/isMobile.js
    module.exports = function(req, res, next) {
       var ua = req.headers['user-agent'];
       req.isMobile = /mobile/i.test(ua);
       next();
    }
    

    // /config/policies.js
    module.exports.policies = {
    '*': 'isMobile'
    };
    

    This will run the code before every controller action, and give you access to the req.isMobile var in all of your custom controller code.