Reference · @clearedby/react

An approval UI that looks like your product.

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.

@clearedby/react 0.1.0 React 18+ @clearedby/sdk/partner-proxy View as Markdown
On this page
  1. How it fits together
  2. ClearedByProvider
  3. Components
  4. Hooks
  5. Theming: design tokens
  6. Deeper customisation
  7. Labels
  8. The partner proxy
  9. Recipes

01How it fits together

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.
  • Browser: @clearedby/react. <ClearedByProvider basePath="/api/clearedby"> plus the components or hooks. It calls only your proxy, with same-origin cookies.
terminal
npm install @clearedby/react @clearedby/sdk
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 wires this up end to end. A runnable Next.js app is in 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.

02ClearedByProvider

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

PropTypeDefaultWhat it does
basePathstring'/api/clearedby'Where your partner proxy is mounted.
labelsLabelOverridesReplace any wording (see labels).
pollIntervalnumber (ms)15000Refresh interval for open views. 0 turns polling off (drive it with useRevalidate).
localestringthe browser'sLocale for dates and money.
fetchtypeof fetchglobal fetchA custom fetch (tests, extra headers).
themeClearedByThemeDesign tokens, applied on top of the stored theme, token by token.
fetchThemebooleantrueFetch the stored theme from ${basePath}/theme.
colorScheme'auto' | 'class' | 'light' | 'dark''auto'Dark mode: the OS setting, a .dark ancestor (shadcn/Tailwind), or forced.
classNamesPartial<ClassNames>Extra classes per part, for every component (see slots).
unstyledbooleanfalseDrop every default cb-* class everywhere.
componentsPartial<UiComponents>Your Button, Input, Textarea, Select, Badge, Dialog (see injection).
childrenReactNode

03Components

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

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.

PropTypeDefaultWhat it does
statusItemStatus | 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.
limitnumber25Page size, 1 to 100.
onSelect(item: Approval) => voidA card was chosen.
selectedIdstring | nullHighlights that card.
titleReactNode | false"Waiting for your OK"Heading; false hides it.
renderItem(item: Approval, selected: boolean) => ReactNodeRender your own card instead of ApprovalCard.
labelsLabelOverrides

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).

PropTypeWhat it does
itemApprovalThe clearance (from the queue).
selectedbooleanSelected styling (cardSelected).
onSelect(item: Approval) => voidClicked.
labelsLabelOverrides

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.

PropTypeDefaultWhat it does
idstringrequiredThe clearance id.
showDecisionBarbooleantrueDecision buttons on open items.
showCancelbooleantrue"Cancel before it runs" on approved, not-yet-done items.
showHistorybooleantrueThe timeline.
escalateTostringHand escalations to this external_subject. Default: the most senior reviewer who can cover it.
onDecided(result: DecideResult, decision: Decision) => voidAfter a decision is recorded.
pageSizenumber50Rows per page in the changes table.
labelsLabelOverrides

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.").

PropTypeWhat it does
idstringThe clearance id.
escalateTostringHand escalations to this external_subject.
onDecided(result: DecideResult, decision: Decision) => voidAfter a decision is recorded.
labelsLabelOverrides

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.

PropTypeDefaultWhat it does
itemPick<Approval, 'action' | 'params'>requiredThe clearance.
pageSizenumber50Rows per page.
labelsLabelOverrides

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.

PropTypeWhat it does
evidence{ claims: EvidenceItem[]; verified: EvidenceItem[] } | undefinedThe clearance's evidence.
currencystringThe item's currency, for money figures in automatic checks.
labelsLabelOverrides

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

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.

PropTypeWhat it does
onLooksGood() => voidThe merchant tapped "Looks good" (the rules are already on; nothing is sent).
onChanged() => voidA change is live (saved stricter, or accepted).
labelsLabelOverrides

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

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

PropTypeWhat it does
idstringThe clearance id.
titlestring | falseHeading; false hides it.
labelsLabelOverrides

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).

PropTypeWhat it does
idstringThe clearance id.
onCancelled(result: RevokeResult) => voidAfter the revoke. result.dispatch is 'delivered' or 'in_flight' when your executor may already have it.
labelsLabelOverrides

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

04Hooks

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.

HookSignatureReturns
useApprovalQueueuseApprovalQueue(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).
useApprovaluseApproval(id: string | null | undefined)Resource<Approval>: the clearance in full. null doesn't load.
usePermissionsusePermissions(id)Resource<Permissions>: { can, cannot, reason_required, dual_review, requires_passkey, send_back_forces?, reviewer, status }. Only show buttons in can.
useHistoryuseHistory(id)Resource<HistoryEvent[]>, oldest first, including earlier revisions.
useDecideuseDecide(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.
useRevokeuseRevoke(id: string){ revoke(reason: string): Promise<RevokeResult>; pending; error; result; reset() }.
useRulesuseRules()Resource<Rules>: { settings, summary[], active_version, currency, refund_approvers?, pending_proposal?, viewer?: { role, can_edit, can_accept } }. Not polled.
useRulesProposaluseRulesProposal(){ propose(settings: Partial<RulesSettings>): Promise<ProposeResult>; accept(proposalId: string): Promise<{ status: 'active' }>; proposal; pending; error; reset() }.
useRevalidateuseRevalidate()(prefix?: string) => Promise<void>: refresh open views now. A prefix ('items', 'item:<id>', 'permissions:<id>', 'history:<id>', 'rules') refreshes only those; nothing refreshes everything.
useClearedByuseClearedBy()The provider's value: { client, store, labels, pollInterval, locale, classNames, unstyled, components }. Throws outside a provider.
useLabelsuseLabels(overrides?: LabelOverrides)The provider's labels with overrides on top.
useUiuseUi(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).

05Theming: design tokens

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

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

WayHow
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.
CLInpx @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.
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

FunctionReadsMapping
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 configSemantic 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) JSONMatched 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

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

06Deeper customisation

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

Level 1: 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:

VariableToken
--cb-color-primarycolors.primary
--cb-color-primary-textcolors.primaryText
--cb-color-surfacecolors.surface
--cb-color-surface-altcolors.surfaceAlt
--cb-color-bordercolors.border
--cb-color-textcolors.text
--cb-color-mutedcolors.mutedText
--cb-color-successcolors.success
--cb-color-warningcolors.warning
--cb-color-dangercolors.danger
--cb-radiusradius
--cb-fontfontFamily
--cb-font-sizefontSize
--cb-space-xs, --cb-space-sm, --cb-space-md, --cb-space-lgspacing
--cb-shadowshadow

Level 2: classNames slots

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, ...).

GroupSlots
Layout and textroot, heading, subheading, text, hint, status, success, error, warning, header, kicker, meta, section, note, callout
Lists and cardslist, listItem, card, cardSelected, cardTop, cardTitle, cardSentence, cardMeta, pager
Badgesbadge, badgeWaiting, badgeOk, badgeBad, badgeWarn, badgeMuted
Buttons and linksbutton, primaryButton, secondaryButton, dangerButton, ghostButton, link, buttonRow
Formsform, field, label, input, textarea, select, checkbox, checkboxLabel
Key/value and tableskv, kvRow, kvTerm, kvValue, tableWrap, table, tableHeadCell, tableRow, tableRowHeader, tableCell, diff, diffBefore, diffAfter
Evidenceevidence, evidenceGroup, evidenceVerified, evidenceComputed, evidenceAgent, evidenceBadge, evidenceItem, evidenceLabel, evidenceValue, evidenceList
History and dialogstimeline, timelineItem, timelineRevision, timelineTime, dialog, dialogTitle

Level 3: your own components

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.

ComponentProps it receives
ButtonButtonHTMLAttributes plus variant: 'primary' | 'secondary' | 'danger' | 'ghost' (map it to yours, e.g. shadcn danger → destructive)
InputInputHTMLAttributes<HTMLInputElement>
TextareaTextareaHTMLAttributes<HTMLTextAreaElement>
SelectSelectHTMLAttributes<HTMLSelectElement>
Badge{ tone: 'waiting' | 'ok' | 'bad' | 'warn' | 'muted'; className?; children? }
Dialog{ open; onClose(); title; titleId; className?; titleClassName?; children? }. Put titleId on your title element.
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>

07Labels

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.

AreaKeys (with the default)
QueuequeueTitle ("Waiting for your OK"), queueEmpty ("Nothing is waiting for you."), loading, loadError, retry, loadMore ("Show more"), needsTwo(have, need), sentToYou, expiresIn(text)
Status badgesstatus.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 panelwhyTitle, 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
DecisionsdecisionGroup, 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 missingcannot.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 runscancelBeforeRuns, cancelPrompt, cancelPlaceholder, cancelConfirm, cancelled, cancelledButMayHaveStarted
HistoryhistoryTitle, historyEmpty, event(kind, data) (return null to hide an event), someone, automatic
RulesrulesTitle ("Your approval rules"), rulesIntro, looksGood, adjust, save, saving, rulesSaved, rulesUnchanged, rulesNeedOwner, rulesLooserTitle, rulesYesChange, rulesPendingTitle, rulesAccepted, never, oneIn(n)
Rule settingssettings.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
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) }.

08The partner 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.

OptionTypeDefaultWhat it does
partnerKeystringrequiredYour cb_partner_ key. Never echoed.
resolveUser(req: Request) => ProxyUser | null (or a promise)requiredWho 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.
basePathstring'/api/clearedby'Where it is mounted. Must match the route.
baseUrlstringhttps://app.clearedby.comClearedBy's API.
canEditRules(user, req) => boolean | Promise<boolean>everyoneMay this person change the approval rules? A looser change still needs an owner or admin, which ClearedBy enforces.
allowedOriginsstring[]Extra origins allowed to send writes. Same-origin writes are always allowed; others get 403 cross_site.
readTokenTtlSecondsnumber600Read-token lifetime (60 to 900), cached per person.
fetchtypeof fetchglobalCustom fetch (tests, instrumentation).

Allow-listed routes

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

RouteClearedBy callCredential used
GET /items (status, action_prefix, batch_id, cursor, limit 1-100, include=params/proof)GET /v1/gate as this reviewercached read token
GET /items/:idGET /v1/gate/:id/detailcached read token
GET /items/:id/eventsGET /v1/gate/:id/events?include=lineagecached read token
GET /items/:id/permissionsGET /v1/gate/:id/permissionscached read token
POST /items/:id/decide (decision, reason, escalate_to)POST /v1/gate/:id/decidefresh decide token pinned to the item (60 s)
POST /items/:id/revoke (reason)POST /v1/gate/:id/revoke as this personfresh decide token pinned to the item
GET /rulesGET /v1/partner/orgs/:org/rules plus viewerpartner key
PUT /rules (settings)PUT /v1/partner/orgs/:org/rulespartner key
POST /rules/proposals/:id/acceptPOST .../rules/:id/accept as this personfresh decide token
GET /themeGET /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.

09Recipes

Next.js App Router

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

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

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

terminal
npx @clearedby/react theme --from app/globals.css --push
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

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

Turn polling down (or off) and refresh the moment something changes: your backend receives ClearedBy's decision.* webhooks (see the API reference), tells the browsers of that merchant over whatever push channel you already have, and the browser calls useRevalidate().

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 })
}
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>
  )
}

Something here doesn't match what you see? Tell your ClearedBy contact, with the clearance id.