Email Domain Validation on Registration

Hi everyone,
I’m trying to restrict user registration in Better Auth to specific email domains (e.g., example.com, company.org).

Any help would be greatly appreciated! 🙏
Solution
you could do something like this with a hook. seems to work well for me

 hooks: {
    before: createAuthMiddleware(async (ctx) => {
      if (ctx.path.startsWith("/callback") && ctx.params?.id === "google") {
        const hd = ctx.query?.hd;
        if (!hd || (hd !== "domain1.com" && hd !== "domain2.com")) {
          throw new APIError("BAD_REQUEST", {
            message: "Google account must be from allowed domain",
          });
        }
        return;
      }

      if (ctx.path !== "/sign-up/email") {
          return;
      }

      const email = ctx.body?.email;
      if (!email || (!email.endsWith("@domain1.com") && !email.endsWith("@domain2.com"))) {
        throw new APIError("BAD_REQUEST", {
          message: "Email domain is not allowed",
        });
      }
    }),
  },
Was this page helpful?