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
andSession
interfaces to includerole
. - 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:
- 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;
}
}
- Middleware Logic:
const role = request.auth?.user?.role; //