API keys
A table of keys, a dialog that shows the new key once, and a revoke that asks first.
277 lines · React · Tailwind 4
Install
$ bunx shadcn@latest add @blocco/api-keysCode
import { useRef, useState, type FormEvent } from "react";
import { Button, IconButton } from "@/registry/blocco/ui/button";
import { ConfirmDialog } from "@/registry/blocco/ui/confirm-dialog";
import { CopyButton } from "@/registry/blocco/ui/copy-button";
import { Dialog } from "@/registry/blocco/ui/dialog";
import { Field, Input } from "@/registry/blocco/ui/field";
import { Plus, Trash2 } from "@/registry/blocco/ui/icons";
import { EmptyState, PageHeader, Table, Td, Th } from "@/registry/blocco/ui/misc";
import { OverflowTip } from "@/registry/blocco/ui/overflow-tip";
import { BusyContent } from "@/registry/blocco/ui/spinner";
import { useToast } from "@/registry/blocco/ui/toast";
import { cn } from "@/registry/blocco/ui/cn";
interface ApiKey {
id: string;
name: string;
/** The first characters, the only part shown after creation. */
prefix: string;
created: string;
lastUsed: string | null;
/** The whole key: present only on the one just made. */
key?: string;
}
const initial: ApiKey[] = [
{
id: "1",
name: "Production server",
prefix: "ak_live_9fQ2",
created: "Oct 2, 2026 by Ada",
lastUsed: "2 minutes ago",
},
{
id: "2",
name: "Zapier",
prefix: "ak_live_k3Lx",
created: "Sep 14, 2026 by Grace",
lastUsed: "3 days ago",
},
{
id: "3",
name: "Claude",
prefix: "ak_live_Wm8e",
created: "Aug 29, 2026 by Ada",
lastUsed: null,
},
];
const ALPHABET = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
/** 32 random characters after a readable prefix. The prefix is stored and
* shown; only the person who just made the key ever sees the rest. */
function mintKey(): string {
const bytes = crypto.getRandomValues(new Uint8Array(32));
return `ak_live_${Array.from(bytes, (b) => ALPHABET[b % ALPHABET.length]).join("")}`;
}
/** The key value, shown once right after minting, with its copy button. */
function ShownOnce({ apiKey, onDone }: { apiKey: ApiKey; onDone: () => void }) {
const toast = useToast();
return (
<div className="flex flex-col gap-4">
<p className="text-sm text-pretty">
<strong>{apiKey.name}</strong> is ready. Copy the key now: it won't be shown again.
</p>
<div className="flex items-center gap-2">
<code className="min-w-0 flex-1 rounded-lg bg-surface-2 px-3 py-2 font-mono text-xs [overflow-wrap:anywhere]">
{apiKey.key}
</code>
<CopyButton
text={apiKey.key ?? ""}
label="Copy key"
onCopy={async (text) => {
await navigator.clipboard.writeText(text);
toast("Copied");
}}
/>
</div>
<div className="flex justify-end pt-1">
<Button variant="primary" onClick={onDone}>
Done
</Button>
</div>
</div>
);
}
function NameForm({ onCreate, creating }: { onCreate: (name: string) => void; creating: boolean }) {
const [name, setName] = useState("");
const [error, setError] = useState<string | undefined>();
const input = useRef<HTMLInputElement>(null);
const submit = (event: FormEvent) => {
event.preventDefault();
if (creating) return;
const trimmed = name.trim();
if (!trimmed) {
setError("Required");
input.current?.focus();
return;
}
onCreate(trimmed);
};
return (
<form onSubmit={submit} noValidate className="flex flex-col gap-4">
<Field label="Name" error={error}>
<Input
ref={input}
autoFocus
autoComplete="off"
maxLength={100}
value={name}
onChange={(e) => {
setName(e.target.value);
setError(undefined);
}}
placeholder="Key name, e.g. Production server"
/>
</Field>
<p className="text-xs text-pretty text-muted">
You see the full key once, when you create it.
</p>
<div className="flex justify-end pt-1">
<Button type="submit" variant="primary">
<BusyContent busy={creating}>Create key</BusyContent>
</Button>
</div>
</form>
);
}
/** One key: its name, its prefix in mono, when it was made and when it last
* called. The trash shows on hover where there is hover. */
function Row({ apiKey, onRevoke }: { apiKey: ApiKey; onRevoke: () => void }) {
return (
<tr className="group/row">
<OverflowTip content={apiKey.name}>
<Td className="truncate text-sm font-semibold">{apiKey.name}</Td>
</OverflowTip>
<Td className="hidden truncate font-mono text-xs text-muted sm:table-cell">
{apiKey.prefix}…
</Td>
<Td className="tnum hidden text-sm whitespace-nowrap text-muted md:table-cell">
{apiKey.created}
</Td>
<Td
className={cn(
"tnum text-sm whitespace-nowrap",
apiKey.lastUsed ? "text-muted" : "text-placeholder",
)}
>
{apiKey.lastUsed ?? "Never"}
</Td>
<Td className="py-1.5">
<div className="flex justify-end transition-opacity duration-150 [@media(hover:hover)]:opacity-0 [@media(hover:hover)]:group-hover/row:opacity-100 [@media(hover:hover)]:focus-within:opacity-100">
<IconButton label={`Revoke ${apiKey.name}`} danger onClick={onRevoke}>
<Trash2 size={15} />
</IconButton>
</div>
</Td>
</tr>
);
}
/** Keys in a table, "Create key" as the page's one primary button. A new
* key shows once in the dialog that made it; revoking asks first. */
export default function ApiKeys() {
const toast = useToast();
const [keys, setKeys] = useState(initial);
const [createOpen, setCreateOpen] = useState(false);
const [justCreated, setJustCreated] = useState<ApiKey | null>(null);
const [creating, setCreating] = useState(false);
const [revokeTarget, setRevokeTarget] = useState<ApiKey | null>(null);
const create = async (name: string) => {
setCreating(true);
await new Promise((r) => setTimeout(r, 500));
const key = mintKey();
const made: ApiKey = {
id: crypto.randomUUID(),
name,
prefix: key.slice(0, 12),
created: "Just now",
lastUsed: null,
key,
};
setKeys((all) => [{ ...made, key: undefined }, ...all]);
setJustCreated(made);
setCreating(false);
};
return (
<section className="mx-auto max-w-4xl px-4 py-10 sm:px-6 sm:py-12">
<PageHeader
title="API keys"
sub="Call the API from your own code."
action={
<Button
variant="primary"
onClick={() => {
// Cleared on the next open, not on close, so the dialog does
// not swap back to the form while it animates out.
setJustCreated(null);
setCreateOpen(true);
}}
>
<Plus size={15} aria-hidden /> Create key
</Button>
}
/>
<div className="flex flex-col gap-3">
{keys.length === 0 ? (
<EmptyState
title="No API keys yet"
hint="Create one to call the API from your own code."
/>
) : (
<>
<Table fixed>
<thead>
<tr>
<Th>Name</Th>
<Th className="hidden sm:table-cell sm:w-44">Key</Th>
<Th className="hidden md:table-cell md:w-52">Created</Th>
<Th className="w-32">Last used</Th>
<Th className="w-14">
<span className="sr-only">Actions</span>
</Th>
</tr>
</thead>
<tbody>
{keys.map((k) => (
<Row key={k.id} apiKey={k} onRevoke={() => setRevokeTarget(k)} />
))}
</tbody>
</Table>
<p className="text-xs text-pretty text-muted">
A key acts as you, in every workspace you belong to. You see the full key once, when
you create it.
</p>
</>
)}
</div>
<Dialog
open={createOpen}
onOpenChange={setCreateOpen}
title={justCreated ? "Copy your key" : "New API key"}
>
{justCreated ? (
<ShownOnce apiKey={justCreated} onDone={() => setCreateOpen(false)} />
) : (
<NameForm onCreate={(name) => void create(name)} creating={creating} />
)}
</Dialog>
<ConfirmDialog
title="Revoke API key"
open={!!revokeTarget}
onClose={() => setRevokeTarget(null)}
onConfirm={() => {
setKeys((all) => all.filter((k) => k.id !== revokeTarget?.id));
setRevokeTarget(null);
toast("Key revoked");
}}
confirmLabel="Revoke key"
danger
>
<p className="text-sm">
Anything using <strong>{revokeTarget?.name}</strong> stops working immediately.
</p>
</ConfirmDialog>
</section>
);
}