Skip to content
Browse documentation

A one-time code step with a carrier pigeon: Coo naps through the resend wait with the seconds in a thought bubble, and flies every new code to your mailbox.

Used forEmail sign-upPasswordless sign-inTwo-factorChanging an email

Install with the shadcn CLI

$ npx shadcn@latest add @hairline/verify-code

Older shadcn CLI, or a network that blocks ui.shadcn.com? Install by URL: shadcn add https://hairlineui.com/r/verify-code.json. More

Templates

Need the whole page?

65 Next.js landing pages, each designed from scratch. Try any of them live; one is $39, all of them $159, and 8 are free.

Where it’s used

  • Email sign-up

    Confirm the address with the code you just sent, before the account opens.

  • Passwordless sign-in

    The magic-code step of an email or SMS login.

  • Two-factor

    A code by text message before a sensitive change.

  • Changing an email

    Prove the new address is yours before it’s saved.

What it handles for you

A verify step usually leaves people staring at a disabled Resend link with no idea how long is left or whether anything is happening. This block shows the wait, shows the send, and says plainly when a send didn’t go through.

Instead of wiring upan OTP inputa resend countdownresend button statesa wrong-code shakea verified state
  1. Real code input

    One input with one-time-code autofill, paste and the numeric keyboard; the boxes are only what you see.

  2. A wait you can see

    Coo naps through the resend wait with the seconds rolling down in a thought bubble over his head.

  3. Your server’s wait

    onResend can return { retryAfter } and the next clock uses it.

  4. Sends that fail

    If onResend throws, Coo comes back with the envelope and Resend turns into Try again.

  5. Wrong and right

    A wrong code shakes and clears the boxes; the right one closes them into a pill with a drawn check.

  6. Email or text

    channel sets the wording (inbox or number), and Change lets people fix the address.

Overview

The “check your inbox” step is a row of boxes and a resend link greyed out for thirty seconds. This one hands it to Coo, an illustrated carrier pigeon in a postman’s cap standing on a post across the stage from a red mailbox with its flag up. He nods along with every digit you type. A wrong code and he shakes his head while the boxes shake and clear; the right one closes the boxes into one pill and he puffs his chest out with two proud flaps. While the resend clock runs he naps on his post, eye shut and z’s drifting up, with a thought bubble over his head rolling the seconds down; typing wakes him to read along, and at zero the bubble pops and he hops up, ready to fly. Resend sends him off with a new envelope in his beak: he flies the route, waits over the mailbox until your send is done, pops the flag and flies home empty, and the clock starts again with whatever wait your server asked for. If the send fails he comes back with the envelope still in his beak. Underneath it is the real thing: one input with one-time-code autofill, paste and the numeric keyboard, onVerify for your check and onResend for your sender.

States

napping
Coo stands on his post at the left of the lit stage, the red mailbox with its flag up at the right and his dashed route between them. While the resend clock runs he dozes: his eye shuts, a z drifts up from his cap every 1.1s, and a thought bubble rolls the seconds down; the line reads “Coo is catching his breath”.
typing
Typing wakes him for 4s (“Coo is reading along”): each digit rises into its box and he nods forward from his feet.
checking
With every box full the row carries a sweep of light and the line reads “Coo is checking”.
wrong
onVerify returns false or throws: Coo shakes his head, the boxes shake, turn red and clear from the right; the line reads “Not the code Coo carried”.
right
The boxes close into one pill with a drawn check, Coo puffs his chest with two flaps and a hop, and the resend line folds away; “Signed for. You’re in.”
ready
At zero the bubble shrinks away into a blur, he wakes with a hop, the line reads “Coo is ready to fly again” and “Resend in 0:00” turns into Resend code.
resend
Coo takes off with an envelope (1s along the route, with real wingbeats), waits over the mailbox until onResend settles, pops the flag and flies home empty; Sent, then the clock starts again.
send failed
onResend throws: he turns back with the envelope still in his beak, the line says “Coo couldn’t get through” and Resend shakes into Try again.

Usage

usage.tsx
import { VerifyCode } from "@/components/verify-code";<VerifyCode  destination={email}  onVerify={(code) => verifyCode(email, code)}  onResend={() => sendCode(email)}/>

Works with

With your own endpoints

Return false for a wrong code, and pass your rate limit back as retryAfter so the clock matches it.

example.tsx
"use client";import { VerifyCode } from "@/components/verify-code";export function CheckInbox({ email, onDone }: { email: string; onDone: () => void }) {  return (    <VerifyCode      destination={email}      autoFocus      onVerify={async (code) => {        const res = await fetch("/api/verify", { method: "POST", body: JSON.stringify({ email, code }) });        if (!res.ok) return false;        setTimeout(onDone, 1200); // after Coo's flaps      }}      onResend={async () => {        const res = await fetch("/api/verify/resend", { method: "POST", body: JSON.stringify({ email }) });        if (!res.ok) throw new Error("Couldn’t send");        return { retryAfter: Number(res.headers.get("Retry-After") ?? 30) };      }}    />  );}

Props

destination
string
Where the code went, shown in the line under the title.
onVerify
(code: string) => Promise<boolean | void>
Check the code. Resolve (or return true) to accept; return false or throw for a wrong code.
onResend
() => Promise<{ retryAfter?: number } | void>
Send a new code. Return { retryAfter } in seconds to set the next wait; throw if it didn’t go.
channel= "email"
"email" | "sms"
The title says inbox or number.
length= 6
number
How many digits.
resendAfter= 30
number
Seconds before the first resend, and between resends when onResend doesn’t say.
onChangeDestination
() => void
Shows Change beside the address.
title / name / autoFocus= "Check your inbox" / "Coo" / false
string / string / boolean
The heading, the pigeon’s name in his lines, and whether the code field takes focus on mount.

Accessibility and motion

  • The code field is Code input: one real input with autocomplete="one-time-code", so SMS autofill, paste and password managers work; its label and status line say what happened.
  • The countdown’s digits (in the bubble and the resend line) are hidden from screen readers; they hear that a resend is coming and when it’s sent or failed.
  • Coo is decoration (aria-hidden). He, the mailbox and the post are illustrations in coo-art.ts and his flight is wingbeat loops cut from generated animations in coo-fly-art.ts (WebP data URIs, about 55KB together), so the install is complete; his nods, nap, blink, z’s and the mailbox flag are code.
  • One frame loop outside React moves him and sleeps when he’s still; his breathing is a compositor animation. The scene is drawn at 364 × 176 and scaled to the stage.
  • With reduced motion he doesn’t fly or nod: the flag and his pose change in place.
  • Built from Code input, Number roll, Status button and Text morph, which the CLI installs with it. No animation library.

Requirements

React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.

The CLI also installs Code input, Number roll, Status button, Text morph.

Source

"use client";import * as React from "react";import { CodeInput } from "./code-input";import { Coo, type CooHandle } from "./coo-pigeon";import { NumberRoll } from "./number-roll";import { StatusButton, type ActionStatus } from "./status-button";import { TextMorph } from "./text-morph";import { EASE_OUT, useInteractionReducedMotion } from "./ui-interaction-motion";/* ───────────────────────────────────────────────────────── * VERIFY CODE: the pigeon who carried it * *   waiting  Coo stands on his post across the stage from the *            mailbox; its flag is up, your code is in there *   reading  every digit you type, he nods along *   wrong    he shakes his head; the boxes shake and clear *   right    the boxes close into one pill, he puffs his chest *            and gives two proud flaps *   wait     while the resend clock runs he naps on his post, *            z's drifting up and a thought bubble counting the *            seconds down; typing wakes him to read along, and *            at zero the bubble pops and he hops up, ready *   resend   he takes off with a new envelope, flies the route, *            pops the mailbox flag and flies home; if the send *            fails he comes back with the envelope in his beak * * onVerify gets the code, onResend sends another; both are * yours, whatever sends your codes. * ───────────────────────────────────────────────────────── */export interface VerifyCodeProps {  /** Where the code went: an email address or a phone number. */  destination: string;  channel?: "email" | "sms";  length?: number;  /** Check the code. Resolve (or return true) to accept; return false or throw to say it's wrong. */  onVerify: (code: string) => Promise<boolean | void>;  /** Send a new code. Return { retryAfter } (seconds) to set the next wait; throw to say it didn't go. */  onResend: () => Promise<{ retryAfter?: number } | void | unknown>;  /** Seconds before the first resend. */  resendAfter?: number;  /** Shows Change beside the address. */  onChangeDestination?: () => void;  title?: string;  /** What the pigeon is called in his lines. */  name?: string;  autoFocus?: boolean;  className?: string;}const mix = (color: string, amount: number, into = "transparent") => `color-mix(in oklab, ${color} ${amount}%, ${into})`;const PF = "var(--primary-foreground)";const CARD: React.CSSProperties = {  backgroundImage: `linear-gradient(180deg, var(--card), ${mix("var(--card)", 95, "var(--foreground)")})`,  boxShadow: `0 0 0 1px var(--border), inset 0 1px 0 ${mix("var(--background)", 85)}`,};/* The one lit surface, ruled with faint airmail stripes along its foot: the sky he flies through. */const STAGE: React.CSSProperties = {  backgroundColor: "var(--primary)",  backgroundImage: [    `radial-gradient(90% 70% at 50% 0%, ${mix(PF, 20)} 0%, transparent 62%)`,    `linear-gradient(175deg, transparent 45%, ${mix("black", 20)} 100%)`,    `repeating-linear-gradient(-45deg, ${mix(PF, 10)} 0 7px, transparent 7px 14px, ${mix(PF, 5)} 14px 21px, transparent 21px 28px)`,  ].join(", "),  backgroundSize: "auto, auto, 100% 7px",  backgroundRepeat: "no-repeat, no-repeat, repeat-x",  backgroundPosition: "0 0, 0 0, 0 100%",  boxShadow: `inset 0 1px 0 ${mix(PF, 36)}, inset 0 0 0 1px ${mix(PF, 12)}`,};const COO = {  "--coo-route": PF,  "--coo-z": PF,  "--coo-bubble": PF,  "--coo-bubble-ink": "var(--primary)",} as React.CSSProperties;type Flight = "home" | "away" | "failed";export function VerifyCode({  destination,  channel = "email",  length = 6,  onVerify,  onResend,  resendAfter = 30,  onChangeDestination,  title,  name = "Coo",  autoFocus,  className = "",}: VerifyCodeProps) {  const reduced = useInteractionReducedMotion();  const baseId = React.useId();  const coo = React.useRef<CooHandle>(null);  const [phase, setPhase] = React.useState<"idle" | "checking" | "wrong" | "right">("idle");  const [left, setLeft] = React.useState(resendAfter);  const [send, setSend] = React.useState<ActionStatus>("idle");  const [flight, setFlight] = React.useState<Flight>("home");  const typed = React.useRef(0);  // typing wakes him for a while; then he nods off again if the clock is still running  const [awake, setAwake] = React.useState(false);  const awakeTimer = React.useRef(0);  React.useEffect(() => () => window.clearTimeout(awakeTimer.current), []);  // whole seconds down to zero; the route drains with them  React.useEffect(() => {    if (left <= 0 || flight === "away") return;    const timer = window.setTimeout(() => setLeft((s) => Math.max(0, s - 1)), 1000);    return () => window.clearTimeout(timer);  }, [left, flight]);  const resend = async () => {    if (send === "pending" || left > 0 || flight === "away") return;    setSend("pending");    setFlight("away");    coo.current?.send();    let next = resendAfter;    let ok = true;    try {      const res = await onResend();      const after = (res as { retryAfter?: number } | undefined)?.retryAfter;      if (typeof after === "number" && after >= 0) next = after;    } catch {      ok = false;    }    const home = () => {      setFlight(ok ? "home" : "failed");      setSend(ok ? "success" : "error");      if (ok) {        setLeft(next);      }      window.setTimeout(() => setSend((s) => (s === "success" ? "idle" : s)), 1400);    };    if (coo.current) coo.current.delivered(ok, home);    else home();  };  const verify = async (code: string) => {    setPhase("checking");    let ok = false;    try {      ok = (await onVerify(code)) !== false;    } catch {      ok = false;    }    setPhase(ok ? "right" : "wrong");    if (ok) coo.current?.puff();    else coo.current?.ruffle();    return ok;  };  const where = channel === "sms" ? "number" : "inbox";  const mood =    phase === "right"      ? "Signed for. You’re in."      : phase === "wrong"        ? `Not the code ${name} carried`        : phase === "checking"          ? `${name} is checking`          : flight === "away"            ? `${name} is on his way`            : flight === "failed"              ? `${name} couldn’t get through`              : send === "success"                ? "A fresh code, delivered"                : left > 0                  ? awake                    ? `${name} is reading along`                    : `${name} is catching his breath`                  : `${name} is ready to fly again`;  const ready = left <= 0 && flight !== "away";  return (    <section aria-labelledby={`${baseId}-title`} className={`relative w-full max-w-[380px] rounded-[28px] p-2 text-card-foreground ${className}`} style={{ ...CARD, ...COO }}>      {/* Its natural width where the parent sizes to its content, without forcing it on narrow screens. */}      <div aria-hidden="true" data-natural-width className="grid h-0" style={{ gridTemplateColumns: "minmax(0, 380px)" }} />      <div className="@container w-full">        <div className="relative overflow-clip rounded-[22px] text-primary-foreground" style={STAGE}>          <Coo ref={coo} wait={flight === "away" || phase === "right" ? 0 : left} dozing={!awake && flight === "home" && (phase === "idle" || phase === "wrong")} reduced={reduced} />          <p className="absolute inset-x-0 bottom-3 z-10 text-center text-[12.5px] font-medium text-primary-foreground/85 @max-[340px]:bottom-2 @max-[340px]:text-[11.5px]">            <TextMorph>{mood}</TextMorph>          </p>        </div>        <div className="px-3 pb-2 pt-3">          <h2 id={`${baseId}-title`} className="text-[15px] font-medium tracking-[-0.01em]">            {title ?? `Check your ${where}`}          </h2>          <p className="mt-0.5 text-[12.5px] text-muted-foreground">            {name} brought a {length}-digit code to <span className="font-medium text-foreground">{destination}</span>            {onChangeDestination ? (              <>                {" · "}                <button type="button" onClick={onChangeDestination} className="cursor-pointer underline decoration-border underline-offset-2 hover:text-foreground">                  Change                </button>              </>            ) : (              "."            )}          </p>          <CodeInput            className="mt-3"            length={length}            label="Enter the code"            autoFocus={autoFocus}            onValueChange={(v) => {              setAwake(true);              window.clearTimeout(awakeTimer.current);              awakeTimer.current = window.setTimeout(() => setAwake(false), 4000);              if (v.length > typed.current) coo.current?.peck();              typed.current = v.length;              if (phase === "wrong") setPhase("idle");            }}            onComplete={verify}          />          {/* the resend line folds away once the code is right */}          <div className="grid" style={{ gridTemplateRows: phase === "right" ? "0fr" : "1fr", opacity: phase === "right" ? 0 : 1, transition: reduced ? "none" : `grid-template-rows 420ms ${EASE_OUT}, opacity 240ms` }}>            <div className="min-w-0 overflow-hidden" inert={phase === "right"}>              <div className="mt-2.5 flex h-7 items-center gap-1.5 text-[12px] text-muted-foreground">                <span>{flight === "failed" ? "Couldn’t send that." : "Didn’t get it?"}</span>                <span className="grid items-center">                  <span className="sr-only">{ready ? "" : flight === "away" ? "Sending a new code." : "You can resend the code shortly."}</span>                  <span                    aria-hidden="true"                    className="col-start-1 row-start-1 flex items-baseline whitespace-nowrap tabular-nums"                    style={{ opacity: ready ? 0 : 1, filter: ready ? "blur(3px)" : "none", transition: reduced ? "none" : `opacity 260ms ${EASE_OUT}, filter 260ms ${EASE_OUT}` }}                  >                    {flight === "away" ? (                      <TextMorph>Sending</TextMorph>                    ) : (                      <>                        Resend in {Math.floor(left / 60)}:                        <NumberRoll value={left % 60} format={{ minimumIntegerDigits: 2 }} direction="down" duration={700} />                      </>                    )}                  </span>                  <span className="col-start-1 row-start-1" inert={!ready} style={{ opacity: ready ? 1 : 0, filter: ready ? "none" : "blur(3px)", transition: reduced ? "none" : `opacity 260ms ${EASE_OUT}, filter 260ms ${EASE_OUT}` }}>                    <StatusButton                      variant="ghost"                      size="sm"                      status={send === "pending" ? "idle" : send}                      labels={{ idle: "Resend code", success: "Sent", error: "Try again" }}                      onClick={resend}                      className="-ml-2"                    />                  </span>                </span>              </div>            </div>          </div>        </div>      </div>    </section>  );}export default VerifyCode;

Registry item: /r/verify-code.json