Skip to content

ApiKeys

The keys of a project: the publishable one, safe in a browser, and the secret ones, each with a name, what it may do, when it was last used and when it ends. A new secret key is shown once; revoking says what stops working.

import { CopyField, RowActions, ConfirmDialog } from '@sypnia/ui/react'

On this page
  1. On a desktop
  2. On a phone
  3. No secret keys yet
  4. Skeleton
  5. When to use it
  6. For everyone
  7. Props

On a desktop

Create a key (a name already used is refused), save it, then revoke one.

API keys

How your apps and servers prove they may use northwind-shop.

Publishable key

Safe in a browser or a mobile app: it can only do what row-level security allows.

Secret keys

NameScopeLast usedEnds
checkout serversk_live_7Hq2…
Read and write4 minutes agoJan 16, 2027
nightly exportsk_live_c9Lm…
Read15 hours agoDoes not end
migration scriptsk_live_Pw41…
AdminNeverNov 27, 2026
Code
import { useState } from 'react';
import {
  Badge, Button, Callout, Checkbox, ConfirmDialog, CopyField, Dialog, EmptyState, Field, Form, FormActions, InlineCode, Input, Page, PageHeader,
  Panel, RadioCards, RowActions, Select, SkeletonOf, SkeletonWords, Stack, Table, Tag, Text, Toaster, toast, useSypnia, type FormProblem,
} from '@sypnia/ui/react';

// The keys of a project: the publishable one, safe in a browser, and the secret ones, each with a name, what it may
// do, when it was last used and when it ends. A new secret key is shown once; revoking says what stops working.
type Key = { id: string; name: string; prefix: string; scope: 'read' | 'write' | 'admin'; created: number; used: number | null; expires: number | null };
const en = {
  title: 'API keys', lead: 'How your apps and servers prove they may use northwind-shop.', create: 'Create a secret key',
  publishable: 'Publishable key', publishableD: 'Safe in a browser or a mobile app: it can only do what row-level security allows.',
  secret: 'Secret keys', secretD: 'For servers only. Anyone with one can do what its scope allows.', name: 'Name', key: 'Key', scope: 'Scope', lastUsed: 'Last used', ends: 'Ends', never: 'Never', noEnd: 'Does not end',
  scopes: { read: 'Read', write: 'Read and write', admin: 'Admin' },
  scopeOptions: [
    { value: 'read', label: 'Read', description: 'Reads every table. Changes nothing.' },
    { value: 'write', label: 'Read and write', description: 'Reads and changes rows. Cannot change tables or settings.' },
    { value: 'admin', label: 'Admin', description: 'Everything, including tables, keys and settings.' },
  ],
  expiry: 'Ends after', days: (n: number) => `${n} days`, noExpiry: 'Never (not recommended)', nameHint: 'Where it will be used: «checkout server».', noName: 'Give the key a name.',
  taken: 'A key with this name exists. Names tell keys apart: choose another.', creating: 'Creating…',
  saveTitle: 'Save your new key', saveLead: 'Copy it now: this is the only time it is shown in full.', saved: 'I saved the key somewhere safe', done: 'Done',
  revoke: 'Revoke', revokeQ: (n: string) => `Revoke the key «${n}»?`, revokeBody: (n: string) => `Requests signed with «${n}» get 401 from now on. Apps that use it stop working until they get a new key. This cannot be undone.`,
  revoked: (n: string) => `«${n}» was revoked`, actions: (n: string) => `Actions for ${n}`, roll: 'Replace with a new key', rolled: (n: string) => `A new key replaced «${n}». The old one works for 24 more hours.`,
  emptyTitle: 'No secret keys yet', emptyBody: 'Your server needs one to write to northwind-shop. The publishable key above is enough for browsers.',
};
const es: typeof en = {
  title: 'Llaves de API', lead: 'Cómo tus apps y servidores prueban que pueden usar northwind-shop.', create: 'Crear una llave secreta',
  publishable: 'Llave publicable', publishableD: 'Segura en un navegador o una app móvil: solo hace lo que permite la seguridad por fila.',
  secret: 'Llaves secretas', secretD: 'Solo para servidores. Quien tenga una puede hacer lo que permite su alcance.', name: 'Nombre', key: 'Llave', scope: 'Alcance', lastUsed: 'Último uso', ends: 'Vence', never: 'Nunca', noEnd: 'No vence',
  scopes: { read: 'Lectura', write: 'Lectura y escritura', admin: 'Administración' },
  scopeOptions: [
    { value: 'read', label: 'Lectura', description: 'Lee todas las tablas. No cambia nada.' },
    { value: 'write', label: 'Lectura y escritura', description: 'Lee y cambia filas. No cambia tablas ni ajustes.' },
    { value: 'admin', label: 'Administración', description: 'Todo, incluidas tablas, llaves y ajustes.' },
  ],
  expiry: 'Vence después de', days: (n: number) => `${n} días`, noExpiry: 'Nunca (no recomendado)', nameHint: 'Dónde se usará: «servidor de pagos».', noName: 'Ponle un nombre a la llave.',
  taken: 'Ya hay una llave con este nombre. Los nombres distinguen las llaves: elige otro.', creating: 'Creando…',
  saveTitle: 'Guarda tu llave nueva', saveLead: 'Cópiala ahora: es la única vez que se muestra completa.', saved: 'Guardé la llave en un lugar seguro', done: 'Listo',
  revoke: 'Revocar', revokeQ: (n: string) => `¿Revocar la llave «${n}»?`, revokeBody: (n: string) => `Las solicitudes firmadas con «${n}» reciben 401 desde ahora. Las apps que la usan dejan de funcionar hasta que tengan una llave nueva. No se puede deshacer.`,
  revoked: (n: string) => `Se revocó «${n}»`, actions: (n: string) => `Acciones para ${n}`, roll: 'Reemplazar por una llave nueva', rolled: (n: string) => `Una llave nueva reemplazó a «${n}». La anterior funciona 24 horas más.`,
  emptyTitle: 'Aún no hay llaves secretas', emptyBody: 'Tu servidor necesita una para escribir en northwind-shop. Para navegadores basta la llave publicable de arriba.',
};
const day = 86400e3, now = Date.UTC(2026, 10, 17, 15);
const seed: Key[] = [
  { id: 'k1', name: 'checkout server', prefix: 'sk_live_7Hq2', scope: 'write', created: now - 120 * day, used: now - 4 * 60e3, expires: now + 60 * day },
  { id: 'k2', name: 'nightly export', prefix: 'sk_live_c9Lm', scope: 'read', created: now - 300 * day, used: now - 15 * 3600e3, expires: null },
  { id: 'k3', name: 'migration script', prefix: 'sk_live_Pw41', scope: 'admin', created: now - 20 * day, used: null, expires: now + 10 * day },
];
const wait = (ms: number) => new Promise((r) => setTimeout(r, ms));
const random = () => Array.from({ length: 32 }, () => 'abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'[Math.floor(Math.random() * 56)]).join('');

export default function ApiKeys({ state = 'ready' }: { state?: 'ready' | 'loading' | 'empty' }) {
  const { locale, format } = useSypnia();
  const c = locale.startsWith('es') ? es : en;
  const [keys, setKeys] = useState<Key[]>(state === 'empty' ? [] : seed);
  const [creating, setCreating] = useState(false);
  const [problems, setProblems] = useState<FormProblem[]>([]);
  const [secret, setSecret] = useState<string | null>(null);
  const [saved, setSaved] = useState(false);
  const [revoking, setRevoking] = useState<Key | null>(null);
  // Loading: the real page, with only the values as skeletons, as long as the values of the last visit (`seed` here).
  const loading = state === 'loading';
  const create = async (v: FormData) => {
    await wait(900);
    const name = String(v.get('name')).trim();
    if (keys.some((k) => k.name === name)) { setProblems([{ name: 'name', label: c.name, message: c.taken }]); return; }
    const value = `sk_live_${random()}`, days = Number(v.get('expiry'));
    setKeys((l) => [{ id: value, name, prefix: value.slice(0, 12), scope: String(v.get('scope')) as Key['scope'], created: now, used: null, expires: days ? now + days * day : null }, ...l]);
    setCreating(false); setSaved(false); setSecret(value);
  };
  const createButton = <Button variant="primary" icon="key" onClick={() => { setProblems([]); setCreating(true); }}>{c.create}</Button>;
  return (
    <Page>
      <PageHeader title={c.title} lead={c.lead} actions={createButton} />
      <Panel title={c.publishable}>
        <Stack gap={3}><Text size="sm" tone="muted">{c.publishableD}</Text>{loading ? <SkeletonOf><CopyField value="pk_live_northwind_shop_4f9a2c7e1b" label={c.publishable} /></SkeletonOf> : <CopyField value="pk_live_northwind_shop_4f9a2c7e1b" label={c.publishable} />}</Stack>
      </Panel>
      <Panel title={c.secret} flush>
        <Table label={c.secret} rows={loading ? undefined : keys} rowKey={(k) => k.id} loading={loading} loadingRows={seed.length}
          empty={<EmptyState icon="key" compact title={c.emptyTitle} actions={createButton}>{c.emptyBody}</EmptyState>}
          columns={[
            { id: 'name', header: c.name, cell: (k) => <Stack gap={1}><b>{k.name}</b><InlineCode>{k.prefix}…</InlineCode></Stack>,
              skeleton: (i) => <Stack gap={1}><b><SkeletonWords>{seed[i].name}</SkeletonWords></b><SkeletonOf><InlineCode>{seed[i].prefix}…</InlineCode></SkeletonOf></Stack> },
            { id: 'scope', header: c.scope, cell: (k) => (k.scope === 'admin' ? <Badge tone="warn">{c.scopes.admin}</Badge> : <Tag>{c.scopes[k.scope]}</Tag>), skeleton: (i) => <SkeletonOf><Tag>{c.scopes[seed[i].scope]}</Tag></SkeletonOf> },
            { id: 'used', header: c.lastUsed, cell: (k) => (k.used ? format.relative(new Date(k.used), now) : c.never), skeleton: (i) => <SkeletonWords>{seed[i].used ? format.relative(new Date(seed[i].used!), now) : c.never}</SkeletonWords> },
            { id: 'ends', header: c.ends, cell: (k) => (k.expires ? format.date(new Date(k.expires)) : c.noEnd), skeleton: (i) => <SkeletonWords>{seed[i].expires ? format.date(new Date(seed[i].expires!)) : c.noEnd}</SkeletonWords> },
            { id: 'act', header: '', actions: true, skeleton: <SkeletonOf><RowActions label="" actions={[]} /></SkeletonOf>, cell: (k) => <RowActions label={c.actions(k.name)} actions={[
              { id: 'roll', label: c.roll, icon: 'refresh', onAction: () => toast(c.rolled(k.name), { tone: 'ok' }) },
              { id: 'revoke', label: c.revoke, icon: 'ban', danger: true, onAction: () => setRevoking(k) },
            ]} /> },
          ]} />
      </Panel>
      <Dialog open={creating} onClose={() => setCreating(false)} title={c.create}>
        <Form label={c.create} problems={problems} validate={(v) => (String(v.get('name') ?? '').trim() ? [] : [{ name: 'name', label: c.name, message: c.noName }])} onSubmit={create}>
          {({ errorFor }) => (
            <>
              <Field label={c.name} hint={c.nameHint} error={errorFor('name')}><Input name="name" onChange={() => setProblems([])} /></Field>
              <Field label={c.scope}><RadioCards name="scope" options={c.scopeOptions} defaultValue="write" /></Field>
              <Field label={c.expiry}><Select name="expiry" defaultValue="90" options={[...[30, 90, 365].map((n) => ({ value: String(n), label: c.days(n) })), { value: '0', label: c.noExpiry }]} /></Field>
              <FormActions submitLabel={c.create} busyLabel={c.creating} />
            </>
          )}
        </Form>
      </Dialog>
      <Dialog open={secret !== null} onClose={() => saved && setSecret(null)} dismissable={false} dirty={!saved} title={c.saveTitle}
        footer={<Button variant="primary" disabled={!saved} onClick={() => setSecret(null)}>{c.done}</Button>}>
        {secret && <Stack gap={4}><p>{c.saveLead}</p><CopyField value={secret} label={c.key} secret once /><Checkbox label={c.saved} checked={saved} onChange={(e) => setSaved(e.target.checked)} /></Stack>}
      </Dialog>
      <ConfirmDialog open={revoking !== null} title={revoking ? c.revokeQ(revoking.name) : ''} action={c.revoke} confirmWord={revoking?.name} onClose={() => setRevoking(null)}
        onConfirm={() => { setKeys((l) => l.filter((k) => k.id !== revoking!.id)); toast(c.revoked(revoking!.name), { tone: 'ok' }); setRevoking(null); }}>
        <Callout kind="danger">{revoking ? c.revokeBody(revoking.name) : ''}</Callout>
      </ConfirmDialog>
      <Toaster />
    </Page>
  );
}

On a phone

On a phone each key is a card with its actions at the corner.

No secret keys yet

What a secret key is for, and the button to make one.

API keys

How your apps and servers prove they may use northwind-shop.

Publishable key

Safe in a browser or a mobile app: it can only do what row-level security allows.

Secret keys

No secret keys yet

Your server needs one to write to northwind-shop. The publishable key above is enough for browsers.

Skeleton

The real page while the keys load: the publishable key waits in its box, and the table keeps its columns with as many rows as the last visit, each value as long as a real one.

API keys

How your apps and servers prove they may use northwind-shop.

Publishable key

Safe in a browser or a mobile app: it can only do what row-level security allows.

Secret keys

NameScopeLast usedEnds

When to use it

Use it when

  • Every project that apps or servers call.
  • Showing the last use of each key, so old keys can be revoked with confidence.

Do not use it when

  • Showing a secret key again after it was made.
  • Keys without a name or without an end: ask for a name, and suggest an end.

For everyone

  • Each key's actions are one button named with the key.
  • Revoking asks to type the key's name and says which apps stop working.
  • The new key's dialog cannot close until the person says it is saved.

Props

CopyFieldTypeDefault
valuerequired string
label string
once boolean
secret boolean
RowActionsTypeDefault
actionsrequired RowAction[]
label

The name of the button, saying which row it belongs to: «Actions for order 1042».

string
ConfirmDialogTypeDefault
actionrequired

The confirm button says exactly what it does: «Delete table», never «OK».

string
onCloserequired () => void
onConfirmrequired () => void
titlerequired

The question, naming the thing: «Delete the table orders?»

ReactNode
busy boolean
children

What will happen, in plain words, and whether it can be undone.

ReactNode
confirmWord

For the most destructive actions: the person must type this word (usually the name of the thing) to enable the button.

string
open boolean true
tone

danger: it cannot be undone. primary: it can, but it matters.

"primary" | "danger" danger
  1. On a desktop
  2. On a phone
  3. No secret keys yet
  4. Skeleton
  5. When to use it
  6. For everyone
  7. Props

    Search pages, sections and terms