Blocks Design System

API keys

A workspace’s API keys in a Table: each row shows the name, a masked key in Code, its scopes as Badges and when it was last used, with a Menu to copy the prefix, roll the secret or revoke the key. “Create key” opens a Modal with a name Field and scope Checkboxes, then shows the full key once with a copy button and a warning.

API keys

Keys act as your workspace. Give each one only the scopes it needs.

NameKeyScopesLast usedActions
Production serverCreated Aug 14, 2026
lk_7Hq2 (rest hidden)
items:readitems:write
4 min ago
Nightly exportCreated Sep 2, 2026
lk_Rb9x (rest hidden)
items:read
Yesterday
Billing dashboardCreated Oct 21, 2026
lk_m3Pz (rest hidden)
billing:read
Never
  • Production serverCreated Aug 14, 2026 · Last used 4 min ago
    lk_7Hq2 (rest hidden)
    items:readitems:write
  • Nightly exportCreated Sep 2, 2026 · Last used yesterday
    lk_Rb9x (rest hidden)
    items:read
  • Billing dashboardCreated Oct 21, 2026 · Never used
    lk_m3Pz (rest hidden)
    billing:read
Source · recipes/api-keys.tsx
recipes/api-keys.tsx
'use client'

import {
  Badge,
  Body,
  BodySmall,
  Box,
  Button,
  Checkbox,
  Code,
  Field,
  Heading,
  Menu,
  Modal,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableHeader,
  TableRow,
  Text,
  toastError,
  toastSuccess,
} from '@blocks/design-system'
import { Copy, Ellipsis, Plus, TriangleAlert } from 'lucide-react'
import { type FormEvent, useId, useRef, useState } from 'react'
import styles from './api-keys.module.css'

const scopes = [
  { id: 'items:read', description: 'List and read projects and items' },
  { id: 'items:write', description: 'Create, edit and archive items' },
  { id: 'webhooks:write', description: 'Register and remove webhooks' },
  { id: 'billing:read', description: 'Read invoices and usage' },
]

interface ApiKey {
  id: string
  name: string
  prefix: string
  scopes: string[]
  created: string
  lastUsed: string
}

const initialKeys: ApiKey[] = [
  {
    id: 'key_1',
    name: 'Production server',
    prefix: 'lk_7Hq2',
    scopes: ['items:read', 'items:write'],
    created: 'Aug 14, 2026',
    lastUsed: '4 min ago',
  },
  {
    id: 'key_2',
    name: 'Nightly export',
    prefix: 'lk_Rb9x',
    scopes: ['items:read'],
    created: 'Sep 2, 2026',
    lastUsed: 'Yesterday',
  },
  {
    id: 'key_3',
    name: 'Billing dashboard',
    prefix: 'lk_m3Pz',
    scopes: ['billing:read'],
    created: 'Oct 21, 2026',
    lastUsed: 'Never',
  },
]

// Secrets are made in event handlers only, never during render.
function generateSecret() {
  const alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789'
  const bytes = crypto.getRandomValues(new Uint8Array(32))
  return `lk_${Array.from(bytes, (byte) => alphabet[byte % alphabet.length]).join('')}`
}

// The secret's first characters identify a key; the rest is never shown again.
const prefixOf = (secret: string) => secret.slice(0, 7)

async function copy(text: string, label: string) {
  try {
    await navigator.clipboard.writeText(text)
    toastSuccess(`${label} copied`)
  } catch {
    toastError('Couldn’t copy. Select the text and copy it instead.')
  }
}

function MaskedKey({ prefix }: { prefix: string }) {
  return (
    <Code dangerouslySetClassName={styles.masked}>
      {prefix}
      <span aria-hidden>••••</span>
      <span className={styles.visuallyHidden}> (rest hidden)</span>
    </Code>
  )
}

function ScopeBadges({ scopes }: { scopes: string[] }) {
  return (
    <Box display="flex" flexWrap="wrap" gap="xs" dangerouslySetClassName={styles.badges}>
      {scopes.map((scope) => (
        <Badge key={scope} tone={scope.endsWith(':write') ? 'warning' : 'neutral'}>
          {scope}
        </Badge>
      ))}
    </Box>
  )
}

// Revealed once: after "Create key" or "Roll", the full secret is shown in
// this dialog and never again.
interface Reveal {
  name: string
  secret: string
  rolled: boolean
}

export default function ApiKeys() {
  const titleId = useId()
  const scopesLabelId = useId()
  const scopesErrorId = useId()
  const nameInput = useRef<HTMLInputElement>(null)
  const title = useRef<HTMLHeadingElement>(null)
  const [keys, setKeys] = useState(initialKeys)
  const [creating, setCreating] = useState(false)
  const [draftName, setDraftName] = useState('')
  const [chosenScopes, setChosenScopes] = useState<string[]>(['items:read'])
  // Errors appear on submit, then follow the fields as they're fixed.
  const [showErrors, setShowErrors] = useState(false)
  const errors = {
    name: showErrors && !draftName.trim() ? 'Name the key after what uses it.' : undefined,
    scopes: showErrors && chosenScopes.length === 0 ? 'Choose at least one scope.' : undefined,
  }
  // Each dialog keeps its data after closing so it doesn't go blank while it animates out.
  const [reveal, setReveal] = useState<Reveal | null>(null)
  const [revealOpen, setRevealOpen] = useState(false)
  const [revokeTarget, setRevokeTarget] = useState<ApiKey | null>(null)
  const [revokeOpen, setRevokeOpen] = useState(false)

  function openCreate(open: boolean) {
    if (open) {
      setDraftName('')
      setChosenScopes(['items:read'])
      setShowErrors(false)
    }
    setCreating(open)
  }

  function create(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    if (!creating) return
    const name = draftName.trim()
    if (!name || chosenScopes.length === 0) {
      setShowErrors(true)
      if (!name) nameInput.current?.focus()
      return
    }

    const secret = generateSecret()
    setKeys((current) => [
      {
        id: `key_${secret.slice(-8)}`,
        name,
        prefix: prefixOf(secret),
        scopes: chosenScopes,
        created: 'today',
        lastUsed: 'Never',
      },
      ...current,
    ])
    setCreating(false)
    setReveal({ name, secret, rolled: false })
    setRevealOpen(true)
  }

  function roll(key: ApiKey) {
    const secret = generateSecret()
    setKeys((current) =>
      current.map((item) => (item.id === key.id ? { ...item, prefix: prefixOf(secret), lastUsed: 'Never' } : item)),
    )
    setReveal({ name: key.name, secret, rolled: true })
    setRevealOpen(true)
  }

  function confirmRevoke(key: ApiKey) {
    setRevokeTarget(key)
    setRevokeOpen(true)
  }

  function revoke() {
    if (!revokeTarget || !revokeOpen) return
    setKeys((current) => current.filter((item) => item.id !== revokeTarget.id))
    toastSuccess(`Revoked “${revokeTarget.name}”`, { description: 'Requests using it now fail with 401.' })
    setRevokeOpen(false)
  }

  const emptyMessage = 'No active keys. Create one to call the API.'

  // The same row menu serves the table and the cards.
  function actionsFor(key: ApiKey) {
    return (
      <Menu>
        <Menu.Trigger
          render={<Button type="button" variant="ghost" size="sm" aria-label={`Actions for ${key.name}`} />}
        >
          <Ellipsis aria-hidden size={16} />
        </Menu.Trigger>
        <Menu.Content align="end">
          <Menu.Item onClick={() => copy(key.prefix, 'Key prefix')}>Copy prefix</Menu.Item>
          <Menu.Item onClick={() => roll(key)}>Roll key…</Menu.Item>
          <Menu.Separator />
          <Menu.Item onClick={() => confirmRevoke(key)}>Revoke…</Menu.Item>
        </Menu.Content>
      </Menu>
    )
  }

  return (
    <Stack as="section" gap="lg" aria-labelledby={titleId} dangerouslySetClassName={styles.keys}>
      <Stack direction="row" justify="space-between" align="end" gap="md" wrap="wrap">
        <Stack gap="xs">
          <Heading as="h3" id={titleId} ref={title} tabIndex={-1} fontSize="lg" margin="none">
            API keys
          </Heading>
          <BodySmall color="text-muted" margin="none">
            Keys act as your workspace. Give each one only the scopes it needs.
          </BodySmall>
        </Stack>

        <Modal open={creating} onOpenChange={openCreate}>
          <Modal.Trigger render={<Button type="button" variant="primary" />}>
            <Plus aria-hidden size={16} />
            Create key
          </Modal.Trigger>
          <Modal.Content initialFocus={nameInput}>
            <Modal.Header>Create API key</Modal.Header>
            <form noValidate onSubmit={create}>
              <Stack gap="lg" padding="lg">
                <Field name="name" invalid={Boolean(errors.name)}>
                  <Field.Label>Name</Field.Label>
                  <Field.Control
                    ref={nameInput}
                    placeholder="Staging server"
                    maxLength={40}
                    autoComplete="off"
                    value={draftName}
                    onValueChange={setDraftName}
                  />
                  <Field.Description>Only you and other admins see this.</Field.Description>
                  {errors.name && <Field.Error match>{errors.name}</Field.Error>}
                </Field>
                <Stack
                  gap="sm"
                  role="group"
                  aria-labelledby={scopesLabelId}
                  aria-describedby={errors.scopes ? scopesErrorId : undefined}
                >
                  <Text id={scopesLabelId} fontSize="sm" fontWeight="semibold">
                    Scopes
                  </Text>
                  {scopes.map((scope) => (
                    <Checkbox
                      key={scope.id}
                      checked={chosenScopes.includes(scope.id)}
                      onCheckedChange={(checked) =>
                        setChosenScopes((current) =>
                          checked ? [...current, scope.id] : current.filter((id) => id !== scope.id),
                        )
                      }
                    >
                      <span>
                        <Code>{scope.id}</Code> <span className={styles.muted}>{scope.description}</span>
                      </span>
                    </Checkbox>
                  ))}
                  {errors.scopes && (
                    <BodySmall id={scopesErrorId} color="danger-text" margin="none">
                      {errors.scopes}
                    </BodySmall>
                  )}
                </Stack>
              </Stack>
              <Modal.Footer>
                <Modal.Close render={<Button type="button" variant="ghost" />}>Cancel</Modal.Close>
                <Button type="submit" variant="primary">
                  Create key
                </Button>
              </Modal.Footer>
            </form>
          </Modal.Content>
        </Modal>
      </Stack>

      {/* One set of keys, two layouts: a table when there's room, cards on a phone. */}
      <TableContainer tabIndex={0} role="region" aria-labelledby={titleId} dangerouslySetClassName={styles.region}>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead scope="col">Name</TableHead>
              <TableHead scope="col">Key</TableHead>
              <TableHead scope="col">Scopes</TableHead>
              <TableHead scope="col">Last used</TableHead>
              <TableHead scope="col">
                <span className={styles.visuallyHidden}>Actions</span>
              </TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {keys.length === 0 && (
              <TableRow>
                <TableCell colSpan={5}>
                  <Body color="text-muted" margin="none">
                    {emptyMessage}
                  </Body>
                </TableCell>
              </TableRow>
            )}
            {keys.map((key) => (
              <TableRow key={key.id}>
                <TableHead scope="row">
                  <Stack gap="none">
                    <Text fontSize="sm" fontWeight="semibold" color="text">
                      {key.name}
                    </Text>
                    <Text fontSize="xs" color="text-muted" fontWeight="body">
                      Created {key.created}
                    </Text>
                  </Stack>
                </TableHead>
                <TableCell>
                  <MaskedKey prefix={key.prefix} />
                </TableCell>
                <TableCell>
                  <ScopeBadges scopes={key.scopes} />
                </TableCell>
                <TableCell dangerouslySetClassName={styles.nowrap}>{key.lastUsed}</TableCell>
                <TableCell>{actionsFor(key)}</TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </TableContainer>

      <ul className={styles.cards} aria-labelledby={titleId}>
        {keys.length === 0 && (
          <li>
            <Body color="text-muted" margin="none">
              {emptyMessage}
            </Body>
          </li>
        )}
        {keys.map((key) => (
          <li key={key.id} className={styles.card}>
            <div className={styles.cardHeader}>
              <Stack gap="none">
                <Text fontSize="sm" fontWeight="semibold">
                  {key.name}
                </Text>
                <Text fontSize="xs" color="text-muted">
                  Created {key.created} ·{' '}
                  <span className={styles.nowrap}>
                    {key.lastUsed === 'Never' ? 'Never used' : `Last used ${key.lastUsed.toLowerCase()}`}
                  </span>
                </Text>
              </Stack>
              {actionsFor(key)}
            </div>
            <MaskedKey prefix={key.prefix} />
            <ScopeBadges scopes={key.scopes} />
          </li>
        ))}
      </ul>

      {/* Shown once: the full secret for a created or rolled key. */}
      <Modal open={revealOpen} onOpenChange={setRevealOpen}>
        <Modal.Content showCloseButton={false}>
          <Modal.Header>
            {reveal?.rolled ? `New secret for “${reveal.name}”` : `“${reveal?.name}” is ready`}
          </Modal.Header>
          <Modal.Body>
            <Stack gap="md">
              <div className={styles.warning}>
                <TriangleAlert aria-hidden size={16} />
                <span>
                  Copy this key now. You won’t be able to see it again.
                  {reveal?.rolled && ' The old secret stops working in 24 hours.'}
                </span>
              </div>
              <div className={styles.secret}>
                <Code dangerouslySetClassName={styles.secretText}>{reveal?.secret}</Code>
                <Button type="button" size="sm" onClick={() => reveal && copy(reveal.secret, 'API key')}>
                  <Copy aria-hidden size={14} />
                  Copy
                </Button>
              </div>
            </Stack>
          </Modal.Body>
          <Modal.Footer>
            <Modal.Close render={<Button type="button" variant="primary" />}>I’ve saved it</Modal.Close>
          </Modal.Footer>
        </Modal.Content>
      </Modal>

      <Modal open={revokeOpen} onOpenChange={setRevokeOpen}>
        {/* A revoked key's menu button is gone, so focus falls back to the heading. */}
        <Modal.Content finalFocus={() => keys.some((key) => key.id === revokeTarget?.id) || title.current}>
          <Modal.Header>Revoke “{revokeTarget?.name}”?</Modal.Header>
          <Modal.Body>
            Anything using <Code>{revokeTarget?.prefix}…</Code> stops working immediately. This can’t be undone.
          </Modal.Body>
          <Modal.Footer>
            <Modal.Close render={<Button type="button" variant="ghost" />}>Cancel</Modal.Close>
            <Button type="button" variant="primary" onClick={revoke}>
              Revoke key
            </Button>
          </Modal.Footer>
        </Modal.Content>
      </Modal>
    </Stack>
  )
}
API keys

How it works

  • The secret appears once. Creating or rolling a key generates the secret in the event handler, never during render, and shows it in its own dialog. The table keeps only the prefix.
  • Destructive actions confirm. Revoke opens a confirmation dialog that names the key. When the key is revoked its row and menu button disappear, so the dialog’s finalFocus sends focus to the section’s heading instead; Cancel returns focus to the menu button as usual.
  • Dialogs don’t go blank while closing. Each dialog’s open state is separate from its data, so its content stays put while it animates out.
  • Scopes read without color. Write scopes are tinted, but the scope names say what they allow. The masked key keeps its dots out of the accessibility tree and says “rest hidden” instead.
  • One list, two layouts. Below about 480px a container query swaps the table for a list of cards, each with the name, dates, masked key and scopes, and its actions Menu always in view. Both layouts share the same menu and badge components.
  • Copy can fail. navigator.clipboard is awaited, and a failure says how to copy by hand.

App-owned CSS

The phone cards, the masked key, the warning and the one-time secret panel.

recipes/api-keys.module.css
/* The table and its phone cards, masked keys and the one-time secret panel. */

.keys {
  container-type: inline-size;
}

/* Contains the visually hidden text in its cells, so it scrolls with them. */
.region {
  position: relative;
}

/* Scope badges stay on one line in the table. */
.region .badges {
  flex-wrap: nowrap;
}

.masked {
  padding-right: var(--ds-space-sm);
  white-space: nowrap;
}

.cards {
  display: none;
  gap: var(--ds-space-sm);
  margin: 0;
  padding: 0;
  list-style: none;
}

.card {
  display: grid;
  gap: var(--ds-space-sm);
  padding: var(--ds-space-md) var(--ds-space-lg);
  border: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);
  border-radius: var(--ds-border-radius-md);
}

.cardHeader {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: var(--ds-space-md);
}

/* Below about 480px each key becomes a card, with its actions always in view. */
@container (max-width: 30rem) {
  .region {
    display: none;
  }

  .cards {
    display: grid;
  }
}

.nowrap {
  white-space: nowrap;
}

.muted {
  color: var(--ds-color-text-muted);
}

.visuallyHidden {
  position: absolute;
  width: 1px;
  height: 1px;
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
}

.warning {
  display: flex;
  align-items: flex-start;
  gap: var(--ds-space-md);
  padding: var(--ds-space-md) var(--ds-space-lg);
  font-size: var(--ds-font-size-sm);
  color: var(--ds-color-warning-text);
  background: var(--ds-color-warning-subtle);
  border-radius: var(--ds-border-radius-md);

  & svg {
    flex: none;
    margin-top: var(--ds-space-xs);
  }
}

.secret {
  display: flex;
  align-items: center;
  gap: var(--ds-space-md);
  padding: var(--ds-space-sm) var(--ds-space-sm) var(--ds-space-sm) var(--ds-space-lg);
  background: var(--ds-color-bg-subtle);
  border: var(--ds-border-width-sm) solid var(--ds-color-border);
  border-radius: var(--ds-border-radius-md);
}

/* The full key wraps anywhere rather than widening the dialog. */
.secretText {
  flex: 1;
  min-width: 0;
  overflow-wrap: anywhere;
  user-select: all;
}