Clara Raquel
Clara Raquel

Reputation: 29

Passport fail to serializeUser. TypeError: Cannot set properties of undefined (setting: 'user')

i've this code

app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(session({
  secret: "secret_shh",
  resave: true,
  saveUninitialized: true,
}));

app.use(passport.initialize());
app.use(passport.session());

passport.use(new PASSPORT_LOCAL_STRATEGY(
  (username, password, done) => {
    if (username === "test" && password === "passwrd") {
      return done(null, {username: username});
    } else {
      return done(null, false);
    }
  }
));

passport.serializeUser((user, done) => {
  done(null, user.username);
});

passport.deserializeUser((username, done) => {
  done(null, {username: username})
}); 

router.post('/login', 
  passport.authenticate('local', {
    failureRedirect: '/failure',
    successRedirect: '/success'
  }
));

When i send /login with wrong user and password it correctly send me to the failureRedirect, but when i send the correct user and password it send me an error saying: TypeError: Cannot set properties of undefined (setting 'user').

Upvotes: 1

Views: 1041

Answers (1)

Tom Monks
Tom Monks

Reputation: 61

I've been getting the same error and I think I've tracked it down. Hopefully this may help you.

In my case, my passport strategy depended on an older version of passport-oauth, which in turn depended on a version of passport prior to 0.5.1. In 0.5.1, passport was updated to move where the passport session is kept (no longer at req._passport.session). The older version of passport was expecting to find it there. Here are a couple things you can check to track down your issue.

  • look at the stack trace to see which package in node_modules is causing the error
  • check your dependency tree to see if you have a dependency on an older version of passport (npm list --depth 3)
  • try reverting passport to 0.5.0 and see if that fixes your issue

Upvotes: 3

Related Questions