diff --git a/docs/content/docs/plugins/2fa.mdx b/docs/content/docs/plugins/2fa.mdx index 5f66b4a7c2..207b57e426 100644 --- a/docs/content/docs/plugins/2fa.mdx +++ b/docs/content/docs/plugins/2fa.mdx @@ -151,6 +151,24 @@ const authClient = createAuthClient({ }); ``` +Using the `twoFactorPage` config: + +```ts title="sign-in.ts" +import { createAuthClient } from "better-auth/client"; +import { twoFactorClient } from "better-auth/client/plugins"; + +const authClient = createAuthClient({ + plugins: [ + twoFactorClient({ + twoFactorPage: "/two-factor", // the page to redirect if a user needs to verify their 2nd factor + }), + ], +}); +``` + + +Using the `twoFactorPage` option will cause a full page reload when redirecting users to the two-factor authentication page. If you want to avoid page reloads, consider using the `onTwoFactorRedirect` callback instead to handle the redirect programmatically within your application. + diff --git a/packages/better-auth/src/plugins/two-factor/client.ts b/packages/better-auth/src/plugins/two-factor/client.ts index 7f27b3cc24..2e117af7fa 100644 --- a/packages/better-auth/src/plugins/two-factor/client.ts +++ b/packages/better-auth/src/plugins/two-factor/client.ts @@ -7,6 +7,13 @@ export * from "./error-code"; export const twoFactorClient = ( options?: | { + /** + * the page to redirect if a user needs to verify + * their two factor + * + * @warning This causes a full page reload when used. + */ + twoFactorPage?: string; /** * a redirect function to call if a user needs to verify * their two factor @@ -43,6 +50,12 @@ export const twoFactorClient = ( if (context.data?.twoFactorRedirect) { if (options?.onTwoFactorRedirect) { await options.onTwoFactorRedirect(); + return; + } + + // fallback for when `onTwoFactorRedirect` is not used and only `twoFactorPage` is provided + if (options?.twoFactorPage && typeof window !== "undefined") { + window.location.href = options.twoFactorPage; } } },