Unable to access user email inside `createAuthMiddleware` when using social providers

I’m trying to implement a before hook in Better Auth to restrict which users are allowed to sign in, following the example in the documentation:
https://www.better-auth.com/docs/concepts/hooks#example-enforce-email-domain-restriction

However, I noticed that this approach only works when signing in with email/password. When using a social provider (in my case, Microsoft), the
email
field is never present in the ctx.body object as shown in the docs.

Because of that, the before hook can’t access the user’s email, making it impossible to validate whether the sign-in should be allowed.

Question


Is there a different or recommended way to access the user’s email when the sign-in is happening through a social provider inside the createAuthMiddleware before hook?

Code Example


hooks: {
  before: createAuthMiddleware(async (ctx) => {
    console.info("Hit before hook on path: ", ctx.path)

    if (!["/sign-in/email", "/sign-in/social"].includes(ctx.path)) {
      return
    }

    console.log(ctx.body)

    const allowed = ["admin@email.com.br"]
    const isAllowed = allowed.includes(ctx.body?.email)
    console.log("isAllowed:", isAllowed)

    if (!isAllowed) {
      throw new APIError("BAD_REQUEST", {
        message: "Email not allowed",
      })
    }
  }),
}
Better Auth Hooks let you customize BetterAuth's behavior
Was this page helpful?