role-based authorization

Hi, I'm implementing role-based access control in my admin panel and facing a challenge. I need to restrict access so only users with user.metadata.role === "ADMIN" can log in.

What's the recommended approach in Better Auth to:
  • Validate a user's role/permissions BEFORE creating a session?
  • Is there any equivalent to Next Auth's authorize callback that lets me check custom conditions during login?
Solution
thanks @Soheel i tried with hooks (not databasehooks), it worked 🎉

I added this to my
auth
config
  hooks: {
    before: createAuthMiddleware(async (ctx) => {
      if (ctx.path !== "/sign-in/email") {
        return;
      }

      const email = ctx.body?.email;
      if (email) {
        const dbUser = await findUserByEmail(email);
        if (!dbUser || dbUser.metadata?.role !== "ADMIN") {
          throw new APIError("UNAUTHORIZED", {
            message: "Only administrators can access this application.",
          });
        }
      }
    }),
  }
Was this page helpful?