Two-Factor Authentication
Pre-built Svelte 5 components for TOTP-based 2FA. Built on top of better-auth's twoFactorClient plugin.
Auth Client Setup
All 2FA components require a TwoFactorAuthClient prop -- a better-auth client configured with the twoFactorClient plugin:
import { createAuthClient } from 'better-auth/svelte'
import { twoFactorClient } from 'better-auth/client/plugins'
export const authClient = createAuthClient({
plugins: [twoFactorClient()],
})
Enable2FAForm
Two-step flow: password confirmation, then TOTP verification with QR code and backup codes.
<script lang="ts">
import { Enable2FAForm } from '@repo/auth'
import { authClient } from '$lib/auth-client'
</script>
<Enable2FAForm
{authClient}
onSuccess={() => { /* 2FA now enabled */ }}
/>
Props
| Prop | Type | Description |
|---|---|---|
authClient | TwoFactorAuthClient | Auth client with twoFactor methods |
onSuccess | () => void | Called after 2FA is successfully enabled |
Disable2FAForm
Password confirmation form to disable 2FA.
<script lang="ts">
import { Disable2FAForm } from '@repo/auth'
import { authClient } from '$lib/auth-client'
</script>
<Disable2FAForm
{authClient}
onSuccess={() => { /* 2FA disabled */ }}
/>
Props
| Prop | Type | Description |
|---|---|---|
authClient | TwoFactorAuthClient | Auth client with twoFactor methods |
onSuccess | () => void | Called after 2FA is disabled |
error | Snippet<[{ message: string }]> | Optional custom error rendering snippet |
Verify2FAForm
Login verification with TOTP code entry. Includes a toggle to switch to backup code input.
<script lang="ts">
import { Verify2FAForm } from '@repo/auth'
import { authClient } from '$lib/auth-client'
</script>
<Verify2FAForm
{authClient}
onSuccess={() => { /* verified, proceed to app */ }}
/>
Props
| Prop | Type | Description |
|---|---|---|
authClient | TwoFactorAuthClient | Auth client with twoFactor methods |
onSuccess | () => void | Called after successful verification |
Schemas
Zod schemas used by the 2FA forms:
import { verifyTOTPSchema, passwordSchema, verifyBackupCodeSchema } from '@repo/auth'
| Schema | Fields |
|---|---|
verifyTOTPSchema | code (6-digit string), trustDevice (boolean, optional) |
passwordSchema | password (non-empty string) |
verifyBackupCodeSchema | code (non-empty string), trustDevice (boolean, optional) |