# Backup Code

A recovery code that copies itself when clicked and is crossed out once it has been used.

- Category: Forms
- Page: https://wunderui.com/components/backup-code
- Tier: Free

## Install

```bash
npx wunderui-cli add backup-code
```

## Import

```tsx
import { BackupCode } from "@/components/blocks/auth"
```

## Minimal usage

Then use it:

```tsx
import { BackupCode } from "@wunderui/react"

export function Code({ onCopy }: { onCopy: (code: string) => void }) {
  return <BackupCode code="4F7K-9QX2" onCopy={onCopy} />
}
```

Expected result: You should see a small bordered button with the code in it. Hover it to see a copy icon; press it to copy the code.

## Usage

```tsx
import { BackupCode } from "@wunderui/react"

export function Example({ onCopy }: { onCopy: (code: string) => void }) {
  return <BackupCode code="4F7K-9QX2" onCopy={onCopy} />
}
```

## When to use

### Use Backup Code for

- Recovery codes after two-factor setup, one code per button
- A short code that is copied with one press
- A list that shows which codes were already used

### Use something else

- [Input Group](https://wunderui.com/components/input-group) for one long value, such as a link, with a visible copy button
- [OTP Field](https://wunderui.com/components/otp-field) for typing a verification code instead of copying one
- [Code Block](https://wunderui.com/components/code-block) for a block of code or a command with a copy action
- [Input](https://wunderui.com/components/input) for a value that people edit

## Keyboard

A code is a native button. Used codes are disabled and are skipped by the Tab key.

| Key | Action |
|---|---|
| `Tab` or `Shift+Tab` | Moves focus to the next or previous code that is not used. |
| `Enter` or `Space` | Presses the focused code: copies it and, once the clipboard took it, calls `onCopy`. |

## Behavior

What a backup code does with state, content, the DOM and motion.

- **Copy:** A press writes the code to the clipboard and calls the copy handler with it, but only after the write succeeded. If the page may not write, nothing happens: no callback, no message, no change.
- **States:** A code is ready or used: hover shows the copy icon, focus draws the indigo ring, and a used code is struck through, disabled and out of the Tab order. Feedback after a copy is yours.
- **Long text:** The button grows with its code and has no ellipsis: in a box narrower than the code the text wraps at the hyphen onto two lines. Give the code a wide enough grid cell.
- **Responsive:** A code has no width of its own, so the grid you put it in decides. Two columns fit down to a 320 px screen; use one column for longer codes.
- **Names for assistive technology:** The accessible name is the code, and the button has a native tooltip, Copy code. A used code is announced as unavailable but not as used, so state the count in text, for example 5 codes left.
- **Motion and reduced motion:** The fill changes on hover and the copy icon fades in, but nothing moves. With reduced motion the colours and fade still apply, because they are not movement.

## Anatomy

- `BackupCode`: A button with an 8 px radius, a 1 px border and the card fill. It is the only element: pressing it copies the code, and a used code is disabled.
- `Code`: The code in 14 px medium text with tabular figures, on one line that wraps at a hyphen when the button is too narrow. A used code is struck through and tertiary.
- `Copy icon`: A 14 px copy icon after the code. It is transparent until hover so it never shifts the code, and it is decorative because the code names the button.

## Best practices

### When to use

- Use Backup Code to list recovery codes after two-factor setup, in a grid with one code per button. For a single long value with a copy action, such as an invite URL, use Invite Link Row.

### Do

- Mark codes that were already redeemed as used, so the list shows which ones are left. Say how many are left in text next to the grid, because the strike-through is visual only.
- Confirm the copy in the copy handler, for example with a status line or a toast. It runs only after the clipboard took the code.
- Offer a second way next to the list, such as Download as a text file, for the moment the clipboard is blocked.
- Give each code a cell of at least 9 rem. A narrower box wraps the code at its hyphen.

### Don't

- Don't show your own Copied message on press. When the clipboard is blocked (an iframe, an http page, a denied permission) the copy handler does not run, and a message of your own would be wrong.
- Don't rely on the copy icon to find the button. It shows on hover only, so on a touch screen the code itself is the target.
- Don't use real codes in docs or tests. The demos here are made up and are not held anywhere.

## API reference

### BackupCode

| Prop | Type | Default | Description |
|---|---|---|---|
| code* | string |  | The recovery code. It is the text of the button, the accessible name and the text that is copied. Required. |
| className | string |  | Added to the button. Use it for the width in a grid. |
| onCopy | (code: string) => void |  | Called with the code after the clipboard accepted it. It is not called when the clipboard refuses, so use it for the confirmation. |
| used | boolean |  | Disables the button, strikes the code through and turns it tertiary. A used code cannot be pressed or focused. |

## Examples

### State: default and used

```tsx
import { BackupCode } from "@wunderui/react"

export function Example({ onCopy }: { onCopy: (code: string) => void }) {
  return <BackupCode code="4F7K-9QX2" onCopy={onCopy} />
}
```

### Clipboard: allowed and blocked

```tsx
import { BackupCode } from "@wunderui/react"

export function Example({ onCopy }: { onCopy: (code: string) => void }) {
  // onCopy runs after the clipboard took the code.
  return <BackupCode code="4F7K-9QX2" onCopy={onCopy} />
}
```

### Text: short, long and narrow

```tsx
import { BackupCode } from "@wunderui/react"

export function Example({ onCopy }: { onCopy: (code: string) => void }) {
  return <BackupCode code="4F7K-9QX2" onCopy={onCopy} />
}
```

### Layout: grids of codes

```tsx
import { BackupCode } from "@wunderui/react"

const CODES = ["4F7K-9QX2", "M8TD-3WLB", "H2VN-6RJC", "Q9ZP-4XKA", "B5GY-7DNE", "W3LS-8UHF", "R6CE-2MTV", "J7AX-5PQK"]

export function Codes({ onCopy }: { onCopy: (code: string) => void }) {
  return (
    <div className="grid grid-cols-2 gap-2">
      {CODES.map((code, index) => (
        <BackupCode key={code} code={code} used={index === 1} onCopy={onCopy} />
      ))}
    </div>
  )
}
```

## In context

### Recovery codes: copy, download and generate new ones

Press a code to copy it, or use Copy all and Download. Generate new codes asks first, then replaces all eight, and the Clipboard switch makes copying fail.

```tsx
import { useState } from "react"
import { Copy, Download } from "lucide-react"
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogIcon,
  AlertDialogTitle,
  BackupCode,
  Button,
} from "@wunderui/react"

const FIRST = ["4F7K-9QX2", "M8TD-3WLB", "H2VN-6RJC", "Q9ZP-4XKA", "B5GY-7DNE", "W3LS-8UHF", "R6CE-2MTV", "J7AX-5PQK"]

export function RecoveryCodes({ makeCodes }: { makeCodes: () => string[] }) {
  const [codes, setCodes] = useState(FIRST)
  const [confirm, setConfirm] = useState(false)
  const [message, setMessage] = useState("")

  async function copyAll() {
    try {
      await navigator.clipboard.writeText(codes.join("\n"))
      setMessage("Copied 8 codes.")
    } catch {
      setMessage("The clipboard is blocked. Download the codes instead.")
    }
  }

  function download() {
    const file = new Blob([codes.join("\n")], { type: "text/plain" })
    const link = Object.assign(document.createElement("a"), { href: URL.createObjectURL(file), download: "wunderui-recovery-codes.txt" })
    link.click()
    URL.revokeObjectURL(link.href)
    setMessage("Downloaded wunderui-recovery-codes.txt.")
  }

  return (
    <section aria-label="Recovery codes" className="flex flex-col gap-4">
      <div className="grid grid-cols-2 gap-2 rounded-xl bg-muted p-4">
        {codes.map((code) => (
          <BackupCode key={code} code={code} onCopy={(value) => setMessage("Copied " + value + ".")} />
        ))}
      </div>
      <div className="flex gap-2">
        <Button variant="plain" onClick={download}>
          <Download className="size-4" strokeWidth={1.5} />
          Download
        </Button>
        <Button variant="plain" onClick={copyAll}>
          <Copy className="size-4" strokeWidth={1.5} />
          Copy all
        </Button>
        <Button variant="plain" onClick={() => setConfirm(true)}>
          Generate new codes
        </Button>
      </div>
      <p role="status" className="min-h-4 text-xs text-text-secondary">
        {message}
      </p>
      <AlertDialog open={confirm} onOpenChange={setConfirm}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogIcon variant="destructive" />
            <AlertDialogTitle>Generate new codes?</AlertDialogTitle>
            <AlertDialogDescription>The 8 codes you have now stop working. Save the new ones before you leave.</AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Keep current codes</AlertDialogCancel>
            <AlertDialogAction
              variant="destructive"
              onClick={() => {
                setCodes(makeCodes())
                setMessage("New codes generated. The old ones no longer work.")
              }}
            >
              Generate new codes
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </section>
  )
}
```

### Recovery status: codes get used up

Each press of Sign in with a code uses the next code up and strikes it through. With two or fewer left, a line asks for new ones.

```tsx
import { useRef, useState } from "react"
import { BackupCode, Button } from "@wunderui/react"

const CODES = ["4F7K-9QX2", "M8TD-3WLB", "H2VN-6RJC", "Q9ZP-4XKA", "B5GY-7DNE", "W3LS-8UHF", "R6CE-2MTV", "J7AX-5PQK"]

export function RecoveryStatus() {
  const [used, setUsed] = useState(3)
  const left = CODES.length - used
  const section = useRef<HTMLElement>(null)

  return (
    <section ref={section} tabIndex={-1} aria-label="Recovery codes" className="flex flex-col gap-4 outline-none">
      <div className="flex items-center justify-between gap-3">
        <p className="text-sm text-text-secondary">
          {left === 0 ? "No codes left." : left + (left === 1 ? " code" : " codes") + " left"}
        </p>
        <Button
          size="sm"
          variant="plain"
          disabled={left === 0}
          onClick={() => {
            setUsed((count) => count + 1)
            if (left === 1) section.current?.focus() // the focused button is disabled now: keep the keyboard in the list
          }}
        >
          Sign in with a code
        </Button>
      </div>
      <div className="grid grid-cols-2 gap-2">
        {CODES.map((code, index) => (
          <BackupCode key={code} code={code} used={index < used} />
        ))}
      </div>
      {left > 0 && left <= 2 && (
        <p role="status" className="text-xs text-text-warning">
          Generate new codes soon.
        </p>
      )}
    </section>
  )
}
```

## For AI agents

`get_component("backup-code")`

Hand your agent this page as Markdown or the WunderUI MCP server, not a screenshot.
