Device code
The code that a person types on another device, with the address to open and the state of the wait.
The screen of a TV app, of a CLI in a browser tab, or of an agent that enrolls itself. It shows a short code, says where to type it, and waits. The preview "approves" by itself after a few seconds.
Installation
- CLI
- Manual
The command adds the file to your project, with the shadcn/ui components that it uses. Your project needs shadcn/ui.
- pnpm
- npm
- yarn
- bun
pnpm dlx shadcn@latest add https://examples.lumoauth.dev/r/device-code.json
npx shadcn@latest add https://examples.lumoauth.dev/r/device-code.json
yarn dlx shadcn@latest add https://examples.lumoauth.dev/r/device-code.json
bunx --bun shadcn@latest add https://examples.lumoauth.dev/r/device-code.json
Add the shadcn/ui components that the pattern uses.
npx shadcn@latest add button cardInstall the packages.
npm install lucide-reactCopy the code into your project.
components/device-code.tsx'use client';import * as React from 'react';import { Check, Copy, MonitorSmartphone, RotateCw, X } from 'lucide-react';import { Button } from '@/components/ui/button';import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';import { cn } from '@/lib/utils';export type DeviceCodeStatus = 'waiting' | 'slow_down' | 'connected' | 'denied' | 'expired';export interface DeviceCodeData {/** The short code that the person types, for example `WDJB-MJHT`. */userCode: string;/** The address that the person opens. */verificationUri: string;/** The same address with the code in it, for a QR code. */verificationUriComplete?: string;/** When the code stops working (ISO 8601). */expiresAt?: string;}/*** Maps the answer of `POST /oauth/device_authorization` (RFC 8628). Call it* when the answer arrives, not during render: it reads the clock.*/export function fromDeviceAuthorization(response: {user_code: string;verification_uri: string;verification_uri_complete?: string;expires_in?: number;}): DeviceCodeData {return {userCode: response.user_code,verificationUri: response.verification_uri,verificationUriComplete: response.verification_uri_complete,expiresAt: response.expires_in ? new Date(Date.now() + response.expires_in * 1000).toISOString() : undefined,};}export interface DeviceCodeProps {code: DeviceCodeData;status: DeviceCodeStatus;/** What connects: "this TV", "the forge CLI", "Sidekick". */deviceName?: string;/** A QR code of `verificationUriComplete`. Render it with the library that your project uses. */qr?: React.ReactNode;/** Ask for a new code. Shown when the code expired or was denied. */onRestart?: () => void;className?: string;}/*** The current time, or null on the server and in the first render. Reading* the clock during render breaks prerendering and hydration, so it is read* in an effect.*/function useNow(active = true) {const [now, setNow] = React.useState<number | null>(null);React.useEffect(() => {if (!active) return;setNow(Date.now());const timer = setInterval(() => setNow(Date.now()), 1000);return () => clearInterval(timer);}, [active]);return now;}function useCountdown(expiresAt: string | undefined, active: boolean) {const now = useNow(active && Boolean(expiresAt));if (!expiresAt || now === null) return null;const left = Math.max(0, Math.floor((new Date(expiresAt).getTime() - now) / 1000));return { left, text: `${Math.floor(left / 60)}:${String(left % 60).padStart(2, '0')}` };}export function DeviceCode({ code, status, deviceName = 'this device', qr, onRestart, className }: DeviceCodeProps) {const waiting = status === 'waiting' || status === 'slow_down';const countdown = useCountdown(code.expiresAt, waiting);const shown: DeviceCodeStatus = waiting && countdown?.left === 0 ? 'expired' : status;const [copied, setCopied] = React.useState(false);const address = code.verificationUri.replace(/^https?:\/\//, '');const copy = async () => {await navigator.clipboard?.writeText(code.userCode);setCopied(true);setTimeout(() => setCopied(false), 1500);};if (shown === 'connected') {return (<Card className={cn('w-full max-w-md items-center gap-3 text-center', className)}><span className="flex size-10 items-center justify-center rounded-full bg-emerald-500/15 text-emerald-700 dark:text-emerald-400"><Check className="size-5" aria-hidden="true" /></span><CardTitle className="text-base">Connected</CardTitle><CardDescription className="px-6">You are signed in on {deviceName}. You can close the page on your other device.</CardDescription></Card>);}if (shown === 'denied' || shown === 'expired') {return (<Card className={cn('w-full max-w-md items-center gap-3 text-center', className)}><span className="flex size-10 items-center justify-center rounded-full bg-muted text-muted-foreground"><X className="size-5" aria-hidden="true" /></span><CardTitle className="text-base">{shown === 'denied' ? 'The request was denied' : 'The code expired'}</CardTitle><CardDescription className="px-6">{shown === 'denied' ? `Nobody is signed in on ${deviceName}.` : 'A code works for a short time only.'}</CardDescription>{onRestart && (<Button onClick={onRestart}><RotateCw aria-hidden="true" />Get a new code</Button>)}</Card>);}return (<Card className={cn('w-full max-w-md gap-5', className)}><CardHeader className="justify-items-center text-center"><MonitorSmartphone className="size-6 text-muted-foreground" aria-hidden="true" /><CardTitle className="text-base">Sign in on {deviceName}</CardTitle><CardDescription>On your phone or computer, open <span className="font-medium text-foreground">{address}</span> and enter this code.</CardDescription></CardHeader><CardContent className="grid justify-items-center gap-4"><div className="flex items-center gap-2"><output aria-label="Code" className="rounded-lg border bg-muted/50 px-4 py-2 font-mono text-3xl font-semibold tracking-[0.2em]">{code.userCode}</output><Button variant="ghost" size="icon" onClick={copy} aria-label="Copy the code">{copied ? <Check aria-hidden="true" /> : <Copy aria-hidden="true" />}</Button></div>{qr && <div className="rounded-lg border bg-white p-2">{qr}</div>}</CardContent><CardFooter className="justify-center gap-2 text-sm text-muted-foreground" role="status" aria-live="polite"><span className="size-2 animate-pulse rounded-full bg-amber-500" aria-hidden="true" />{status === 'slow_down' ? 'Still waiting. Checking less often now.' : 'Waiting for you to approve.'}{countdown && <span className="tabular-nums">The code works for {countdown.text}.</span>}</CardFooter></Card>);}Change the import paths if your project keeps its components in another place.
Usage
fromDeviceAuthorization maps the answer of the device authorization endpoint. Your code polls the token endpoint and sets the status.
'use client';
import * as React from 'react';
import { DeviceCode, fromDeviceAuthorization, type DeviceCodeData, type DeviceCodeStatus } from '@/components/device-code';
export function TvSignIn() {
const [code, setCode] = React.useState<DeviceCodeData | null>(null);
const [status, setStatus] = React.useState<DeviceCodeStatus>('waiting');
const start = React.useCallback(async () => {
const response = await fetch('/api/device/start', { method: 'POST' }).then((r) => r.json());
setCode(fromDeviceAuthorization(response));
setStatus('waiting');
}, []);
React.useEffect(() => void start(), [start]);
// Poll your backend, which polls the token endpoint with the device code.
React.useEffect(() => {
if (!code || (status !== 'waiting' && status !== 'slow_down')) return;
const timer = setInterval(async () => {
const { state } = await fetch('/api/device/poll').then((r) => r.json());
if (state !== 'authorization_pending') setStatus(state === 'access_denied' ? 'denied' : state === 'expired_token' ? 'expired' : state);
}, 5000);
return () => clearInterval(timer);
}, [code, status]);
return code ? <DeviceCode code={code} status={status} deviceName="this TV" onRestart={start} /> : null;
}
The pattern has no QR library of its own. Pass a QR code of verificationUriComplete as qr, drawn with the library that your project uses. The page that the person opens is the hosted device activation page.
Where the data comes from
| What the pattern shows | Call |
|---|---|
| The code and the address | POST /oauth/device_authorization: user_code, verification_uri, verification_uri_complete, expires_in, interval |
| The wait | POST /oauth/token with the device grant type: authorization_pending, slow_down, access_denied, expired_token |
| An agent that enrolls itself | POST /agents/enrollments, then POST /agents/enrollments/token |
States
- Slow down. The server asked for a longer interval.
- Connected.
- Denied, with "Get a new code".
- Expired. A waiting code whose time ran out shows this state by itself.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
coderequired | DeviceCodeData | The code: userCode, verificationUri, verificationUriComplete and expiresAt. | |
statusrequired | 'waiting' | 'slow_down' | 'connected' | 'denied' | 'expired' | The state of the wait. | |
deviceName | string | 'this device' | What connects, for example "this TV". |
qr | ReactNode | A QR code of verificationUriComplete. | |
onRestart | () => void | Ask for a new code. The button appears when the code expired or was denied. | |
className | string | Class name for the card. |