---
title: Quickstart
crumb: Quickstart
eyebrow: Quickstart · about 15 minutes
h1: From partner key to an approved, executed change.
description: Copy-paste, top to bottom. Set up your partner account, create a merchant org with a reviewer, embed the approval queue in a Next.js app, propose a change, approve it in your UI, verify the signed dispatch and report completion.
lede: Copy-paste, top to bottom. By the end, a proposal from a script shows up in an approval queue inside your own Next.js app, a person approves it, your executor receives a signed authorisation, verifies it and reports the result. Every step shows the code and what you should see.
pills: Next.js App Router, Node 18+, @clearedby/sdk 0.1+, @clearedby/react 0.1+
---

# Quickstart

This walks through the whole integration once, with the smallest code that is still correct. Shopify is the worked example, but nothing touches a real store: the executor logs the change instead of calling Shopify. The [guide](/docs/partners/guide) explains each piece in depth; the [API reference](/docs/partners/api) has every signature.

### Before you start {#before}

You need:

- **A partner key** (`cb_partner_...`) from ClearedBy. Partner accounts are provisioned by ClearedBy: contact us for a partner account, or ask your ClearedBy contact for a key. It goes in your server's environment only: never in a browser bundle, an agent prompt or a log line.
- **Node 18 or later** and a **Next.js 14+ app using the App Router**. Starting fresh: `npx create-next-app@latest my-app --ts --app`.
- **A public HTTPS URL for your dev server.** ClearedBy refuses to send approvals to `localhost` or private addresses (`400 blocked_destination`), so run a tunnel. For example, with Cloudflare's free quick tunnel: `npx cloudflared tunnel --url http://localhost:3000`. It prints a URL like `https://quiet-river-1234.trycloudflare.com`. Keep it running.
- **A Shopify store domain** to register (for example your development store, `acme-dev.myshopify.com`). Nothing is written to it in this quickstart.

## Install and configure {#install}

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

```bash title=".env.local"
# From ClearedBy. SERVER ONLY: never prefix it with NEXT_PUBLIC_.
CLEAREDBY_PARTNER_KEY=cb_partner_0123456789abcdef0123456789abcdef
# Your tunnel URL from "Before you start" (no trailing slash).
PUBLIC_URL=https://quiet-river-1234.trycloudflare.com
```

The setup scripts below are `.mts` files (ES modules, so top-level `await` works in any project) run with `tsx`. They read `.env.local` with Node's `--env-file` flag (Node 20.6+). On Node 18, export the variables in your shell instead.

**Expected result:** `npm ls @clearedby/sdk @clearedby/react` shows both packages.

## Set your execution URL and alert email {#settings}

Once per partner account, tell ClearedBy where approved changes go (your executor, which you build in step 7) and where operational alerts go. Every org you create from now on uses these; there is nothing to configure per org.

```ts title="scripts/01-settings.mts"
import { ClearedByPartner } from '@clearedby/sdk'

const partner = new ClearedByPartner({ partnerKey: process.env.CLEAREDBY_PARTNER_KEY! })

const settings = await partner.updateSettings({
  execution_url: `${process.env.PUBLIC_URL}/api/executor`,   // cleared changes are POSTed here
  alert_email: 'platform-oncall@yourapp.example',             // dispatch failures, disabled webhooks
})
console.log(settings.execution_url, settings.alert_email)
```

```bash title="terminal"
npx tsx --env-file=.env.local scripts/01-settings.mts
```

**Expected result:** it prints your `https://.../api/executor` URL and the email. A `400 blocked_destination` means the URL isn't public HTTPS (check the tunnel). If your quick tunnel's URL changes later, run this script again.

## Create a company {#create-org}

One ClearedBy org per merchant company, keyed by your own id for it. The call is idempotent on `external_id`: running it again returns the same org with `created: false` and no key.

```ts title="scripts/02-create-org.mts"
import { ClearedByPartner } from '@clearedby/sdk'

const partner = new ClearedByPartner({ partnerKey: process.env.CLEAREDBY_PARTNER_KEY! })

const org = await partner.createOrg({
  external_id: 'shop_demo_1',                  // YOUR id for this merchant
  name: 'Acme Outdoor (dev)',
  currency: 'GBP',                             // ISO 4217: reviewer limits are in this currency
  shop_domains: ['acme-dev.myshopify.com'],    // permanent *.myshopify.com domains its keys may act on
})
if (!org.created) throw new Error('Org already exists: its first key was shown once, when it was created')

// A second key, so the executor's key can be rotated separately from the agent's.
const executorKey = await partner.createOrgKey(org.org_id, { name: 'executor' })
// The org's dispatch signing secret: your executor checks every dispatch with it.
const signingSecret = await partner.getSigningSecret(org.org_id)

console.log(`CLEAREDBY_ORG_ID=${org.org_id}`)
console.log(`CLEAREDBY_AGENT_KEY=${org.api_key}`)
console.log(`CLEAREDBY_EXECUTOR_KEY=${executorKey.api_key}`)
console.log(`CLEAREDBY_SIGNING_SECRET=${signingSecret}`)
```

```bash title="terminal"
npx tsx --env-file=.env.local scripts/02-create-org.mts >> .env.local
```

**Expected result:** four new lines at the end of `.env.local`: the org id (`01K...`, a ULID), two `cb_live_...` keys and the signing secret. The keys are shown **once**; in production, put them in your secret store. The org already has the default approval rules switched on: price changes always need a person, which is what the next steps rely on.

## Add a reviewer {#reviewer}

A reviewer is a person at the merchant who can approve, identified by **your** id for them (`external_subject`). Their authority maps action names to the largest amount they may approve, in minor units; `"*": 0` covers every action that carries no amount (tags, stock, prices, product edits) but no money.

```ts title="scripts/03-reviewer.mts"
import { ClearedByPartner } from '@clearedby/sdk'

const partner = new ClearedByPartner({ partnerKey: process.env.CLEAREDBY_PARTNER_KEY! })

const sam = await partner.upsertReviewer(process.env.CLEAREDBY_ORG_ID!, 'user_17', {
  display_name: 'Sam R.',
  role: 'owner',                                   // owner | admin | reviewer
  authority: { '*': 0, 'shopify.refund.create': 50000 },   // no-amount actions, refunds up to £500.00
})
console.log(sam.created ? 'created' : 'updated', sam.external_subject, sam.role)
```

```bash title="terminal"
npx tsx --env-file=.env.local scripts/03-reviewer.mts
```

**Expected result:** `created user_17 owner`. Running it again prints `updated`: a `PUT` replaces the whole record, so it is safe to repeat.

## Mount the partner proxy {#proxy}

The browser never talks to ClearedBy. It talks to **your** server, through one catch-all route. The proxy works out who is signed in with **your** session (`resolveUser`), mints short-lived tokens for exactly that person, and calls ClearedBy with your partner key, which never leaves the server.

```ts title="lib/session.ts"
import type { ProxyUser } from '@clearedby/sdk/partner-proxy'

// QUICKSTART ONLY: everyone is Sam in the one dev org. In your app, read YOUR
// session (cookie, JWT, NextAuth...) and return the merchant org the person is
// working in and the external_subject you provisioned them with, or null.
export async function currentUser(_req: Request): Promise<ProxyUser | null> {
  return { org_id: process.env.CLEAREDBY_ORG_ID!, external_subject: 'user_17' }
}
```

```ts title="app/api/clearedby/[...path]/route.ts"
import { createPartnerProxy } from '@clearedby/sdk/partner-proxy'
import { currentUser } from '@/lib/session'

const proxy = createPartnerProxy({
  partnerKey: process.env.CLEAREDBY_PARTNER_KEY!,
  basePath: '/api/clearedby',          // must match where this file is mounted
  resolveUser: (req) => currentUser(req),
})

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

**Expected result:** after `npm run dev`, opening `http://localhost:3000/api/clearedby/items` in the browser returns `{"items":[],"next_cursor":null}`. A `403 not_a_reviewer` means the org id or `external_subject` doesn't match step 3 or 4.

## Render the approval queue {#queue}

```tsx title="app/approvals/approvals.tsx"
'use client'
import { useState } from 'react'
import { ClearedByProvider, ApprovalQueue, ReviewPanel } from '@clearedby/react'
import '@clearedby/react/styles.css'

export function Approvals() {
  const [id, setId] = useState<string | null>(null)
  return (
    <ClearedByProvider basePath="/api/clearedby">
      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(260px, 1fr) 2fr', gap: 24, padding: 24 }}>
        <ApprovalQueue selectedId={id} onSelect={(item) => setId(item.id)} />
        {id ? <ReviewPanel id={id} /> : <p>Pick something from the list.</p>}
      </div>
    </ClearedByProvider>
  )
}
```

```tsx title="app/approvals/page.tsx"
import { Approvals } from './approvals'

export default function Page() {
  return <Approvals />
}
```

**Expected result:** `http://localhost:3000/approvals` shows **Waiting for your OK** and "Nothing is waiting for you."

## Build the executor {#executor}

ClearedBy POSTs every approved change to your `execution_url` as a signed envelope carrying an Ed25519-signed receipt. Your executor verifies it with `verifyDispatch`, dedupes on `work_item_id`, executes **only** the receipt's params, and reports what happened. Read the body as **text**: the signature is over the exact bytes.

```ts title="app/api/executor/route.ts"
import { ClearedBy, type CompletionItem } from '@clearedby/sdk'
import { verifyDispatch, DispatchVerificationError, ReceiptRevokedError } from '@clearedby/sdk/dispatch'

export const runtime = 'nodejs'          // verifyDispatch uses node:crypto
export const dynamic = 'force-dynamic'

const executed = new Set<string>()        // QUICKSTART ONLY: use a unique DB index in production
const cb = new ClearedBy({ apiKey: process.env.CLEAREDBY_EXECUTOR_KEY! })

type PriceChange = { variant_id: string; before: { price: string }; after: { price: string } }

export async function POST(req: Request) {
  const raw = await req.text()
  let v
  try {
    v = await verifyDispatch(raw, req.headers, {
      secret: process.env.CLEAREDBY_SIGNING_SECRET!,
      orgId: process.env.CLEAREDBY_ORG_ID!,                        // the signed body must name this org
      jwksUrl: 'https://app.clearedby.com/.well-known/clearedby-keys',
      audience: process.env.PUBLIC_URL!,                           // the receipt must name you
      checkStatus: true,                                           // refuse an approval revoked since
    })
  } catch (err) {
    if (err instanceof ReceiptRevokedError) return Response.json({ status: 'revoked' })      // 2xx: don't retry
    if (err instanceof DispatchVerificationError && err.code === 'status_unavailable') {
      return new Response(null, { status: 503 })                  // fail closed: ClearedBy retries
    }
    console.error('dispatch refused:', err instanceof DispatchVerificationError ? err.code : err)
    return Response.json({ error: 'invalid dispatch' }, { status: 401 })
  }

  const { envelope, params, receipt } = v
  if (envelope.verdict !== 'cleared') return Response.json({ status: 'noted', executed: false })   // only 'cleared' authorises
  if (executed.has(envelope.work_item_id)) {
    return Response.json({ status: 'already_executed', executed: false }, { status: 409 })
  }
  // The go-live checker (npx @clearedby/sdk doctor): its own requests are dry runs,
  // and its test approvals (doctor.noop) touch nothing but are reported done.
  if (req.headers.get('clearedby-doctor') === '1') return Response.json({ status: 'dry_run', executed: false })
  executed.add(envelope.work_item_id)                             // record BEFORE executing
  if (envelope.action === 'doctor.noop') {
    if (params.skip_complete !== true) {
      await cb.complete(envelope.work_item_id, { status: 'done', completionId: `${envelope.work_item_id}:final`, deliveryReceiptId: receipt!.receipt_id })
    }
    return Response.json({ status: 'noop', executed: false })
  }

  // "Execute": in production, re-read each variant's live price, write `after` only if it
  // still equals `before`, and report the rest as 'skipped'. Here we just log.
  const items: CompletionItem[] = (params.changes as PriceChange[]).map((c) => {
    console.log(`would set ${c.variant_id} price ${c.before.price} -> ${c.after.price} in ${params.store}`)
    return { key: c.variant_id, status: 'done', before: c.before, after: c.after }
  })

  const result = await cb.complete(envelope.work_item_id, {
    status: 'done',
    completionId: `${envelope.work_item_id}:final`,   // stable: a retry replays instead of duplicating
    items,
    deliveryReceiptId: receipt!.receipt_id,
  })
  console.log('completion recorded:', result.recorded, 'diverged:', result.diverged)
  return Response.json({ status: 'accepted' }, { status: 202 })
}
```

**Expected result:** nothing yet. Restart `npm run dev` so the new environment variables load. A quick check: `curl -X POST $PUBLIC_URL/api/executor -d '{}'` answers `401` (no signature), which is what a forged request gets.

## Propose a change from a script {#propose}

This plays your agent. It holds the org's **agent** key, which can propose but never approve. A price change always needs a person under the default rules, so it will wait in the queue.

```ts title="scripts/04-propose.mts"
import { ClearedBy } from '@clearedby/sdk'

const agent = new ClearedBy({ apiKey: process.env.CLEAREDBY_AGENT_KEY! })

const r = await agent.gate({
  action: 'shopify.price.update',
  params: {
    store: 'acme-dev.myshopify.com',          // must be one of the org's shop_domains
    currency: 'GBP',
    changes: [{
      variant_id: 'gid://shopify/ProductVariant/2001',
      label: 'Linen shirt / M',               // what the reviewer sees
      before: { price: '40.00', compare_at_price: null },
      after: { price: '30.00', compare_at_price: '40.00' },
    }],
  },
  audience: process.env.PUBLIC_URL,           // the receipt will name your executor
  context: { summary: 'Mark the linen shirt down for the summer sale' },
  proof: {
    reason: 'Sell-through is 40% below plan and the summer sale starts Friday.',
    confidence: 0.8,
    evidence: [{ type: 'threshold', value: { label: 'Price drop', value: 25, limit: 30, unit: '%', status: 'ok' } }],
  },
  idempotencyKey: 'quickstart-price-1',       // a retry replays instead of proposing twice
})
console.log(r.status, r.id)
```

```bash title="terminal"
npx tsx --env-file=.env.local scripts/04-propose.mts
```

**Expected result:** `pending 01K...`. Within the 15-second refresh, the queue at `/approvals` shows **Update prices** with the change in a sentence. Running the script again prints the same id (the idempotency key replays the first answer).

## Approve it in your UI {#approve}

Open `http://localhost:3000/approvals`, pick the item and look at the review panel: the change as a before/after table, the agent's evidence badged **Agent says**, and only the buttons Sam may press (from ClearedBy's own permission check). Click **Approve**.

Behind the button, the proxy minted a single-use decision token naming `user_17`, pinned to this item, and called `POST /v1/gate/:id/decide`. ClearedBy checked Sam's authority itself.

**Expected result:** the panel shows **Approved.** and the item leaves the queue. ClearedBy dispatches straight away.

## Watch the dispatch arrive and complete {#complete}

In the `npm run dev` terminal:

```text title="dev server output"
would set gid://shopify/ProductVariant/2001 price 40.00 -> 30.00 in acme-dev.myshopify.com
completion recorded: true diverged: false
```

Confirm from ClearedBy's side with the agent key:

```ts title="scripts/05-check.mts"
import { ClearedBy } from '@clearedby/sdk'

const cb = new ClearedBy({ apiKey: process.env.CLEAREDBY_AGENT_KEY! })
const [item] = (await cb.list({ status: 'cleared', limit: 1 })).items
const d = await cb.delivery(item.id)
console.log(item.status, item.completion?.status, 'delivered:', d.delivery?.delivered)
```

```bash title="terminal"
npx tsx --env-file=.env.local scripts/05-check.mts
```

**Expected result:** `cleared done delivered: true`. That's the full loop: proposed, held by the merchant's rules, approved by a person in your UI, authorised with a signed receipt, verified and executed by your executor, and reported back.

## Check it before go-live {#doctor}

Run the go-live checker. It attacks your executor the way a forged or replayed dispatch would (a bad signature, a stale timestamp, tampered params, a `cleared` dispatch with a receipt ClearedBy never signed) and checks each is refused, then with `--full` pushes a harmless `doctor.noop` approval through for real and checks delivery, idempotency, your completion report and revocation. Each problem comes with a one-line fix.

The quickstart executor knows one org's signing secret, so point the doctor at that org (`--org`). An executor that looks secrets up by `envelope.org_id` can use the doctor's own sandbox org instead: leave `--org` out.

```bash title="terminal"
npx @clearedby/sdk doctor --org "$CLEAREDBY_ORG_ID" --audience "$PUBLIC_URL" --full
```

**Expected result:** every line is ✓ (or `-` for skipped) and the summary says `0 failed`. Anything marked ✗ says what to change. Add `--json` to run it in CI; the exit code is `1` when anything failed. The [API reference](/docs/partners/api#doctor) lists every check and what it can and can't prove.

## What to change for production {#production}

- [ ] Replace `lib/session.ts` with your real session lookup. The org and `external_subject` must come from **your** session, never from the request.
- [ ] Dedupe on `work_item_id` with a unique database index written before executing, not an in-memory `Set`.
- [ ] Reply to the dispatch fast (`202`) and execute in a job. Re-check live state before every write and report per-item results, including `skipped` and `failed`.
- [ ] Onboard each merchant from your own signup flow (steps 3 and 4), store the keys and signing secret in your secret store, and subscribe to lifecycle webhooks per org with `partner.createWebhook(orgId, ...)`. Rotate keys with `partner.rotateOrgKey` (a grace period lets you deploy the new key first).
- [ ] Work through the [security checklist](/docs/partners/security) and the [go-live checklist](/docs/partners/guide#testing), and get `npx @clearedby/sdk doctor --full` to `0 failed` against your production executor.

Next: make it look like your app in [UI components](/docs/partners/ui#theming), or read the [guide](/docs/partners/guide) for send-backs, evidence, revokes and undo.
