twoFactor Skill: Implementing TOTP/OTP Two-Factor Authentication in Better Auth

Introduction

In production environments, single-factor login with email and password alone often struggles to meet security and compliance requirements. Implementing 2FA from scratch typically requires handling multiple logic blocks, such as the TOTP algorithm, OTP delivery, backup codes, intermediate login state cookies, trusted devices, and rate limiting, making it easy to overlook details or write fragile workflows. Better Auth has integrated these capabilities into a single configuration via the twoFactor plugin; the twoFactor Agent Skill organizes official best practices into instructions that coding assistants can directly reference, reducing the likelihood of AI generating incomplete or incorrect 2FA code.

What is this

twoFactor is an Agent Skill located in the Better Auth skills repository (directory name twoFactor, with the name two-factor-authentication-best-practices in the SKILL metadata). It targets projects already using Better Auth, explaining how to configure the server-side twoFactor() plugin and client-side twoFactorClient(), as well as the complete lifecycle including enabling, login verification, trusted devices, and disabling. It is categorized as an official security Skill on officialskills.sh, with the index maintained by the VoltAgent team.

Core Features

The following capabilities are derived from the official Skill documentation and correspond to the Better Auth twoFactor plugin behavior:

  • TOTP: Integrates with authenticator apps; configurable digits (6 or 8) and period (default 30 seconds); verification accepts codes from one time window before and after the current period.
  • OTP: Custom email or SMS delivery via sendOTP; configurable validity period, digit count, and maximum attempts per code; in-library OTP storage supports plain, encrypted, hashed, or custom encryption/decryption.
  • Backup codes: Automatically generated when enabling 2FA; single-use valid; supports regeneration after password confirmation (all old codes become invalid).
  • Login flow: If 2FA is required after password login, the response includes twoFactorRedirect: true, redirecting the client to a verification page; can be completed using TOTP, OTP, or backup codes, establishing a session upon success.
  • Trusted devices: Pass trustDevice: true during verification; trusted for 30 days by default (trustDeviceMaxAge), refreshable upon each login.
  • Security: Session removed before issuing a temporary 2FA Cookie (default 10 minutes) after credential verification; built-in rate limiting for 2FA endpoints (3 attempts per 10 seconds); TOTP secrets and default backup codes encrypted; OTP verification uses constant-time comparison.
  • Limitations: Only supports enabling 2FA for credential (email/password) accounts; both enabling and disabling require password confirmation.

Installation and Activation

In coding assistants that support Agent Skills, you can use the official installation command (consistent with officialskills.sh):

npx skills add https://github.com/better-auth/skills --skill better-auth-twoFactor

You can also provide the Skill directory link to the assistant for installation: https://github.com/better-auth/skills/tree/main/better-auth/twoFactor.

Installing the Skill only affects the assistant context; the application side still needs to integrate the Better Auth plugin and migrate the database within the project.

Server-side: Add twoFactor to the betterAuth configuration and set the issuer (the issuer name displayed in authenticator apps):

import { betterAuth } from "better-auth";
import { twoFactor } from "better-auth/plugins";

export const auth = betterAuth({
  appName: "My App",
  plugins: [
    twoFactor({
      issuer: "My App",
    }),
  ],
});

Client-side: Use twoFactorClient to redirect when secondary verification is needed (example redirects to /2fa):

import { createAuthClient } from "better-auth/client";
import { twoFactorClient } from "better-auth/client/plugins";

export const authClient = createAuthClient({
  plugins: [
    twoFactorClient({
      onTwoFactorRedirect() {
        window.location.href = "/2fa";
      },
    }),
  ],
});

Database: When using the built-in adapter, run:

npx auth@latest migrate

If using Drizzle or Prisma, generate and push the schema according to project conventions. Verification: A twoFactorSecret field should appear in the user table.

Support for npx skills add varies among tools like Cursor, Codex CLI, and Claude Code; differences not specifically detailed in official materials are not expanded upon here and should follow the current Skills documentation for each tool.

Typical Usage

Enabling 2FA for a User

Password must be verified first; returns totpURI (for generating QR codes) and backupCodes. twoFactorEnabled becomes true only after the first successful TOTP verification (can be skipped with skipVerificationOnEnable: true, though this is not recommended by the official docs).

const enable2FA = async (password: string) => {
  const { data, error } = await authClient.twoFactor.enable({
    password,
  });

  if (data) {
    // data.totpURI — generate a QR code from this
    // data.backupCodes — display to user
  }
};

Displaying the QR code (example uses react-qr-code):

import QRCode from "react-qr-code";

const TotpSetup = ({ totpURI }: { totpURI: string }) => {
  return <QRCode value={totpURI} />;
};

Completing TOTP binding:

const verifyTotp = async (code: string) => {
  const { data, error } = await authClient.twoFactor.verifyTotp({
    code,
    trustDevice: true,
  });
};

Email OTP as a Second Factor

Configure otpOptions.sendOTP on the server, e.g., to send an email:

twoFactor({
  otpOptions: {
    sendOTP: async ({ user, otp }, ctx) => {
      await sendEmail({
        to: user.email,
        subject: "Your verification code",
        text: `Your code is: ${otp}`,
      });
    },
    period: 5,
    digits: 6,
    allowedAttempts: 5,
    storeOTP: "encrypted",
  },
});

Client-side sending and verification: authClient.twoFactor.sendOtp(); authClient.twoFactor.verifyOtp({ code, trustDevice: true }).

2FA Branching during Login

  1. Call signIn.email({ email, password })
  2. Check context.data.twoFactorRedirect in onSuccess
  3. If true, navigate to a verification page like /2fa
  4. Complete verification using TOTP, OTP, or backup codes
  5. Write session cookies upon success
const signIn = async (email: string, password: string) => {
  const { data, error } = await authClient.signIn.email(
    { email, password },
    {
      onSuccess(context) {
        if (context.data.twoFactorRedirect) {
          window.location.href = "/2fa";
        }
      },
    }
  );
};

When connecting directly to the API server-side, you can check if the response contains twoFactorRedirect. Backup code recovery: authClient.twoFactor.verifyBackupCode({ code, trustDevice: true }). Disabling 2FA: authClient.twoFactor.disable({ password }), which also revokes trusted device records.

For more complete combinations of issuer, totpOptions, backupCodeOptions, twoFactorCookieMaxAge, trustDeviceMaxAge, etc., refer to the Complete Configuration Example in the official Skill.

Use Cases and Notes

Suitable for: Web or full-stack applications already using Better Auth that require TOTP authenticators, email/SMS OTP, backup codes, and a “trust this device” login experience; suitable for cases where you want the assistant to generate configurations and client calls based on official fields and flows rather than hand-writing TOTP logic.

Notes:

  • 2FA applies only to email/password accounts; OAuth and others require separate design.
  • OTP delivery relies on your implementation of sendEmail or SMS channels; the Skill does not include specific email service provider integrations.
  • Production environments should use encrypted storage for OTP/backup codes and understand default rate limits and cookie timeouts, adjusting twoFactorCookieMaxAge, allowedAttempts, etc., as needed.
  • The Skill describes plugin capabilities; specific framework routing (Next.js, React, etc.) and UI still need to be implemented manually.

Conclusion

The twoFactor Skill documents the installation, client hooks, TOTP/OTP/backup codes, and login branching of Better Auth’s two-factor authentication into searchable steps and code snippets. It is suitable for handing over to coding assistants for reference implementation when MFA is needed, avoiding single-factor or half-baked 2FA flows. Official directory: https://github.com/better-auth/skills/tree/main/better-auth/twoFactor.

羽毛球分组比赛记分
小程序二维码

欢迎使用《羽毛球分组比赛记分》微信小程序

Xiaoye