Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS + session object in ALL views without passing it on all controller actions

I want my session to be available in all views (*.ejs) without having to pass it on every single action. My code is shown below, but the req.session object is always null here, even though in my "controllers" I can access a session object after an user has authenticated, by specifying:

req.session.whatever

My initialization code (that is currently executed on every single request (I double checked with a debug breakpoint) is:

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

    if(req.session != null && req.session.user != null)
    {
        res.locals.user = req.session.user;
    }

    next(null, req, res);
};

I register this function in the app setup preamble:

app.use(appendLocalsToUseInViews);

I have seen people use app.use methods and dynamicHelpers. I am using express 3, and it seems they are gone, deprecated from Express 2... But that does not seem to be the point, as the function is being called correctly on every single request. How to I access the Express session in this sort of pre-controller code?

Thanks!

SOLUTION thanks Jani Hartikainen:

I moved the code to after the session middleware is loaded and its working!!! Here is the new code.

    app.use(express.cookieParser(appSecret));
    app.use(express.session({ secret: appSecret }));

    ---->>>app.use(appendLocalsToUseInViews);
like image 844
João Rocha da Silva Avatar asked Sep 12 '13 13:09

João Rocha da Silva


1 Answers

This should work but make sure your app.use for this is only after you have initialized your session middleware. If you have this before the initialization for the session middleware, it will be ran before it in the chain, and thus the data will not be available.

like image 131
Jani Hartikainen Avatar answered Nov 15 '22 04:11

Jani Hartikainen