Search code examples
passport.jskoa

Why is ctx.state.user undefined after logging in user when using koa-passport


I am using koa-passport to handle the local signup/login in my react app. I am trying to set up the local authentication without the redirect, since I want to handle routing on the client side. My Problem: When I send a request to the server after successfully authenticating and logging in a user, I don't have the ctx.state.user object I was hoping to get. Here is my initial login:

router.post('/login/local', passport.authenticate('local-login', function(err, user, info) {
  if (err) // handle error
  else if (!user && info) // handle no user
  else {
    // handle successful login
    ctx.login(user);
  }
}));

Then, I want to access the logged in user, like so:

router.get('/profile', (ctx) => {
  // ctx.state.user is undefined
}

But there is no user property in ctx.state. Isn't this the way this should work or am I missing something?


Solution

  • I found the problem: I wasn't sending back the cookies from the client. In my fetch I had to set credentials: 'include' to make it work and since I am using koa-cors, I had to specify to allow cookies as well.