3

is there any alternate for using session variables in jade template file other than using dynamic helper function and passing it through res.render? if i use dynamichelpers method its showing error since it is deprecated. please help

app.use(function(req, res, next){
            res.locals.user = "xxxx";
            next(); 
        }); 

i used this code in app.js inside app.configure function. but still i couldn't use the variable user in my view. do i need to install any additional packages or any other code?

Jagan
  • 41
  • 4

1 Answers1

1

This code should work. For example, I'm using nearly identical code in one of my production systems:

app.use(function (req, res, next) {
    app.locals.token = req.session._csrf;
    app.locals.user = req.user;
    ...
    next();
});

You'll need to make sure this code is after you set req.locals.user - for example, if you are using Passport, after you do the initialize and session code, but before you actually handle and render the request.

Michael Pratt
  • 3,438
  • 1
  • 17
  • 31
  • What is the purpose of next() in this case? I know it can be useful for user authentication functions, but if you are just setting app.locals do we need next()? I removed next() and it still works fine without it. – Sahat Yalkabov Apr 21 '13 at 23:40
  • The next() call, without an error, indicates that this middleware is complete but further middleware needs to be executed as well. If you do not call next(), I don't believe any further middleware is executed. – Michael Pratt Apr 24 '13 at 06:46
  • I think you only need next if you want to pass something on to the next piece of middleware. 'Use' adds the next func in the chain to be called. Next gives it an argument. – Erik Reppen Dec 14 '14 at 20:47