virattara virattara - 1 year ago 98
Javascript Question

Unable to access req.user in Passport.js on Express.js

not accessible anywhere except its origin function.

I read that passport attaches the user to every request after authentication.

I want to stop any user from accessing the inner pages through the url bar thus skipping the login page or if his session is already active he must be redirected to the user page. These two things can be done only if I get access to
in all the middlewares.

app.js link

app.js:-'/',passport.authenticate('local',{failureRedirect: '/'}),
console.log(req.user); //req.user defined here only not in users.js


router.get('/users', function(req, res, next) {


passport.deserializeUser(function(id, done) {
db.findById(id, function(err, user) {
done(err, user);
console.log(user) //undefined

Answer Source

It doesn't look like your app is set up to support sessions, which is generally what's needed for Passport to "remember" that a user has logged in, and to populate req.user.

The most common session middleware for Express is express-session, and it relatively easy to set up.

For a quick check, to see if this is the problem, you can add the following to your app:

app.use(session({ secret: 'super secret' }));

Make sure you add it before app.use(passport.session()).

If that works, you should read up on how to configure a session store, and what the various other options of the session middleware are.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download