two-factor-authentication-best-practices
by better-authAdd TOTP, OTP delivery, backup codes, and trusted device management to your Better Auth workflow with the twoFactor skill. Ideal for enhancing access control and login security.
Overview
What is twoFactor?
twoFactor is a Better Auth plugin designed to add robust multi-factor authentication (MFA) to your application. It enables TOTP (Time-based One-Time Password) setup for authenticator apps, delivers OTP codes via email or SMS, manages backup codes, and handles trusted device workflows. This skill is ideal for developers and teams seeking to strengthen access control and login security using modern authentication standards.
Who should use twoFactor?
Use twoFactor if you need to:
- Protect user accounts with MFA
- Support authenticator app setup (TOTP)
- Provide backup codes for account recovery
- Manage trusted devices and secure sign-in flows
- Integrate with Better Auth for flexible authentication
How to Use
Installation Steps
- Add the twoFactor plugin to your server configuration:
import { betterAuth } from "better-auth"; import { twoFactor } from "better-auth/plugins"; export const auth = betterAuth({ appName: "My App", plugins: [ twoFactor({ issuer: "My App" }), ], }); - Add the twoFactorClient plugin to your client configuration:
import { createAuthClient } from "better-auth/client"; import { twoFactorClient } from "better-auth/client/plugins"; export const authClient = createAuthClient({ plugins: [ twoFactorClient({ onTwoFactorRedirect() { window.location.href = "/2fa"; }, }), ], }); - Run database migration:
Confirm that thenpx @better-auth/cli migratetwoFactorSecretcolumn exists in your user table.
Enabling 2FA for Users
- Users must verify their password to enable 2FA.
- The skill returns a TOTP URI (for QR code generation) and backup codes for recovery.
twoFactorEnabledis set to true only after successful TOTP verification.
Best Practices
- Encourage users to store backup codes securely.
- Use trusted device management for smoother user experience.
- Regularly review authentication flows for security updates.
FAQ
Is twoFactor compatible with all Better Auth setups?
Yes, twoFactor integrates seamlessly with Better Auth server and client configurations.
What authentication methods does twoFactor support?
twoFactor supports TOTP via authenticator apps, OTP delivery via email/SMS, backup codes, and trusted device workflows.
How do I migrate my database for twoFactor?
Run npx @better-auth/cli migrate and verify the twoFactorSecret column in your user table.
Where can I find more details or code samples?
Check the SKILL.md file in the better-auth/skills repository for implementation details and sample code.
When should I use twoFactor?
Use twoFactor whenever you need to add multi-factor authentication, TOTP setup, or enhanced login security to your Better Auth-powered application.
