Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passport.js - passing {user: req.user} to template implicitly?

Using Passport.js and Express for multiple projects now, I have noticed myself doing this over and over again, namely specifying { user: req.user } explicitly for my Express routes. Ocassionally I forget to pass it, and suddenly it's like user is not even logged in anymore.

How can I pass a user variable in my routes without having to explicitly write it for each route like this?

app.get = function(req, res, next) {
    res.render('home', {
        title: 'Home',
        user: req.user
    });
};

I think everyauth has such Express helper, but does Passport.js?

like image 523
Sahat Yalkabov Avatar asked Jan 03 '14 20:01

Sahat Yalkabov


1 Answers

You could use a simple middleware for that:

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

This will make a user variable available in all templates, provided that req.user is populated. Make sure that you declare that middleware after you declare the passport.session middleware, but before any routes.

like image 137
robertklep Avatar answered Nov 14 '22 19:11

robertklep