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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With