Next.js Discord

Discord Forum

Next Auth update server session when data in the backend changes.

Unanswered
Devon Rex posted this in #help-forum
Open in Discord
Devon RexOP
Hey everyone I am new to Next Auth. I have a users role in the session for being able to access an admin backend. When I change the role in my database, how do I get that to update the session without making the user log out and log back in?

3 Replies

Devon RexOP
This is what I have right now which correctly displays the role, but if I update the role in the backend then it won't display the proper role until I sign out and sign back in.

const page = async () => {
  const session = await getServerSession(authOptions);
  if (session?.user.role != "ADMIN") {
    redirect('/')
  }
  const role = session?.user.role;
  return (
    <div>{role}</div>
  )
}
Masai Lion
Read the next auth docs. They provide settings for watching events like this : https://next-auth.js.org/getting-started/client#updating-the-session . Hope this helps
Masai Lion
keep in mind if your flow is like this : admin loggs in he changes an user with id 20 to role admin from worker (the user with Id is currently logged in and has his old role set as worker). The user with id 20 goes to myawesomesite.come/admin ( heres the part either client side * i dont recommend that * or server side you need to setup a logic to re validate or check the session again or so to say on each request. As an example lucia auth (different auth lib defaults to database session management) provides a way to handle each request and parse the session to check for changes in the db.