authentication - Role not Populating in Next-Auth JWT Token for Middleware Role-Based Access - Stack Overflow

admin2025-04-17  3

I'm implementing role-based access control in a Next.js app using Drizzle ORM, Supabase (Postgres), and Auth.js. My middleware isn't receiving the user's role from the JWT token (request.auth.user.role is undefined). I'm using google as an Oauth provider

Setup:

  • Auth Config: Extended User and Session interfaces to include role.
  • Auth.ts: Configured DrizzleAdapter, JWT, and session callbacks to propagate role from the user to the token and session.
  • Middleware.ts: Uses auth() middleware to redirect based on role.

Issue: The JWT callback's token.role and session data aren't populated with the user's role. In middleware, request.auth?.user?.role logs as undefined, despite assigning it in callbacks. The JWT token shows role is missing.

Code Snippets:

  1. JWT Callback:
callbacks: {
  async jwt({ token, user }) {
    if (user) {
      token.role = user.role; // Here it's ok
      token.id = user.id;
    }
    return token;
  },
  async session({ session, token }) {
    session.user.role = token.role; // Propagates to session
    return session;
  }
}
  1. Middleware Logic:
const role = request.auth?.user?.role; // 
转载请注明原文地址:http://anycun.com/QandA/1744820030a88064.html