---
title: UI components
crumb: UI components
eyebrow: Reference · @clearedby/react
h1: An approval UI that looks like your product.
description: The @clearedby/react reference: every component and its props, every hook with its signature and return shape, the full theme schema, importers and CLI, classNames slots, labels keys, component injection, the partner proxy, and recipes for Next.js, Express, Tailwind/shadcn, a custom UI and webhook-driven refresh.
lede: A review queue, a plain-English review panel, the decision buttons a person is allowed to press, "Your approval rules" and history, in React. The browser only talks to your server (the partner proxy), and everything from colours to wording to the buttons themselves can be yours.
pills: @clearedby/react 0.1.0, React 18+, @clearedby/sdk/partner-proxy
---

# UI components

## How it fits together {#architecture}

There are two halves, and the partner key never reaches the browser:

- **Server:** `createPartnerProxy()` from `@clearedby/sdk/partner-proxy`, mounted at one catch-all route in your app (default `/api/clearedby`). It works out who is asking from **your** session, mints short-lived ClearedBy tokens for exactly that person, calls ClearedBy, strips anything credential-like and answers. See [the proxy](#proxy).
- **Browser:** `@clearedby/react`. `<ClearedByProvider basePath="/api/clearedby">` plus the components or hooks. It calls only your proxy, with same-origin cookies.

```bash title="terminal"
npm install @clearedby/react @clearedby/sdk
```

```tsx title="app/approvals.tsx"
'use client'
import { useState } from 'react'
import { ClearedByProvider, ApprovalQueue, ReviewPanel } from '@clearedby/react'
import '@clearedby/react/styles.css'          // optional: the default look (only cb-* classes, no globals)

export function Approvals() {
  const [id, setId] = useState<string | null>(null)
  return (
    <ClearedByProvider basePath="/api/clearedby">
      <ApprovalQueue selectedId={id} onSelect={(item) => setId(item.id)} />
      {id && <ReviewPanel id={id} />}          {/* includes DecisionBar, CancelButton and History */}
    </ClearedByProvider>
  )
}
```

The [quickstart](/docs/partners/quickstart#proxy) wires this up end to end. A runnable Next.js app is in [`examples/partner-approvals-next`](https://github.com/ClearedBy/clearedby-js/tree/main/examples/partner-approvals-next).

Open views refresh every 15 s while the tab is visible, pause while it is hidden, refresh as soon as it is visible again and back off (up to 5 minutes) after errors. The components are keyboard-accessible (arrow keys move through the queue; Enter or Space opens an item) and announce status changes.

## ClearedByProvider {#provider}

Wrap every component and hook in one provider. It holds the client, a per-provider cache, the labels, the theme and your component overrides.

| Prop | Type | Default | What it does |
| --- | --- | --- | --- |
| `basePath` | `string` | `'/api/clearedby'` | Where your partner proxy is mounted. |
| `labels` | `LabelOverrides` | | Replace any wording (see [labels](#labels)). |
| `pollInterval` | `number` (ms) | `15000` | Refresh interval for open views. `0` turns polling off (drive it with `useRevalidate`). |
| `locale` | `string` | the browser's | Locale for dates and money. |
| `fetch` | `typeof fetch` | global `fetch` | A custom fetch (tests, extra headers). |
| `theme` | `ClearedByTheme` | | Design tokens, applied on top of the stored theme, token by token. |
| `fetchTheme` | `boolean` | `true` | Fetch the stored theme from `${basePath}/theme`. |
| `colorScheme` | `'auto' \| 'class' \| 'light' \| 'dark'` | `'auto'` | Dark mode: the OS setting, a `.dark` ancestor (shadcn/Tailwind), or forced. |
| `classNames` | `Partial<ClassNames>` | | Extra classes per part, for every component (see [slots](#classnames)). |
| `unstyled` | `boolean` | `false` | Drop every default `cb-*` class everywhere. |
| `components` | `Partial<UiComponents>` | | Your `Button`, `Input`, `Textarea`, `Select`, `Badge`, `Dialog` (see [injection](#components-injection)). |
| `children` | `ReactNode` | | |

## Components {#components}

Every component also accepts the **style props**: `className` (extra class on its root), `classNames` (per-part classes, merged with the provider's) and `unstyled` (overrides the provider's). Every component takes `labels` to override wording for that component only.

### ApprovalQueue {#approvalqueue}

The signed-in reviewer's list of things waiting for them, newest first, with "Show more" paging. Up/Down arrows move between cards; Enter or Space opens one.

| Prop | Type | Default | What it does |
| --- | --- | --- | --- |
| `status` | `ItemStatus \| ItemStatus[]` | `['pending', 'escalated']` | Which statuses to show. For a history tab: `['cleared', 'rejected', 'sent_back', 'expired', 'revoked']`. |
| `filter` | `{ actionPrefix?: string; batchId?: string }` | | Only some actions, or one batch. |
| `limit` | `number` | `25` | Page size, 1 to 100. |
| `onSelect` | `(item: Approval) => void` | | A card was chosen. |
| `selectedId` | `string \| null` | | Highlights that card. |
| `title` | `ReactNode \| false` | "Waiting for your OK" | Heading; `false` hides it. |
| `renderItem` | `(item: Approval, selected: boolean) => ReactNode` | | Render your own card instead of `ApprovalCard`. |
| `labels` | `LabelOverrides` | | |

### ApprovalCard {#approvalcard}

One queue entry as a button: what the assistant wants to do in a sentence, its status, and meta (two-person approval progress, sent to you, when it lapses).

| Prop | Type | What it does |
| --- | --- | --- |
| `item` | `Approval` | The clearance (from the queue). |
| `selected` | `boolean` | Selected styling (`cardSelected`). |
| `onSelect` | `(item: Approval) => void` | Clicked. |
| `labels` | `LabelOverrides` | |

### ReviewPanel {#reviewpanel}

Everything a reviewer needs to decide one item: the change in plain English, a paged before/after table for batches, the evidence grouped by who vouches for it, the buttons they may press, "Cancel before it runs" on approved items, and the history.

| Prop | Type | Default | What it does |
| --- | --- | --- | --- |
| `id` | `string` | required | The clearance id. |
| `showDecisionBar` | `boolean` | `true` | Decision buttons on open items. |
| `showCancel` | `boolean` | `true` | "Cancel before it runs" on approved, not-yet-done items. |
| `showHistory` | `boolean` | `true` | The timeline. |
| `escalateTo` | `string` | | Hand escalations to this `external_subject`. Default: the most senior reviewer who can cover it. |
| `onDecided` | `(result: DecideResult, decision: Decision) => void` | | After a decision is recorded. |
| `pageSize` | `number` | `50` | Rows per page in the changes table. |
| `labels` | `LabelOverrides` | | |

### DecisionBar {#decisionbar}

Only the buttons this person may press, from ClearedBy's own permission check (`can`). Decline and send back ask for a note of at least 4 characters first; escalate takes an optional note. Shows a short message after deciding ("Approved.", "Thanks. One more person needs to approve this.").

| Prop | Type | What it does |
| --- | --- | --- |
| `id` | `string` | The clearance id. |
| `escalateTo` | `string` | Hand escalations to this `external_subject`. |
| `onDecided` | `(result: DecideResult, decision: Decision) => void` | After a decision is recorded. |
| `labels` | `LabelOverrides` | |

### ChangesTable {#changestable}

The before/after table for a batch (`params.changes[]`), paged so a 3,000-product batch stays quick, with a summary line on top. Used inside `ReviewPanel`.

| Prop | Type | Default | What it does |
| --- | --- | --- | --- |
| `item` | `Pick<Approval, 'action' \| 'params'>` | required | The clearance. |
| `pageSize` | `number` | `50` | Rows per page. |
| `labels` | `LabelOverrides` | | |

### EvidenceList {#evidencelist}

The evidence grouped and badged by provenance: **Verified by** your name (`partner_verified`), **Checked automatically** (`clearedby_computed`), then **Agent says** (`agent_claim`), with a warning when an item's `integrity` is `mismatch`. Used inside `ReviewPanel`.

| Prop | Type | What it does |
| --- | --- | --- |
| `evidence` | `{ claims: EvidenceItem[]; verified: EvidenceItem[] } \| undefined` | The clearance's `evidence`. |
| `currency` | `string` | The item's currency, for money figures in automatic checks. |
| `labels` | `LabelOverrides` | |

`groupEvidence(evidence, labels)` returns the same grouping as data (`EvidenceGroup[]`: `key`, `kind` of `'verified' | 'computed' | 'agent'`, `badge`, `items`) for your own rendering.

### RulesSummary {#rulessummary}

"Your approval rules": one plain-English line per setting, **Looks good** and **Adjust**. Adjusting shows simple controls (amounts in the org currency, spot-checks with "How often"). A stricter change is saved at once. A looser change is confirmed by an owner or admin in place (in your `Dialog`, if you provide one), or shows "Your store owner needs to approve this change." A waiting proposal is shown to owners and admins with **Yes, change it**.

| Prop | Type | What it does |
| --- | --- | --- |
| `onLooksGood` | `() => void` | The merchant tapped "Looks good" (the rules are already on; nothing is sent). |
| `onChanged` | `() => void` | A change is live (saved stricter, or accepted). |
| `labels` | `LabelOverrides` | |

Who may edit and accept comes from the proxy: the `viewer` it adds to `GET /rules` (`role`, `can_edit`, `can_accept`), from your `canEditRules` option and the reviewer's role.

### History {#history}

The item's story, oldest first, across revisions: asked, sent back and revised, approved, carried out, cancelled or undone. Technical steps are left out.

| Prop | Type | What it does |
| --- | --- | --- |
| `id` | `string` | The clearance id. |
| `title` | `string \| false` | Heading; `false` hides it. |
| `labels` | `LabelOverrides` | |

### CancelButton {#cancelbutton}

"Cancel before it runs" on an approved change that hasn't been reported done or failed. Renders nothing otherwise. Asks why (4+ characters) and confirms in your `Dialog` if you provide one. ClearedBy decides whether this person may (owners and admins, or anyone who could approve it).

| Prop | Type | What it does |
| --- | --- | --- |
| `id` | `string` | The clearance id. |
| `onCancelled` | `(result: RevokeResult) => void` | After the revoke. `result.dispatch` is `'delivered'` or `'in_flight'` when your executor may already have it. |
| `labels` | `LabelOverrides` | |

`canCancelBeforeRun(item)` is the same test as data: `true` for `cleared` items whose `completion.status` isn't `done` or `failed`.

## Hooks {#hooks}

The components are built on these. Use them for a fully custom UI: they carry the same permission-aware logic. A `Resource<T>` is `{ data: T | undefined; error: unknown; loading: boolean; revalidate: () => Promise<void> }`; it loads on mount, shares requests between components, and polls while visible.

| Hook | Signature | Returns |
| --- | --- | --- |
| `useApprovalQueue` | `useApprovalQueue(opts?: QueueOptions)` | `{ items: Approval[]; loading; error; hasMore; loadingMore; loadMore(): Promise<void>; revalidate(): Promise<void> }`. `QueueOptions` = `{ status?, filter?: { actionPrefix?, batchId? }, limit? }` (default status `['pending', 'escalated']`, limit 25). |
| `useApproval` | `useApproval(id: string \| null \| undefined)` | `Resource<Approval>`: the clearance in full. `null` doesn't load. |
| `usePermissions` | `usePermissions(id)` | `Resource<Permissions>`: `{ can, cannot, reason_required, dual_review, requires_passkey, send_back_forces?, reviewer, status }`. Only show buttons in `can`. |
| `useHistory` | `useHistory(id)` | `Resource<HistoryEvent[]>`, oldest first, including earlier revisions. |
| `useDecide` | `useDecide(id: string)` | `{ decide(decision: Decision, opts?: { reason?, escalateTo? }): Promise<DecideResult>; pending; error: ApprovalsError \| null; result: DecideResult \| null; reset() }`. Refuses a decline or send-back without a 4+ character reason before sending (`reason_required`). Refreshes open views after. |
| `useRevoke` | `useRevoke(id: string)` | `{ revoke(reason: string): Promise<RevokeResult>; pending; error; result; reset() }`. |
| `useRules` | `useRules()` | `Resource<Rules>`: `{ settings, summary[], active_version, currency, refund_approvers?, pending_proposal?, viewer?: { role, can_edit, can_accept } }`. Not polled. |
| `useRulesProposal` | `useRulesProposal()` | `{ propose(settings: Partial<RulesSettings>): Promise<ProposeResult>; accept(proposalId: string): Promise<{ status: 'active' }>; proposal; pending; error; reset() }`. |
| `useRevalidate` | `useRevalidate()` | `(prefix?: string) => Promise<void>`: refresh open views now. A prefix (`'items'`, `'item:<id>'`, `'permissions:<id>'`, `'history:<id>'`, `'rules'`) refreshes only those; nothing refreshes everything. |
| `useClearedBy` | `useClearedBy()` | The provider's value: `{ client, store, labels, pollInterval, locale, classNames, unstyled, components }`. Throws outside a provider. |
| `useLabels` | `useLabels(overrides?: LabelOverrides)` | The provider's labels with `overrides` on top. |
| `useUi` | `useUi(props: StyleProps)` | `{ cls(...slots), root(...slots), C: UiComponents, pass, unstyled }`: class and component resolution for building your own parts that honour `classNames` / `unstyled` / `components`. |

`Decision` is `'clear' | 'reject' | 'send_back' | 'escalate'`. `DecideResult.status` is `'cleared' | 'rejected' | 'pending' | 'escalated' | 'sent_back'` (`pending` = one of two approvals, with `approvals` and `required`). Errors from hooks are `ApprovalsError` (`message`, `status`, `code`: ClearedBy's or the proxy's error code, `network` for a failed request).

Also exported: `keys` (the cache-key builders `useRevalidate` prefixes come from: `keys.queue(qs)`, `keys.item(id)`, `keys.permissions(id)`, `keys.history(id)`, `keys.rules()`), `REASON_REQUIRED` (`['reject', 'send_back']`) and `MIN_REASON_LENGTH` (`4`).

## Theming: design tokens {#theming}

The components inherit your page's font and text colour by default. To match your product, give ClearedBy your design tokens **once, as data**: no CSS to write, and every component in every org picks them up.

### The ClearedByTheme schema {#theme-schema}

```ts title="ClearedByTheme"
interface ClearedByTheme {
  colors?: {
    primary?: string       // buttons, links, focus rings, the selected card
    primaryText?: string   // text on primary buttons
    surface?: string       // card / panel background (default: transparent)
    surfaceAlt?: string    // subtle background: table headers, notes, neutral badges
    border?: string
    text?: string          // body text (default: inherited)
    mutedText?: string
    success?: string
    warning?: string
    danger?: string
  }
  radius?: string          // e.g. '8px' or '0.5rem'
  fontFamily?: string      // e.g. 'Inter, system-ui, sans-serif' (default: inherited)
  fontSize?: string        // base size, e.g. '15px' (default: inherited)
  spacing?: { xs?: string; sm?: string; md?: string; lg?: string }
  shadow?: string          // card shadow, e.g. '0 1px 2px rgba(0,0,0,.08)' (default: none)
  dark?: { colors?: ClearedByTheme['colors']; shadow?: string }   // dark-mode overrides
}
```

Values must be plain CSS: colours (`#hex`, `rgb()`, `hsl()`, `hwb()`, `lab()`, `lch()`, `oklab()`, `oklch()`, `color()`, colour names), lengths (`px`, `rem`, `em`, `%`), a font list, or a box-shadow. `url()`, `var()`, `expression()`, `attr()`, `;`, `{`, `}`, `<`, comments and unknown keys are refused by the API with `400 invalid_body` and dropped by the components, so a theme can never inject CSS.

### Four ways to set it {#theme-ways}

| Way | How |
| --- | --- |
| **API** (recommended) | `partner.updateSettings({ theme })` for your whole account, and optionally `partner.updateOrg(orgId, { theme })` per merchant (token by token on top; `null` clears it). `partner.getOrgTheme(orgId)` returns the merged result. The provider fetches it through the proxy (`GET /theme`, cached 5 minutes per org). |
| **Importers** | `@clearedby/react/theme`: `fromShadcn(globalsCss \| cssVars \| element)`, `fromTailwind(resolvedConfig)`, `fromDesignTokens(w3cJson)` turn what you already have into a theme. |
| **CLI** | `npx @clearedby/react theme --from <file> [--push] [--org <org_id>] [--base-url <url>]` prints the theme; `--push` saves it with `CLEAREDBY_PARTNER_KEY` (account-wide, or one org with `--org`). |
| **In code** | `<ClearedByProvider theme={...} colorScheme="class">` overrides the stored theme token by token. |

```bash title="terminal"
# shadcn/ui: read the CSS variables in globals.css, print the theme, save it for your account
npx @clearedby/react theme --from app/globals.css --push

# Tailwind 3 config (resolved with tailwindcss/resolveConfig when installed), for one merchant
npx @clearedby/react theme --from tailwind.config.js --push --org 01K...

# W3C design tokens (DTCG), or an existing ClearedByTheme JSON
npx @clearedby/react theme --from tokens.json
```

### Importers {#importers}

| Function | Reads | Mapping |
| --- | --- | --- |
| `fromShadcn(input)` | A `globals.css` string, a `{ '--primary': ... }` map, or (in the browser) an element whose computed style carries the variables | `--primary` → primary, `--primary-foreground` → primaryText, `--card` / `--background` → surface, `--muted` → surfaceAlt, `--border` → border, `--foreground` → text, `--muted-foreground` → mutedText, `--destructive` → danger, `--success`, `--warning`, `--radius`, `--font-sans`. The `.dark` block becomes `dark`. shadcn v3 HSL channels and v4 `oklch()` both work. |
| `fromTailwind(config)` | A **resolved** Tailwind config | Semantic names first (`primary`, `background`, `card`, `muted`, `border`, `foreground`, `destructive`, `success`, `warning`), then the default palette (`blue`/`indigo` 600, `gray`/`slate` 100/200/500/900, `green` 600, `amber` 600, `red` 600); `borderRadius`, `fontFamily.sans`, `fontSize.base`, `spacing` 1/2/3/5, `boxShadow.sm`. |
| `fromDesignTokens(json)` | W3C Design Tokens (DTCG) JSON | Matched by name (primary/brand/accent, surface/background, border, text/foreground, success, warning, danger/error, radius, font, spacing, shadow); `{alias}` references resolved; a top-level `dark` group becomes `dark`. |
| `parseCssVariables(css)` | CSS text | `{ light, dark }` maps of the custom properties in `:root` and `.dark`. |

The theme helpers are exported from both `@clearedby/react` and `@clearedby/react/theme`: `sanitizeTheme(input)` (keep only valid tokens, or `null`), `mergeTheme(base, over)` (token by token), `themeToCssVars(theme)` and `themeToDarkCssVars(theme)` (the `--cb-*` properties) and `themeCss(theme, scopeId, colorScheme)` (the stylesheet the provider injects).

### Let your AI coding agent write it {#theme-agent}

```text title="prompt"
Read our design system (the Tailwind config, globals.css / CSS variables, or design-token
files) and produce a JSON object matching the ClearedByTheme type from
https://clearedby.com/docs/partners/ui#theme-schema, choosing the values our app actually
uses for buttons, cards, borders, body text, muted text, success/warning/error states,
corner radius, font and spacing. Use only literal CSS values: hex / rgb() / hsl() / oklch()
colours, px / rem lengths, a font-family list and a box-shadow. No var(), no url(). Include
a "dark" block if we support dark mode. Save it as clearedby-theme.json, then run:
npx @clearedby/react theme --from clearedby-theme.json --push
```

## Deeper customisation {#customisation}

When tokens aren't enough there are three further levels, and you can mix them.

### Level 1: CSS variables {#css-variables}

The default stylesheet (`@clearedby/react/styles.css`) reads only these variables, with neutral fallbacks that work on light and dark pages. It uses only `cb-*` classes: no element selectors, resets or globals. Set any of them in your own CSS, for one page or everywhere:

| Variable | Token |
| --- | --- |
| `--cb-color-primary` | `colors.primary` |
| `--cb-color-primary-text` | `colors.primaryText` |
| `--cb-color-surface` | `colors.surface` |
| `--cb-color-surface-alt` | `colors.surfaceAlt` |
| `--cb-color-border` | `colors.border` |
| `--cb-color-text` | `colors.text` |
| `--cb-color-muted` | `colors.mutedText` |
| `--cb-color-success` | `colors.success` |
| `--cb-color-warning` | `colors.warning` |
| `--cb-color-danger` | `colors.danger` |
| `--cb-radius` | `radius` |
| `--cb-font` | `fontFamily` |
| `--cb-font-size` | `fontSize` |
| `--cb-space-xs`, `--cb-space-sm`, `--cb-space-md`, `--cb-space-lg` | `spacing` |
| `--cb-shadow` | `shadow` |

### Level 2: classNames slots {#classnames}

Every styleable part has a slot. Pass any subset as `classNames` on the provider (every component) or on one component; they are added to the default `cb-*` class, or replace it with `unstyled`. `DEFAULT_CLASSES` holds the defaults (`root` → `cb-root`, `cardSelected` → `cb-card--selected`, ...).

| Group | Slots |
| --- | --- |
| Layout and text | `root`, `heading`, `subheading`, `text`, `hint`, `status`, `success`, `error`, `warning`, `header`, `kicker`, `meta`, `section`, `note`, `callout` |
| Lists and cards | `list`, `listItem`, `card`, `cardSelected`, `cardTop`, `cardTitle`, `cardSentence`, `cardMeta`, `pager` |
| Badges | `badge`, `badgeWaiting`, `badgeOk`, `badgeBad`, `badgeWarn`, `badgeMuted` |
| Buttons and links | `button`, `primaryButton`, `secondaryButton`, `dangerButton`, `ghostButton`, `link`, `buttonRow` |
| Forms | `form`, `field`, `label`, `input`, `textarea`, `select`, `checkbox`, `checkboxLabel` |
| Key/value and tables | `kv`, `kvRow`, `kvTerm`, `kvValue`, `tableWrap`, `table`, `tableHeadCell`, `tableRow`, `tableRowHeader`, `tableCell`, `diff`, `diffBefore`, `diffAfter` |
| Evidence | `evidence`, `evidenceGroup`, `evidenceVerified`, `evidenceComputed`, `evidenceAgent`, `evidenceBadge`, `evidenceItem`, `evidenceLabel`, `evidenceValue`, `evidenceList` |
| History and dialogs | `timeline`, `timelineItem`, `timelineRevision`, `timelineTime`, `dialog`, `dialogTitle` |

### Level 3: your own components {#components-injection}

Pass your design system's primitives to the provider. Anything you leave out uses the default (plain, accessible elements; the default `Dialog` is inline and non-modal). `DEFAULT_COMPONENTS` holds the defaults.

| Component | Props it receives |
| --- | --- |
| `Button` | `ButtonHTMLAttributes` plus `variant: 'primary' \| 'secondary' \| 'danger' \| 'ghost'` (map it to yours, e.g. shadcn `danger` → `destructive`) |
| `Input` | `InputHTMLAttributes<HTMLInputElement>` |
| `Textarea` | `TextareaHTMLAttributes<HTMLTextAreaElement>` |
| `Select` | `SelectHTMLAttributes<HTMLSelectElement>` |
| `Badge` | `{ tone: 'waiting' \| 'ok' \| 'bad' \| 'warn' \| 'muted'; className?; children? }` |
| `Dialog` | `{ open; onClose(); title; titleId; className?; titleClassName?; children? }`. Put `titleId` on your title element. |

```tsx title="app/approvals.tsx"
import { ClearedByProvider, ApprovalQueue, type UiButtonProps, type UiBadgeProps } from '@clearedby/react'
import { Button } from '@/components/ui/button'   // shadcn/ui
import { Badge } from '@/components/ui/badge'

const VARIANT = { primary: 'default', secondary: 'secondary', danger: 'destructive', ghost: 'ghost' } as const
const CbButton = ({ variant, ...rest }: UiButtonProps) => <Button variant={VARIANT[variant]} {...rest} />
const CbBadge = ({ tone, children }: UiBadgeProps) => <Badge variant={tone === 'bad' ? 'destructive' : 'secondary'}>{children}</Badge>

<ClearedByProvider basePath="/api/clearedby" components={{ Button: CbButton, Badge: CbBadge }}>
  <ApprovalQueue />
</ClearedByProvider>
```

## Labels {#labels}

Every word is written for merchants, not developers (no "policy", no product names). Override any of it with `labels` on the provider or on one component; grouped labels merge one level deep, so `{ decisions: { clear: 'Looks good' } }` keeps the other decisions. `DEFAULT_LABELS` holds the defaults and `mergeLabels(base, overrides)` merges them.

| Area | Keys (with the default) |
| --- | --- |
| Queue | `queueTitle` ("Waiting for your OK"), `queueEmpty` ("Nothing is waiting for you."), `loading`, `loadError`, `retry`, `loadMore` ("Show more"), `needsTwo(have, need)`, `sentToYou`, `expiresIn(text)` |
| Status badges | `status.pending`, `status.escalated` ("Waiting"), `status.cleared` ("Approved"), `status.rejected` ("Declined"), `status.expired` ("Lapsed"), `status.sent_back` ("Sent back"), `status.revoked` ("Cancelled"), `status.withdrawn` ("Withdrawn") |
| Review panel | `whyTitle`, `detailsTitle`, `changesTitle` ("What will change"), `changesSummary(count)`, `showing(from, to, total)`, `previousPage`, `nextPage`, `columnItem`, `columnBefore` ("Now"), `columnAfter` ("After"), `confidence(pct)`, `evidenceTitle` ("The facts"), `evidenceAgent` ("Agent says"), `evidenceVerifiedBy(name)` ("Verified by …"), `evidenceComputed` ("Checked automatically"), `evidenceChanged`, `evidenceAgentHint`, `revisionOf(attempt)`, `decidedBy(status, who)`, `reasonGiven` |
| Decisions | `decisionGroup`, `actionError`, `saveError`, `decisions.clear` ("Approve"), `decisions.reject` ("Decline"), `decisions.send_back` ("Send back with a note"), `decisions.escalate` ("Ask someone else"), `reasonPrompt.{reject,send_back,escalate}`, `reasonPlaceholder.{reject,send_back,escalate}`, `reasonTooShort`, `confirm.{clear,reject,send_back,escalate}`, `cancel`, `working`, `decided.{cleared,rejected,pending,escalated,sent_back}`, `nothingToDo` |
| Why a button is missing | `cannot.not_pending`, `cannot.no_authority`, `cannot.already_approved`, `cannot.self_approval`, `cannot.requester_cannot_approve`, `cannot.forbidden`, `cannot.passkey_required`, `cannot.passkey_required_not_supported_for_partner` (any other code can be added) |
| Cancel before it runs | `cancelBeforeRuns`, `cancelPrompt`, `cancelPlaceholder`, `cancelConfirm`, `cancelled`, `cancelledButMayHaveStarted` |
| History | `historyTitle`, `historyEmpty`, `event(kind, data)` (return `null` to hide an event), `someone`, `automatic` |
| Rules | `rulesTitle` ("Your approval rules"), `rulesIntro`, `looksGood`, `adjust`, `save`, `saving`, `rulesSaved`, `rulesUnchanged`, `rulesNeedOwner`, `rulesLooserTitle`, `rulesYesChange`, `rulesPendingTitle`, `rulesAccepted`, `never`, `oneIn(n)` |
| Rule settings | `settings.refund_auto_max`, `settings.refund_dual_above`, `settings.refund_daily_auto_cap`, `settings.refund_per_order_cap`, `settings.tags_auto_max_products`, `settings.inventory_auto_max_items`, `settings.price_changes`, `settings.price_changes_always`, `settings.price_changes_drops`, `settings.price_drop_review_pct`, `settings.timeout_hours`, `settings.spot_checks`, `settings.spot_checks_help`, `settings.spot_check_how_often` |

```tsx title="labels.tsx"
<ClearedByProvider
  basePath="/api/clearedby"
  labels={{
    queueTitle: 'Needs your approval',
    decisions: { clear: 'Looks good', send_back: 'Ask for changes' },
    evidenceVerifiedBy: (name) => `Checked by ${name}`,
    status: { rejected: 'Not approved' },
  }}
>
```

Plain-English helpers used by the components, exported for your own UI: `describeAction(item, formatters)` returns `{ title, sentence }` for a clearance; `ACTION_TITLES` maps catalogue actions to titles ("Update prices"); `humanizeAction(action)` for anything else; `shortId(gid)` turns `gid://shopify/Order/6001` into `#6001`; `makeFormatters(locale?)` returns `{ money(amount, currency?), number(n) }`.

## The partner proxy {#proxy}

`createPartnerProxy(options)` from `@clearedby/sdk/partner-proxy` returns `{ handle(req: Request): Promise<Response>, clearTokenCache(user?) }`. It is Web Fetch in, Web Fetch out, so it drops into Next.js App Router, Hono, Remix, Bun, Deno or Cloudflare Workers; `expressHandler(proxy)` adapts it to Express.

| Option | Type | Default | What it does |
| --- | --- | --- | --- |
| `partnerKey` | `string` | required | Your `cb_partner_` key. Never echoed. |
| `resolveUser` | `(req: Request) => ProxyUser \| null` (or a promise) | required | Who is asking, from **your** session: `{ org_id, external_subject }`, or `null` for `401`. The **only** source of the org and the person: an `org_id` or `reviewer` the browser sends is ignored. |
| `basePath` | `string` | `'/api/clearedby'` | Where it is mounted. Must match the route. |
| `baseUrl` | `string` | `https://app.clearedby.com` | ClearedBy's API. |
| `canEditRules` | `(user, req) => boolean \| Promise<boolean>` | everyone | May this person change the approval rules? A looser change still needs an owner or admin, which ClearedBy enforces. |
| `allowedOrigins` | `string[]` | | Extra origins allowed to send writes. Same-origin writes are always allowed; others get `403 cross_site`. |
| `readTokenTtlSeconds` | `number` | `600` | Read-token lifetime (60 to 900), cached per person. |
| `fetch` | `typeof fetch` | global | Custom fetch (tests, instrumentation). |

### Allow-listed routes {#proxy-routes}

Only these exist; anything else is `404`, a wrong method `405`.

| Route | ClearedBy call | Credential used |
| --- | --- | --- |
| `GET /items` (`status`, `action_prefix`, `batch_id`, `cursor`, `limit` 1-100, `include`=`params`/`proof`) | `GET /v1/gate` as this reviewer | cached read token |
| `GET /items/:id` | `GET /v1/gate/:id/detail` | cached read token |
| `GET /items/:id/events` | `GET /v1/gate/:id/events?include=lineage` | cached read token |
| `GET /items/:id/permissions` | `GET /v1/gate/:id/permissions` | cached read token |
| `POST /items/:id/decide` (`decision`, `reason`, `escalate_to`) | `POST /v1/gate/:id/decide` | fresh decide token pinned to the item (60 s) |
| `POST /items/:id/revoke` (`reason`) | `POST /v1/gate/:id/revoke` as this person | fresh decide token pinned to the item |
| `GET /rules` | `GET /v1/partner/orgs/:org/rules` plus `viewer` | partner key |
| `PUT /rules` (`settings`) | `PUT /v1/partner/orgs/:org/rules` | partner key |
| `POST /rules/proposals/:id/accept` | `POST .../rules/:id/accept` as this person | fresh decide token |
| `GET /theme` | `GET /v1/partner/orgs/:org/theme` (cached 5 min) | partner key |

What it guarantees: the partner key and every token stay on your server; `receipt`, `token` and `api_key` fields and anything shaped like a ClearedBy key are stripped from responses; writes must be same-origin JSON (`415` otherwise), at most 16 KB, with only the listed fields; a `401` from ClearedBy for your own credentials becomes `502 upstream_auth` rather than logging the reviewer out; responses are `cache-control: no-store`.

## Recipes {#recipes}

### Next.js App Router {#recipe-nextjs}

```ts title="app/api/clearedby/[...path]/route.ts"
import { createPartnerProxy } from '@clearedby/sdk/partner-proxy'
import { auth } from '@/auth'                      // your auth (NextAuth, Clerk, a cookie...)
import { db } from '@/db'

const proxy = createPartnerProxy({
  partnerKey: process.env.CLEAREDBY_PARTNER_KEY!,
  resolveUser: async () => {
    const session = await auth()
    if (!session?.user) return null
    const m = await db.membership.findActive(session.user.id)   // which merchant are they working in?
    return m ? { org_id: m.clearedbyOrgId, external_subject: session.user.id } : null
  },
  canEditRules: async () => (await auth())?.user.role === 'admin',
})

export const dynamic = 'force-dynamic'
export const GET = proxy.handle
export const POST = proxy.handle
export const PUT = proxy.handle
```

### Express {#recipe-express}

```ts title="server.ts"
import express from 'express'
import { createPartnerProxy, expressHandler } from '@clearedby/sdk/partner-proxy'

const app = express()
const proxy = createPartnerProxy({
  partnerKey: process.env.CLEAREDBY_PARTNER_KEY!,
  basePath: '/api/clearedby',
  resolveUser: async (req) => {
    const s = await sessions.fromCookie(req.headers.get('cookie'))   // your session store
    return s ? { org_id: s.clearedbyOrgId, external_subject: s.userId } : null
  },
})
// Mount on the same path as basePath. Any body parser is fine: the adapter reads the raw
// stream, or re-serialises a body that express.json() / express.text() already parsed.
app.use('/api/clearedby', expressHandler(proxy))
```

### Tailwind or shadcn/ui theming {#recipe-tailwind}

Store the theme once from your existing CSS, then either keep the default stylesheet or go fully utility-first:

```bash title="terminal"
npx @clearedby/react theme --from app/globals.css --push
```

```tsx title="app/approvals.tsx"
import { ClearedByProvider, ApprovalQueue, ReviewPanel } from '@clearedby/react'
// no styles.css import: `unstyled` drops every cb-* class, Tailwind does it all

<ClearedByProvider
  basePath="/api/clearedby"
  colorScheme="class"                               // follow shadcn's .dark
  unstyled
  classNames={{
    root: 'space-y-4',
    heading: 'text-lg font-semibold',
    card: 'w-full rounded-lg border p-3 text-left hover:bg-muted',
    cardSelected: 'border-primary ring-1 ring-primary',
    cardMeta: 'text-sm text-muted-foreground',
    badge: 'rounded-full px-2 py-0.5 text-xs',
    badgeWaiting: 'bg-amber-100 text-amber-900',
    badgeOk: 'bg-emerald-100 text-emerald-900',
    badgeBad: 'bg-red-100 text-red-900',
    table: 'w-full text-sm',
    tableHeadCell: 'text-left font-medium text-muted-foreground',
    textarea: 'w-full rounded-md border bg-background p-2',
    buttonRow: 'flex gap-2',
  }}
  components={{ Button: CbButton }}                 // the shadcn Button mapping from "Level 3"
>
  <ApprovalQueue />
</ClearedByProvider>
```

### A fully custom UI with hooks {#recipe-hooks}

```tsx title="components/approval-inbox.tsx"
'use client'
import { useApprovalQueue, useApproval, usePermissions, useDecide, describeAction, makeFormatters } from '@clearedby/react'

const f = makeFormatters('en-GB')

export function Inbox({ onOpen }: { onOpen: (id: string) => void }) {
  const q = useApprovalQueue({ filter: { actionPrefix: 'shopify.refund.' } })
  if (q.loading) return <Spinner />
  return (
    <ul>
      {q.items.map((item) => (
        <li key={item.id}><button onClick={() => onOpen(item.id)}>{describeAction(item, f).sentence}</button></li>
      ))}
      {q.hasMore && <button onClick={() => void q.loadMore()}>More</button>}
    </ul>
  )
}

export function Decide({ id }: { id: string }) {
  const item = useApproval(id)
  const perms = usePermissions(id)
  const d = useDecide(id)
  if (!item.data || !perms.data) return null
  return (
    <div>
      <h2>{describeAction(item.data, f).title}</h2>
      {perms.data.can.includes('clear') && <button disabled={d.pending} onClick={() => void d.decide('clear')}>Approve</button>}
      {perms.data.can.includes('reject') && (
        <button onClick={() => void d.decide('reject', { reason: prompt('Why?') ?? '' })}>Decline</button>
      )}
      {d.error && <p role="alert">{d.error.code === 'reason_required' ? 'Please add a note.' : d.error.message}</p>}
    </div>
  )
}
```

### Webhook-driven refresh {#recipe-revalidate}

Turn polling down (or off) and refresh the moment something changes: your backend receives ClearedBy's `decision.*` webhooks (see the [API reference](/docs/partners/api#cb-createwebhook)), tells the browsers of that merchant over whatever push channel you already have, and the browser calls `useRevalidate()`.

```ts title="app/api/clearedby-events/route.ts (server)"
import { verifyWebhook } from '@/lib/verify-webhook'   // HMAC check from the API reference
import { pusher } from '@/lib/pusher'                  // or SSE, a WebSocket, Ably...

export async function POST(req: Request) {
  const raw = await req.text()
  const evt = JSON.parse(raw)
  const secret = await secrets.get(`cb:${evt.org_id}:whsec`)
  if (!verifyWebhook(raw, req.headers.get('x-clearedby-signature'), secret)) return new Response(null, { status: 401 })
  await pusher.trigger(`approvals-${evt.org_id}`, 'changed', { id: evt.data.id })   // no payload data needed
  return new Response(null, { status: 200 })
}
```

```tsx title="components/live-approvals.tsx (browser)"
'use client'
import { useEffect } from 'react'
import { ClearedByProvider, ApprovalQueue, useRevalidate } from '@clearedby/react'

function LiveRefresh({ channel }: { channel: string }) {
  const revalidate = useRevalidate()
  useEffect(() => {
    const sub = pusherClient.subscribe(channel)
    sub.bind('changed', ({ id }: { id: string }) => {
      void revalidate('items')          // the queue
      void revalidate(`item:${id}`)     // that item, if open
      void revalidate(`permissions:${id}`)
    })
    return () => pusherClient.unsubscribe(channel)
  }, [channel, revalidate])
  return null
}

export function LiveApprovals({ orgId }: { orgId: string }) {
  return (
    <ClearedByProvider basePath="/api/clearedby" pollInterval={60_000}>
      <LiveRefresh channel={`approvals-${orgId}`} />
      <ApprovalQueue />
    </ClearedByProvider>
  )
}
```
