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

Using Passport.js and Express for several projects, I noticed that I was doing it again and again, namely, explicitly specifying { user: req.user } for my Express routes. Ocassionally I forgot to transfer it, and suddenly he, as a user, did not even log in anymore.

How to pass user variable in my routes without explicitly writing 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 an express helper, but does Passport.js?

+8
source share
1 answer

To do this, you can use a simple intermediate link:

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

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

+28
source share

All Articles