Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS (Express.js) : How to make the Session global

I know that global vars are a bad practice in javascript and in programming overall, but i want to make my user session available throughout my express.js app, avoiding having to pass the session parameter all over, from my controllers to my models.

How can I best do this?

Thanks!

like image 858
João Rocha da Silva Avatar asked Jan 16 '14 14:01

João Rocha da Silva


1 Answers

I ended up solving this like so:

var appendLocalsToUseInViews = function(req, res, next)
{            
    //append request and session to use directly in views and avoid passing around needless stuff
    res.locals.session = req.session;
    next(null, req, res);
}

Then add it to the middleware:

app.use(appendLocalsToUseInViews);
like image 168
João Rocha da Silva Avatar answered Sep 19 '22 07:09

João Rocha da Silva