Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass variables from Connect's middleware into app.get-action?

I would like to create kind of a before filter which allows me to make the current user available in all actions. The followint approach works well and I didn't even need to declare a global variable:

app.use(function(req, res, next){
    if(req.session.user_id){
        /* Get user from database
           and share it in a variable
           that can be accessed frooom ...
        */
        User.find({ /* ... */ }, function(err, users){
            if(users.length == 1){
                req.current_user = users[0];
            }
            next();
        });
    }
    else{
        next();
    }
});

app.get('/', function(req, res){
    // ... here!!
    console.log(req.current_user);
    res.render('index', {
        current_user: req.current_user,
    });
});

But I'm still unsure if it is okay to manipulate req because I don't know if it's right to change something that's not owned by me? Is there a better way to do this?

like image 785
YMMD Avatar asked May 02 '12 10:05

YMMD


1 Answers

Go right ahead and tack on properties to req! When I was first starting out with Node.js and JavaScript, this felt very odd to me too (coming from a predominately C++ background). It is, however, quite natural given JavaScript's prototypical object model. After you get comfortable with it, you'll realize that you can do powerful things in succinct code.

I'm the developer of Passport (mentioned by the previous commenter). If you are planning on developing middleware that can be reused across apps, my advice is to pay a bit of attention to how you name the properties that you add to req or res, to avoid any potential conflict with other middleware in the same application.

For example, Passport sets the user at req.user, but gives an option to change that (so an app can say set it at req.currentUser, for example.). Internal, private variables are attached to a req._passport property.

like image 71
Jared Hanson Avatar answered Nov 15 '22 21:11

Jared Hanson