Skip to content
Product block

Two-Factor Challenge

Authenticator-code prompt with a backup-code escape hatch and an opt-in trusted-device checkbox that is off by default.

148 lineslucide-reactAdded 8 Aug 2026Updated 25 Aug 2026
  • 2fa
  • mfa
  • security
  • backup codes
  • auth

What's included

  • components/auth-two-factor.tsx
  • Needs lucide-react

Works with

  • React
  • Next.js
  • Tailwind CSS
  • TypeScript

npx hoverlab add auth-two-factor

Or over MCP, from your editor's agent — no account needed.

License

Free to read, copy and install, for personal and non-commercial projects. Shipping it in client work or a paid product needs Pro ($79 once). The source lands in your repo and stops being ours — no attribution, nothing to upgrade.

Was this useful?

Start a page with this section — add more, order them, and leave with the page source.

Preview

Two-factor authentication

Enter the 6-digit code from your authenticator app.

Rendered live in your current theme — this is the same component whose source is below, not a screenshot of it.

Source

components/auth-two-factor.tsx
'use client'

/**
 * <AuthTwoFactor> — the authenticator-app challenge, with a backup route.
 *
 * The backup-code escape hatch is the point of this block. A 2FA screen
 * without one locks out every user who changes phone, and support tickets
 * for account recovery are the most expensive kind there is. It is a mode
 * switch rather than a second form so only one input is ever submittable.
 *
 * "Trust this device" is off by default. A checkbox that weakens a security
 * control should never be pre-ticked.
 */

import * as React from 'react'
import { Loader2, Smartphone, KeySquare } from 'lucide-react'

export interface AuthTwoFactorProps {
  heading?: string
  onVerify?: (value: { code: string; mode: Mode; trustDevice: boolean }) => Promise<void>
  /**
   * Render as a demo inside a larger page, which drops the code field's
   * `autoFocus`. Focusing an input scrolls the browser to it, so a card in
   * a preview grid would drag the visitor down the page on load.
   */
  embedded?: boolean
  className?: string
}

type Mode = 'app' | 'backup'

export function AuthTwoFactor({
  heading = 'Two-factor authentication',
  onVerify,
  embedded = false,
  className = '',
}: AuthTwoFactorProps) {
  // Per-instance ids. A literal id in a reusable component is a
  // collision waiting for the second copy on the page — and a <label>
  // then resolves to whichever input rendered first.
  const uid = React.useId()
  const [mode, setMode] = React.useState<Mode>('app')
  const [code, setCode] = React.useState('')
  const [trustDevice, setTrustDevice] = React.useState(false)
  const [busy, setBusy] = React.useState(false)
  const [error, setError] = React.useState<string | null>(null)

  const isApp = mode === 'app'
  const expected = isApp ? 6 : 10
  const ready = code.trim().length >= (isApp ? expected : 8)

  function switchMode(next: Mode) {
    setMode(next)
    setCode('')
    setError(null)
  }

  async function handleSubmit(event: React.FormEvent) {
    event.preventDefault()
    if (!ready || busy) return

    setBusy(true)
    setError(null)
    try {
      await onVerify?.({ code, mode, trustDevice })
    } catch {
      setError(isApp ? 'That code is not valid or has expired.' : 'That backup code was not recognised.')
      setCode('')
    } finally {
      setBusy(false)
    }
  }

  return (
    <div className={`flex min-h-96 w-full items-center justify-center p-6 ${className}`}>
      <div className="w-full max-w-sm rounded-2xl border border-border/60 bg-card/80 p-7 shadow-sm backdrop-blur">
        <div className="mb-5 inline-flex h-11 w-11 items-center justify-center rounded-xl bg-primary/15 text-primary">
          {isApp ? <Smartphone className="h-5 w-5" /> : <KeySquare className="h-5 w-5" />}
        </div>

        <h1 className="text-2xl font-bold tracking-tight">{heading}</h1>
        <p className="mt-1.5 text-sm text-muted-foreground">
          {isApp
            ? 'Enter the 6-digit code from your authenticator app.'
            : 'Enter one of the backup codes you saved when you set 2FA up.'}
        </p>

        <form onSubmit={handleSubmit} className="mt-6 space-y-4">
          <div>
            <label htmlFor={`${uid}-tfa-code`} className="mb-1.5 block text-sm font-medium">
              {isApp ? 'Authentication code' : 'Backup code'}
            </label>
            <input
              id={`${uid}-tfa-code`}
              // Backup codes contain letters and dashes, so only the app
              // code gets the numeric keypad and the OTP autofill hint.
              inputMode={isApp ? 'numeric' : 'text'}
              autoComplete={isApp ? 'one-time-code' : 'off'}
              autoFocus={!embedded}
              required
              maxLength={expected}
              value={code}
              onChange={(e) => setCode(isApp ? e.target.value.replace(/\D/g, '') : e.target.value)}
              placeholder={isApp ? '123456' : 'xxxx-xxxx'}
              className="w-full rounded-xl border border-border/60 bg-background px-3.5 py-2.5 text-center font-mono text-lg tracking-[0.3em] outline-none transition-shadow placeholder:tracking-normal placeholder:font-sans placeholder:text-sm placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-primary"
            />
          </div>

          <p aria-live="polite" className="min-h-5 text-sm text-destructive">
            {error}
          </p>

          <label className="flex items-start gap-2.5 text-sm">
            <input
              type="checkbox"
              checked={trustDevice}
              onChange={(e) => setTrustDevice(e.target.checked)}
              className="mt-0.5 h-4 w-4 shrink-0 rounded border-border/60 accent-primary"
            />
            <span className="text-muted-foreground">
              Trust this device for 30 days
            </span>
          </label>

          <button
            type="submit"
            disabled={!ready || busy}
            className="inline-flex w-full items-center justify-center gap-2 rounded-xl bg-primary px-4 py-2.5 text-sm font-semibold text-primary-foreground transition-colors hover:bg-primary/90 disabled:opacity-50"
          >
            {busy ? <Loader2 aria-hidden className="h-4 w-4 animate-spin motion-reduce:[animation-duration:1.6s]" /> : null}
            {busy ? 'Verifying' : 'Verify'}
          </button>
        </form>

        <div className="mt-6 border-t border-border/60 pt-4 text-center">
          <button
            type="button"
            onClick={() => switchMode(isApp ? 'backup' : 'app')}
            className="text-sm font-medium text-muted-foreground transition-colors hover:text-foreground"
          >
            {isApp ? 'Lost your device? Use a backup code' : 'Use your authenticator app instead'}
          </button>
        </div>
      </div>
    </div>
  )
}

Before you paste

  • Styling is Tailwind utility classes on semantic tokens (bg-card, text-muted-foreground) — it inherits your theme instead of overriding it.
  • Install: npm i lucide-react
  • Every prop has a default, so it renders standalone before you wire it up.

Where it goes

Drop it at components/auth-two-factor.tsx and import it where you need the section:

import { AuthTwoFactor } from '@/components/auth-two-factor'

Customize

2 of this block’s props are simple enough to drive from here. Change them and the block below re-renders — it is the same component whose source is above, not a mock of it. Everything else it accepts is in the table underneath.

Props

Read out of the component’s own type and signature, so this cannot drift from the source below. Every prop has a default — the component renders standalone before you pass it anything.

PropTypeDefault
headingstring'Two-factor authentication'
onVerify(value: { code: string; mode: Mode; trustDevice: boolean }) => Promise<void>—
embeddedRender as a demo inside a larger page, which drops the code field's `autoFocus`. Focusing an input scrolls the browser to it, so a card in a preview grid would drag the visitor down the page on load.booleanfalse
classNamestring''

Not using React?

The same block rendered once to markup, wrapped as a file your framework compiles. Tailwind classes are framework-agnostic, so the design transfers intact — the behaviour does not.

This block is interactive. The markup below is its initial state with the event handlers stripped — you will need to re-wire the behaviour in your framework.

auth-two-factor.html
<!--
  Two-Factor Challenge — markup from the Hoverlab catalog.

  This is the block rendered once to HTML and wrapped as a component
  file. It is not a port of the React source: the Tailwind classes carry
  the design, which is the part that took the work, and they are the same
  in every framework.

  This block is interactive in React and the handlers are NOT here.
  Buttons, toggles and menus render in their initial state and do
  nothing until you wire them up.
-->
<div class="flex min-h-96 w-full items-center justify-center p-6 ">
  <div class="w-full max-w-sm rounded-2xl border border-border/60 bg-card/80 p-7 shadow-sm backdrop-blur">
    <div class="mb-5 inline-flex h-11 w-11 items-center justify-center rounded-xl bg-primary/15 text-primary">
      <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-smartphone h-5 w-5" aria-hidden="true">
        <rect width="14" height="20" x="5" y="2" rx="2" ry="2"></rect>
        <path d="M12 18h.01"></path>
      </svg>
    </div>
    <h1 class="text-2xl font-bold tracking-tight">Two-factor authentication</h1>
    <p class="mt-1.5 text-sm text-muted-foreground">Enter the 6-digit code from your authenticator app.</p>
    <form class="mt-6 space-y-4">
      <div>
        <label for="_R_0_-tfa-code" class="mb-1.5 block text-sm font-medium">Authentication code</label>
        <input id="_R_0_-tfa-code" inputMode="numeric" autoComplete="one-time-code" autofocus="" required="" maxLength="6" placeholder="123456" class="w-full rounded-xl border border-border/60 bg-background px-3.5 py-2.5 text-center font-mono text-lg tracking-[0.3em] outline-none transition-shadow placeholder:tracking-normal placeholder:font-sans placeholder:text-sm placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-primary" value="" />
      </div>
      <p aria-live="polite" class="min-h-5 text-sm text-destructive"></p>
      <label class="flex items-start gap-2.5 text-sm">
        <input type="checkbox" class="mt-0.5 h-4 w-4 shrink-0 rounded border-border/60 accent-primary" />
        <span class="text-muted-foreground">Trust this device for 30 days</span>
      </label>
      <button type="submit" disabled="" class="inline-flex w-full items-center justify-center gap-2 rounded-xl bg-primary px-4 py-2.5 text-sm font-semibold text-primary-foreground transition-colors hover:bg-primary/90 disabled:opacity-50">Verify</button>
    </form>
    <div class="mt-6 border-t border-border/60 pt-4 text-center">
      <button type="button" class="text-sm font-medium text-muted-foreground transition-colors hover:text-foreground">Lost your device? Use a backup code</button>
    </div>
  </div>
</div>
  • This is rendered HTML, not a translation of the React source. The Tailwind classes carry the design and work in any framework.
  • It is one frame: the component in its initial state, with no props applied beyond the defaults.
  • This block is interactive in React — toggles, menus or form state. None of that survives here; the markup is the closed/default state and the handlers are gone. Re-wire them in your own framework.
  • Requires Tailwind, and the design tokens the classes reference (bg-card, text-muted-foreground, and so on). The template ZIPs ship a globals.css that defines them.

What each framework gets across the whole catalog — effects convert properly; this rung is markup.

For AI

The component, its props, the design tokens it expects and the command that installs it — as one prompt. Paste it into Claude, Cursor, v0 or ChatGPT and what they build around it will match the rest of the catalog instead of inventing its own system.

See the prompt

Used in these pages

Want the whole screen instead of this one section? Open a page and copy it entire.

8 more blocks in Authentication

All of them free to read, copy and install — no account, no locked tiles, no watermarked preview. The whole catalog is open, and so are the API and the CLI.

Browse Authentication

Shipping one commercially

Copying the code is free. Putting it in client work or a paid product is what Pro is for — the licence, not the access.

  • A commercial licence for everything in the catalog
  • Unlimited bundle exports, in Vue, Svelte and Tailwind
  • One payment — no subscription, nothing to renew
Pro — $79 once

More Authentication blocks

View category
Open the full page for this block

Split Signup With Proof

Registration form beside a testimonial panel, with live password rules and a proof column that drops rather than stacks on mobile.

Authentication205 lines1 dep
Open the full page for this block

One-Time Code Input

Six-box OTP entry that handles paste, backspace, arrow keys and iOS SMS autofill — the parts hand-rolled versions always miss.

Authentication184 lines1 dep
Open the full page for this block

New Password With Strength Meter

Set-a-new-password form with a four-step strength meter, confirm matching and errors announced rather than only coloured.

Authentication179 lines1 dep
Open the full page for this block

Email-First SSO Sign-In

Email first, then whatever that domain uses. The password field is absent rather than disabled when SSO is enforced, the button names the company it redirects to, and a personal address is a normal answer instead of an error.

Authentication257 lines1 dep
Open the full page for this block

Magic Link Sign In

Passwordless sign-in that says what will land in the inbox and how long it lasts, before the address is typed.

Authentication176 linesNo deps
Open the full page for this block

Enterprise SSO Split

What SSO actually covers, written for the person who has to configure it rather than the person who asked for it.

Authentication155 linesNo deps