two-factor-authentication-best-practices

Multi-factor authentication with TOTP, OTP, backup codes, and trusted device management for Better Auth.

better-auth/skillsUpdated Apr 8, 2026

Works with

Claude CodeCursorClineWindsurfCodexGooseGitHub CopilotZed

0

total installs

0

this week

169

GitHub stars

0

upvotes

Install Skill

Run in your terminal

$npx skills add https://github.com/better-auth/skills --skill two-factor-authentication-best-practices

0

installs

0

this week

169

stars

What it does

  • Supports three verification methods: authenticator apps (TOTP with QR codes), email/SMS codes (OTP), and single-use backup codes

  • Handles complete 2FA sign-in flows with automatic session management, temporary 2FA cookies, and trusted device tracking with configurable expiration

  • Built-in security features including rate limiting (3 requests per 10 seconds), encryption at rest for s

Category

Productivity

Last updated

Apr 8, 2026

Installation Guide

How to use two-factor-authentication-best-practices on Cursor

AI-first code editor with Composer

1

Prerequisites

Before installing skills in Cursor, ensure your development environment meets these requirements:

  • Cursor installed and configured on your machine
  • Node.js 16+ with npm — verify with node --version
  • Active project directory where you want to add two-factor-authentication-best-practices
2

Run the install command

Execute the skills CLI command in your project's root directory to begin installation:

$npx skills add https://github.com/better-auth/skills --skill two-factor-authentication-best-practices

Fetches two-factor-authentication-best-practices from better-auth/skills and configures it for Cursor.

3

Select Cursor when prompted

The CLI shows a list of agents. Use arrow keys and space to select Cursor:

◆ Which agents do you want to install to?
│ ── Universal (.agents/skills) ────────────────
│ · Cline · Codex · Goose · Windsurf
│ ●Cursor(selected)
│ · Cursor · Aider · Continue
4

Verify installation

Confirm successful installation by checking the skill directory location:

.cursor/skills/two-factor-authentication-best-practices

Restart Cursor to activate two-factor-authentication-best-practices. Access via /two-factor-authentication-best-practices in your agent's command palette.

Security Notice

We perform automated surface-level scans (Gen AI Scanner, Socket, Snyk) during installation. These checks detect common vulnerabilities but do not guarantee complete security. Always review skill source code and verify the publisher's reputation before production use.

Skills execute code in your environment. Always review source, verify the publisher, and test in isolation before production.

Documentation

Setup

  1. Add twoFactor() plugin to server config with issuer
  2. Add twoFactorClient() plugin to client config
  3. Run npx @better-auth/cli migrate
  4. Verify: check that twoFactorSecret column exists on user table
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 Setup

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

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

Enabling 2FA for Users

Requires password verification. Returns TOTP URI (for QR code) and backup codes.

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
  }
};

twoFactorEnabled is not set to true until first TOTP verification succeeds. Override with skipVerificationOnEnable: true (not recommended).

TOTP (Authenticator App)

Displaying the QR Code

import QRCode from "react-qr-code";

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

Verifying TOTP Codes

Accepts codes from one period before/after current time:

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

TOTP Configuration Options

twoFactor({
  totpOptions: {
    digits: 6, // 6 or 8 digits (default: 6)
    period: 30, // Code validity period in seconds (default: 30)
  },
});

OTP (Email/SMS)

Configuring OTP Delivery

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

export const auth = betterAuth({
  plugins: [
    twoFactor({
      otpOptions: {
        sendOTP: async ({ user, otp }, ctx) => {
          await sendEmail({
            to: user.email,
            subject: "Your verification code",
            text: `Your code is: ${otp}`,
          });
        },
        period: 5, // Code validity in minutes (default: 3)
        digits: 6, // Number of digits (default: 6)
        allowedAttempts: 5, // Max verification attempts (default: 5)
      },
    }),
  ],
});

Sending and Verifying OTP

Send: authClient.twoFactor.sendOtp(). Verify: authClient.twoFactor.verifyOtp({ code, trustDevice: true }).

OTP Storage Security

Configure how OTP codes are stored in the database:

twoFactor({
  otpOptions: {
    storeOTP: "encrypted", // Options: "plain", "encrypted", "hashed"
  },
});

For custom encryption:

twoFactor({
  otpOptions: {
    storeOTP: {
      encrypt: async (token) => myEncrypt(token),
      decrypt: async (token) => myDecrypt(token),
    },
  },
});

Backup Codes

Generated automatically when 2FA is enabled. Each code is single-use.

Displaying Backup Codes

const BackupCodes = ({ codes }: { codes: string[] }) => {
  return (
    <div>
      <p>Save these codes in a secure location:</p>
      <ul>
        {codes.map((code, i) => (
          <li key={i}>{code}</li>
        ))}
      </ul>
    </div>
  );
};

Regenerating Backup Codes

Invalidates all previous codes:

const regenerateBackupCodes = async (password: string) => {

List & Monetize Your Skill

Submit your Claude Code skill and start earning

Get started →

Use Cases

User Story & Requirements Generation

Create detailed user stories, acceptance criteria, and feature specs

Example

Generate user stories for 'password reset feature' with acceptance criteria, edge cases, and test scenarios

Reduce spec writing time by 50%, ensure comprehensive coverage

Competitive Analysis

Research competitors, compare features, identify gaps

Example

Analyze 5 competitor products, create feature comparison matrix, suggest differentiation opportunities

Complete competitive research in 2 hours instead of 2 days

Roadmap Prioritization

Evaluate features using frameworks (RICE, ICE, Kano) and create prioritized backlogs

Example

Score 20 feature ideas using RICE framework, generate prioritized roadmap with rationale

Make data-driven prioritization decisions faster

Stakeholder Communication

Draft PRDs, status updates, and stakeholder presentations

Example

Create executive summary of Q3 roadmap, monthly progress report, feature launch announcement

Save 3-5 hours/week on communication overhead

Implementation Guide

Prerequisites

  • Claude Desktop or compatible AI client
  • Access to product documentation and roadmap tools (Jira, Notion, etc.)
  • Understanding of product management frameworks (RICE, Jobs-to-be-Done, etc.)
  • Stakeholder contact information and communication channels

Time Estimate

30-60 minutes to see productivity improvements

Steps

  1. 1Install product management skill
  2. 2Start with user story generation for known feature
  3. 3Progress to competitive analysis: research 2-3 competitors
  4. 4Use for roadmap prioritization: apply RICE/ICE scoring
  5. 5Draft stakeholder communications and refine based on feedback
  6. 6Build template library for recurring PM tasks
  7. 7Share effective prompts with product team

Common Pitfalls

  • Not validating competitive research—verify facts before sharing
  • Accepting user stories without involving engineering team
  • Over-relying on frameworks without qualitative judgment
  • Not customizing outputs to company culture and communication style
  • Skipping stakeholder validation of generated requirements

Best Practices

✓ Do

  • +Validate research and competitive analysis with real data
  • +Collaborate with engineering when generating technical requirements
  • +Customize frameworks and templates to your company context
  • +Use skill for first drafts, refine with stakeholder input
  • +Document successful prompt patterns for PM tasks
  • +Combine AI efficiency with human judgment and intuition

✗ Don't

  • Don't publish competitive analysis without fact-checking
  • Don't finalize user stories without engineering review
  • Don't make prioritization decisions solely on AI scoring
  • Don't skip customer validation of generated requirements
  • Don't ignore company-specific context and culture

💡 Pro Tips

  • Provide context: company goals, constraints, customer feedback
  • Ask for alternatives: 'Show 3 ways to prioritize this roadmap'
  • Request stakeholder-specific formatting: 'Executive summary vs. engineering spec'
  • Use skill for 70% generation + 30% customization to company needs

When to Use This

✓ Use when

Use for user story writing, competitive research, roadmap prioritization, stakeholder communication, and PRD drafting. Best for reducing repetitive documentation and research work.

✗ Avoid when

Avoid for strategic product vision (requires deep customer empathy), pricing decisions (needs market and financial expertise), or when face-to-face customer discovery is more valuable than speed.

Learning Path

  1. 1Basic: user stories, feature specs, status updates
  2. 2Intermediate: competitive analysis, prioritization frameworks, PRDs
  3. 3Advanced: product strategy, go-to-market planning, OKR setting
  4. 4Expert: product vision, market positioning, business model innovation

Related Skills

Reviews

4.537 reviews
  • N
    Noor OkaforDec 28, 2024

    Keeps context tight: two-factor-authentication-best-practices is the kind of skill you can hand to a new teammate without a long onboarding doc.

  • O
    Omar MartinezDec 20, 2024

    two-factor-authentication-best-practices fits our agent workflows well — practical, well scoped, and easy to wire into existing repos.

  • G
    Ganesh MohaneDec 12, 2024

    two-factor-authentication-best-practices has been reliable in day-to-day use. Documentation quality is above average for community skills.

  • L
    Lucas SrinivasanDec 8, 2024

    We added two-factor-authentication-best-practices from the explainx registry; install was straightforward and the SKILL.md answered most questions upfront.

  • I
    Isabella ThomasNov 27, 2024

    two-factor-authentication-best-practices fits our agent workflows well — practical, well scoped, and easy to wire into existing repos.

  • Y
    Yash ThakkerNov 23, 2024

    Solid pick for teams standardizing on skills: two-factor-authentication-best-practices is focused, and the summary matches what you get after install.

  • D
    Diya DixitNov 19, 2024

    Registry listing for two-factor-authentication-best-practices matched our evaluation — installs cleanly and behaves as described in the markdown.

  • O
    Omar AndersonNov 11, 2024

    We added two-factor-authentication-best-practices from the explainx registry; install was straightforward and the SKILL.md answered most questions upfront.

  • S
    Sakshi PatilNov 3, 2024

    two-factor-authentication-best-practices reduced setup friction for our internal harness; good balance of opinion and flexibility.

  • C
    Chaitanya PatilOct 22, 2024

    We added two-factor-authentication-best-practices from the explainx registry; install was straightforward and the SKILL.md answered most questions upfront.

showing 1-10 of 37

1 / 4

Discussion

Comments — not star reviews
  • No comments yet — start the thread.