# API keys

> The API keys screen, done properly: the secret rises in once, and Done folds it down into the "sk_live_••••4f2a" it leaves behind.

Most API key screens open a modal for the name, flash the secret in a box with a copy icon, then drop a new row into a table somewhere else. Here "Create key" opens a row at the top of the list and the rows below glide down. That row becomes the key: its secret rises in character by character under the name, with Copy and Done. Done folds the secret away, and its prefix and last four characters fly up into the key's chip while the rest blurs out, so the masked key is visibly what's left of the one you just saw. Rolling a key lifts its chip away and opens the new secret in the same row; if your server keeps the old key alive for a while, it sits underneath counting down to its expiry. Revoking stretches the bin's own circle into "Revoke": a check draws, then the row folds away. Keys are plain records, and every change is one async function that returns what your server stored.

## Install

```bash
npx shadcn@latest add @hairline/api-keys
```

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

- npm: `lucide-react`
- Hairline UI components it needs (the CLI installs them too): `text-morph`, `number-roll`, `status-button`
- Docs and live preview: https://hairlineui.com/ui/api-keys
- Registry item (source): https://hairlineui.com/r/api-keys.json

## Usage

```tsx
import { ApiKeys } from "@/components/api-keys";

<ApiKeys
  defaultValue={keys}
  scopes={[{ value: "read", label: "Read" }, { value: "write", label: "Write" }]}
  onCreate={async ({ name, scopes }) => {
    const res = await fetch("/api/keys", { method: "POST", body: JSON.stringify({ name, scopes }) });
    if (!res.ok) throw new Error((await res.json()).error);
    return res.json(); // { key, secret }
  }}
  onRevoke={(key) => fetch(`/api/keys/${key.id}`, { method: "DELETE" })}
/>
```

## Keys stored hashed in your database

The secret is made on your server, returned once and stored only as a SHA-256 hash, with its prefix and last four kept for the chip. Requests are checked by hashing the presented key and looking the hash up. The same shape works with Unkey: return its key id, start and the key it gives you.

```tsx
// app/api/keys/route.ts
import { randomBytes, createHash } from "node:crypto";
import { db } from "@/lib/db";

const hash = (secret: string) => createHash("sha256").update(secret).digest("hex");

export async function POST(req: Request) {
  const user = await requireUser(req);
  const { name, scopes } = await req.json();
  const secret = "sk_live_" + randomBytes(24).toString("base64url");
  const key = await db.apiKey.create({
    data: { userId: user.id, name, scopes, prefix: "sk_live_", last4: secret.slice(-4), hash: hash(secret) },
    select: { id: true, name: true, prefix: true, last4: true, scopes: true, createdAt: true, lastUsedAt: true },
  });
  return Response.json({ key, secret });
}

// app/settings/api-keys.tsx
"use client";
import { ApiKeys, type ApiKey } from "@/components/api-keys";

export function ApiKeysSettings({ initial }: { initial: ApiKey[] }) {
  return (
    <ApiKeys
      defaultValue={initial}
      scopes={[{ value: "read", label: "Read" }, { value: "write", label: "Write" }]}
      onCreate={async (input) => {
        const res = await fetch("/api/keys", { method: "POST", body: JSON.stringify(input) });
        if (!res.ok) throw new Error("The key couldn't be created.");
        return res.json();
      }}
      onRoll={async (key) => {
        const res = await fetch(`/api/keys/${key.id}/roll`, { method: "POST" });
        if (!res.ok) throw new Error();
        return res.json(); // { key, secret, previous: { ...old, expiresAt } }
      }}
      onRevoke={async (key) => {
        const res = await fetch(`/api/keys/${key.id}`, { method: "DELETE" });
        if (!res.ok) throw new Error();
      }}
    />
  );
}
```

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value` | `ApiKey[]` | – | Controlled keys: { id, name, prefix?, last4, scopes?, createdAt?, lastUsedAt?, expiresAt? }. Never the secret. |
| `defaultValue` | `ApiKey[]` | – | Starting keys when uncontrolled. |
| `onValueChange` | `(keys: ApiKey[]) => void` | – | The list after every create, roll and revoke, newest first. |
| `onCreate` | `({ name, scopes }) => Promise<{ key, secret }>` | – | Creates a key. Return it with the whole secret, which is shown once; throw to keep the form and show the error's message. |
| `onRoll` | `(key) => Promise<{ key, secret, previous? }>` | – | Issues a new secret. Return previous (the old key with expiresAt) to keep it listed while it still works. Without onRoll there is no roll button. |
| `onRevoke` | `(key) => Promise<unknown>` | – | Revokes a key; the row leaves once it resolves. Throw to show Try again. Without it there is no bin. |
| `scopes` | `{ value, label }[]` | – | What a key may do; the form shows them as toggles and asks for at least one. |
| `defaultScopes` | `string[]` | – | Scopes a new key starts with. All of them by default. |
| `title` | `string` | `"API keys"` | Heading and the list's accessible name. |
| `description` | `string` | – | The line under the heading. |
| `placeholder` | `string` | `"e.g. Production server"` | The name field's placeholder. |

## States

- **create**: "Create key" opens a form row at the top of the list; it fades in from a blur while the rows below glide down 480ms. Escape or Cancel folds it away. A missing name or scope shakes the field and says why under it.
- **creating**: Create key turns into "Creating" with a spinner while onCreate runs. If it throws, the form keeps the name and scopes, the button says Try again and the error lifts in under the form.
- **reveal**: The form fades out over the key it became while the row eases to its new height in 460ms. The secret rises in under the name, each character out of a 4px blur, the whole of it inside half a second. Copy takes focus; it turns into Copied with a drawn check.
- **seal**: Done closes the fold in 460ms. The secret's prefix and last four characters fly into the chip together, as words (540ms), the dots rise in between them and the chip's hairline fades in behind; everything else blurs out. The secret then leaves the page.
- **roll**: The roll icon stretches into "Roll key". Once onRoll resolves, the chip lifts away through a blur and the new secret opens in the same row. If onRoll returns the old key with expiresAt, it fades in underneath as "Expires in 23:59:41", its numbers rolling down a second at a time.
- **revoke**: The bin's circle stretches into a red "Revoke"; it spins, a check draws and the row dims for 700ms, then folds away while the rows below glide up. A failure shakes the button and says Try again.
- **last used**: "Last used 2 min ago" rolls its number and morphs its unit as time passes, re-rendering only when the words change.

## What it handles

The usual API keys screen shows a secret once in a box, hopes you copied it, and leaves the rest to you: scopes, rolling, revoking and expiry. This is the whole screen, working against your own backend.

- **The secret is shown once**: It appears under the name with a Copy button. Done folds it away and the secret leaves the page.
- **What is left is a masked key**: The prefix and last four characters fly into the key’s chip, so it reads like sk_live_••••4f2a.
- **Scopes when you create**: The form shows what a key may do as toggles and asks for at least one.
- **Rolling without a gap**: The new secret opens in the same row, and the old key can stay listed, counting down to its expiry.
- **Revoking asks first**: The bin stretches into “Revoke”, a check draws, then the row folds away. A failure says Try again.
- **Errors keep your input**: If creating fails, the form keeps the name and scopes and shows the server’s message.

## Replaces

a create-key modal, a copy-once secret box, a keys table, a revoke confirmation, a key rotation flow

## Where it fits

- **Developer dashboards**: The Settings → API keys page of any product that has an API.
- **Scoped keys**: Let people choose what a key may do before it is created.
- **Personal access tokens**: A page where each person creates and revokes their own tokens.
- **Internal platforms**: Keys per service or environment, such as “Production server”.

## Notes

- The secret only ever lives in the component's state while it is on screen; it leaves the page once Done has folded it away. Store a hash on your server, never the key.
- The new key's Copy button takes focus as the secret opens; Done hands focus back to "Create key". Creating, rolling, revoking and hiding the secret are announced in a status region outside the list.
- Roll and Revoke ask first: the icon becomes a cross and the confirm button opens beside it. Escape, the cross, or a click or focus elsewhere takes the question back.
- The expiry countdown is hidden from screen readers (it would re-announce every second); they hear the time the key expires instead.
- Rows glide with additive transforms measured from layout offsets, and a revoked row folds away as its own detached element, so nothing re-renders for it.
- Reduced motion opens, seals and removes in place; the chip and the secret simply swap.

License: MIT (https://hairlineui.com/license#components)
