Skip to main content

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

PropTypeDescription
authClientTwoFactorAuthClientAuth client with twoFactor methods
onSuccess() => voidCalled 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

PropTypeDescription
authClientTwoFactorAuthClientAuth client with twoFactor methods
onSuccess() => voidCalled after 2FA is disabled
errorSnippet<[{ 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

PropTypeDescription
authClientTwoFactorAuthClientAuth client with twoFactor methods
onSuccess() => voidCalled after successful verification

Schemas

Zod schemas used by the 2FA forms:

import { verifyTOTPSchema, passwordSchema, verifyBackupCodeSchema } from '@repo/auth'
SchemaFields
verifyTOTPSchemacode (6-digit string), trustDevice (boolean, optional)
passwordSchemapassword (non-empty string)
verifyBackupCodeSchemacode (non-empty string), trustDevice (boolean, optional)