user3658423 user3658423 - 2 months ago 27
Node.js Question

nodejs express middleware function return value

Im using node.js and express, I have the following route and the middleware function isMobile. If I dont use return next(); in the isMobile function, the app gets stuck because nodejs does not move over to the next function.

But I need the isMobile function to return a value so I can process accordingly in the app.get. Any ideas?

app.get('/', isMobile, function(req, res){
// do something based on isMobile return value
});



function isMobile(req, res, next) {

var MobileDetect = require('mobile-detect');
md = new MobileDetect(req.headers['user-agent']);

//return md.phone(); // need this value back

return next();
}


Thanks

Answer

You have a couple of choices:

  1. Attach the value to the req object:

    app.get('/', isMobile, function(req, res){
       // Now in here req.phone is md.phone. You can use it:
       req.phone.makePrankCall();
    });
    
    function isMobile(req, res, next) {
        var MobileDetect = require('mobile-detect');
        md = new MobileDetect(req.headers['user-agent']);
    
        req.phone = md.phone();
        next();// No need to return anything.
    }
    

    This is how many of express/connect middlewares pass values. Like bodyParser which attaches body property to request object, or session middleware which attaches session property to request obejct.

Though note that you have to be careful that no other library uses that property, so there's no conflicts.

  1. Don't make it a middleware, just use the function directly. If it's not asynchronous like above, and not gonna be used globally for all routes(not gonna have something like this: app.use(isMobile)), this also a good solution:

    app.get('/', function(req, res){
       var phone = isMobile(req);
       phone.makePrankCall();
    });
    
    function isMobile(req) {
        var MobileDetect = require('mobile-detect');
        md = new MobileDetect(req.headers['user-agent']);
    
        return md.phone();
    }
    

If it's expensive to compute, and you might use it in more than one middleware you can cache it with a weakmap.