Moving a block off the bridge
Most data a block used to fetch by posting a message to its host now has a REST route, and a block can call those routes today with the token it already has. This page maps each bridge hook to its route, and says what each credential reaches.
Which transport for what: Concepts → Transport models.
@civitai/sdk runs in a block now — and nothing is asking you to move
@civitai/app-sdk + @civitai/blocks-react continue; no app has to move.
The @civitai/sdk calls on this page need 0.14.0 at minimum.
On the default block token, @civitai/sdk's initialize() succeeds. app.storage, app.site on blocks/* paths, app.requestGrants and all of app.host (bridge messages underneath) work. app.orchestration rejects before it sends for a signed-in viewer, and app.site outside blocks/* returns the API's own 401/403 — with the auth: "oauth" opt-in appended — on a route that requires auth, while a public route answers anonymously.
auth: "oauth" gets a real OAuth access token that /api/v1, the orchestrator and the MCP accept — but it is a trade that costs the block routes which re-verify the bearer as a block token; see choosing your credential. The replacement table below is a map of routes, not packages, and applies either way.
The bridge is not deprecated. A block that moves its data calls uses both — fewer messages, not zero.
Before you write any code
Scope binding is per-route — declare only what you use
A route that declares a required scope binds only that scope against your block context: GET /api/v1/models/{id} declares models:read:self and 403s unless ?id is the model your block renders beside; GET /api/v1/blocks/buzz declares buzz:read:self and ignores your other scopes. A route with no required scope binds nothing — GET /api/v1/blocks/models accepts any valid block token, clamped only by its maturity ceiling. (An unrecognised scope is rejected outright, but the manifest validator catches that first.)
So declare the scopes your app actually uses, and pass each route the parameters its scope binds on.
Your tests will pass while exercising nothing
After the port your block sends no postMessage operations, so a mock host answers nothing and the suite goes green having tested none of the new path. Move the fake to fetch — see Testing below.
Choose your credential: the manifest's auth field
{
"blockId": "my-app",
"auth": "oauth"
}auth | Credential | Reaches |
|---|---|---|
"block-token" (default when omitted) | the block-scoped JWT | the block-token routes under /api/v1/blocks/*, plus /api/v1/models/{id} |
"oauth" | a real OAuth access token for the block's own client | /api/v1, the orchestrator and the MCP, unchanged |
Omitting auth keeps today's behaviour, so an existing manifest needs no edit to start calling the block routes.
The OAuth mint is live in production, but block-token is the default for good reasons:
- The block token reaches further than its name suggests — every route under
/api/v1/blocks/*except the publisher tooling (submit-version,withdraw,submissionsanddev-token, which take the developer's own API key), plus/api/v1/models/{id}. If that is your whole surface,auth: "oauth"buys nothing and costs the routes below. - The
oauthpath has little production use yet, and its consent surface is new — declare the narrowest scope set you can.
auth: "oauth" gives up four groups of block REST routes
An OAuth token resolves to the same (app, viewer) claims, but these routes re-verify the raw bearer as a block JWS, which it is not, so they fail with a 401 or 403: every app storage route (app-storage/*), every shared storage route (shared-storage/*), every workflow route (workflows/estimate, submit, poll, cancel and query) and user-checkpoint/set. Routes that do not re-verify the bearer work on either token — buzz, me, models, images, gated-images, generation-resources, tools, tip, tip-allowance and the collections routes among them.
If your app uses app storage, it cannot use auth: "oauth" today — the document store included: the refusal covers every apps:storage* scope. The server refuses the pair when a moderator approves the version (and on a direct git push), not when civitai app submit uploads it, and civitai app validate doesn't check it either — so fix it before submitting, or the request sits in review until approval fails. Left unrefused, every storage read and write would 401 as soon as a viewer signs in.
If your block generates, stay on the host-proxied workflow routes. They carry the per-call Buzz budget, the per-viewer and per-app daily caps, the maturity clamp and the app-block:<appId> attribution tag; a direct orchestrator call keeps only the per-viewer consent budget.
oauth is for a block that needs the general /api/v1 surface or the orchestrator directly, and none of the routes above.
The adapter shape
Put a thin per-app layer in src/platform/ rather than calling the API from components: one place to own the token, one place to fake in tests, and no wire shapes in your UI. It uses the validated host origin and the bearer the block already holds — the same direct-fetch pattern useTip and useGenerationResources use internally:
// src/platform/useApi.ts
import { useCallback } from 'react';
import { useHostOrigin, useBlockToken } from '@civitai/blocks-react';
/** A fetcher bound to this block's own credential. Throws until BLOCK_INIT. */
export function useApi() {
const host = useHostOrigin();
const { raw } = useBlockToken();
// useCallback is load-bearing, not tidiness. A fresh function identity every
// render turns the usual `useEffect(..., [call])` into an unbounded request
// loop — against money-scoped routes. blocks-react's own useTip does the same.
return useCallback(
async function call<T>(path: string, init?: RequestInit): Promise<T> {
if (!host) throw new Error('not ready: BLOCK_INIT has not landed');
const headers = new Headers(init?.headers);
headers.set('authorization', `Bearer ${raw}`);
const res = await fetch(`${host}/api/v1/blocks/${path}`, { ...init, headers });
if (!res.ok) throw new Error(`${path}: ${res.status}`);
return (await res.json()) as T;
},
[host, raw],
);
}// src/platform/buzz.ts — a capability, named the way your app thinks about it
import { useCallback } from 'react';
import { useApi } from './useApi';
export interface BuzzBalance {
blue: number;
green: number;
yellow: number;
}
export function useBuzzBalanceFetcher() {
const call = useApi();
return useCallback(() => call<BuzzBalance>('buzz'), [call]);
}Components import the capability, never the fetcher.
Two things this layer does not do for you
Gate on readiness. The function throws until BLOCK_INIT lands, so gate the call site on useBlockContext().ready, or a mount-time read fails with an unhandled rejection first.
Retry the 401 race. For a request that outlived its token, retry once through useBlockToken().refresh().
@civitai/sdk's initialize() runs in a block on either credential, so useApi can later become app.site with nothing above it changing.
Hook replacements
Every hook @civitai/blocks-react exports — the package root, plus useBlocksStyles from @civitai/blocks-react/ui. "Local" means the hook never talked to the platform — it is your own code now, with nothing to replace.
Don't trust a hook count — enumerate
The package gains hooks between releases. List the ones in your installed version:
node -e "import('@civitai/blocks-react').then(m => console.log(Object.keys(m).filter(k => k.startsWith('use')).sort().join(' ')))"| Bridge hook | Replacement |
|---|---|
useAppWorkflows | POST /api/v1/blocks/workflows/query. In @civitai/sdk: app.workflows.list({ cursor?, limit? }), which resolves { workflows, cursor } |
useBatchEstimate | No route yet — ESTIMATE_WORKFLOW_BATCH is a bridge message, and no /api/v1/blocks/* route prices a batch. Over REST, price each body with POST /api/v1/blocks/workflows/estimate; in @civitai/sdk that is one app.workflows.estimate(body) per body |
useBlockAnalytics | Keep — a bridge message with no route. Its events are recorded once your manifest declares them; @civitai/sdk's app.host.track() sends the same message. See the note below |
useBlockBreakpoint | Local — element measurement, keep as is |
useBlockContext | Keep — the handshake payload arrives over the bridge and has no route |
useBlockResize | Keep — host UI; only the host can size your frame |
useBlockSettings | Keep — part of the handshake payload |
useBlockTheme | Keep — part of the handshake payload |
useBlockToken | Keep — this is where the bearer for a direct fetch comes from, and its refresh() covers the 401 race |
useBlocksStyles | Local — stylesheet injection |
useBuzzAccounts | No route yet |
useBuzzBalance | GET /api/v1/blocks/buzz |
useBuzzPurchase | Keep — host UI |
useBuzzTransactions | No route yet |
useBuzzWorkflow | /api/v1/blocks/workflows/{estimate,submit,poll,cancel}. In @civitai/sdk: app.workflows.estimate, submit, get (the poll route), watch, wait and cancel — see Money calls for what changes in the port |
useCheckpointPicker | Keep the picker (host UI); .persist → POST /api/v1/blocks/user-checkpoint/set |
useCivitaiLocation | Keep — like useCivitaiRoute, it reads the host-owned view (sub-path, query string and fragment) from the handshake and ROUTE_CHANGED; off the bridge your own router owns the URL, so there is nothing to replace |
useCivitaiNavigate | Keep — host UI |
useCivitaiRoute | Keep — reads the host-owned sub-path from the handshake and ROUTE_CHANGED; off the bridge your own router owns the URL, so there is nothing to replace |
useCollectionFollow | POST /api/v1/blocks/collections/{id}/follow |
useConsentUnavailable | Keep — consent is host UI |
useCreatePostFromApp | Stays on the bridge, by design — see Posting from an app |
useDailyCompensation | Not carried |
useDirectLoad | Keep — see Embedding |
useDomainMaturity | No direct equivalent — keep the hook. Gate through its derived isSfw / isLevelAllowed, never on a raw bitmask: maxBrowsingLevel is the domain's ceiling (identical for every viewer on it, including one whose NSFW setting is off) |
useEntitlements | GET /api/v1/blocks/entitlements — the read half of the goods rail, scope goods:read:self. The reply is scoped server-side to your own appBlockId, so the scope is consent-EXEMPT and a read-only block needs no purchase power. Revoked entitlements are excluded server-side |
useGatedImages | GET /api/v1/blocks/gated-images |
useGenerationResources | GET /api/v1/blocks/generation-resources?ids= |
useGoodPurchase | POST /api/v1/blocks/goods/purchase — scope goods:purchase:self and a goods entry in your manifest; without both the endpoint answers 404. Same direct-fetch-on-the-validated-origin shape as useTip, and the buyer is always the token subject (the block never supplies a user id). The platform renders no confirmation for the purchase itself, so the confirm UI is yours. Its optional top-up on insufficient funds opens useBuzzPurchase — host UI, and the opposite money direction |
useHostOrigin | Keep — it is the validated base URL every direct fetch needs |
useImagePicker | Keep — host UI; Civitai opens the picker over the viewer's own posted and generated images in its own chrome, and the block receives only the pick. Page apps only. @civitai/sdk has no equivalent yet |
useImageUpload | Keep — host UI. (@civitai/sdk covers it as host.openImageUpload, usable on either credential — but that is still a bridge message, not a route.) |
useMediaUpload | Keep — a bridge message with no route. It sends OPEN_MEDIA_UPLOAD (the host's picker, or your own bytes with no picker), and the host stores the file as a private generation input; no /api/v1/blocks/* route accepts a media upload. Page apps only |
useNestedDocument | Local — fetches one of your own bundled documents into a srcdoc string; it never talks to the platform |
useOutputUnlock | Keep — host UI. It sends REQUEST_OUTPUT_UNLOCK, and the host reads the live workflow, decides what to offer and draws the unlock dialog in its own chrome; no /api/v1/blocks/* route unlocks an output |
usePersistGenerationSource | Keep — a bridge message with no route. It sends PERSIST_GENERATION_SOURCE, and the page host stores one of the app's own finished outputs as a private, scanned generation source as the signed-in viewer; no /api/v1/blocks/* route does this. Page apps only. @civitai/sdk has no typed wrapper, but BlockTransport.request('PERSIST_GENERATION_SOURCE', …) sends the same message |
usePublishGenerationOutputs | Stays on the bridge, by design |
useReactions | No route yet — GET_ENTITY_REACTIONS and SET_ENTITY_REACTION are bridge messages, and no /api/v1/blocks/* route reads or sets a reaction. The tickets it needs do come from REST: each image /api/v1/blocks/images, /api/v1/blocks/gated-images or /api/v1/blocks/collections/{id} serves to a signed-in viewer carries a reactTicket |
useRequestConsent | Keep — consent is host UI |
useRequestSignIn | Keep — host UI |
useResourceFile | Keep — a bridge message with no route. The page host resolves the file as the signed-in viewer and parses it in the viewer's tab; no /api/v1/blocks/* route serves a model file's contents. Page apps only. See Reading a workflow file |
useResourcePicker | Keep — host UI; a sandboxed frame cannot draw the picker |
useRunConfirmedStep | Keep — host UI; the job runs only after the viewer confirms its price in a dialog Civitai shows in its own chrome |
useRunTraining | Keep — host UI; the run starts only from the consent dialog Civitai shows in its own chrome |
useSaveImage | Keep — host UI; the host fetches from origins it allowlists |
useShareLink | Keep — host UI. It sends SHARE_LINK; the host builds the canonical link from its own origin and your app's slug, and copies it or opens the share sheet from the viewer's click; no /api/v1/blocks/* route makes a share link. Page apps only |
useTip | POST /api/v1/blocks/tip |
useTipAllowance | GET /api/v1/blocks/tip-allowance |
useUploadImageBytes | Keep — a bridge message with no route. It sends OPEN_IMAGE_UPLOAD with bytes, and the host stores, persists and scans the image; no /api/v1/blocks/* route accepts an image upload. Page apps only, and the token needs posts:write:self. See Posting from an app |
useViewer | GET /api/v1/blocks/me. Keeping the hook is not free: it is a GET_VIEWER bridge round trip on mount, not a snapshot read — but it is the authoritative self-read, where useBlockContext().viewer is the coarser BLOCK_INIT snapshot |
useWildcardPack | Not carried |
useWorkflowBatch | No batch route — the hook is one watch() and one cancel() per workflow id, with no server-side batch. Over REST, poll and cancel each id with /api/v1/blocks/workflows/{poll,cancel}; in @civitai/sdk, app.workflows.watch(id) (or wait(id)) and app.workflows.cancel(id) per id |
Keep your track() calls — and declare the events
useBlockAnalytics() sends TRACK_EVENT, and both hosts forward it: your events reach your app's analytics. An earlier version of this page said the calls were no-ops and could be deleted. That is no longer true, and deleting them loses data.
Two things to do when you port:
- Declare every event under
analytics.eventsin your manifest. Only declared events, with declared properties of the declared type, are recorded; an undeclared event is counted as a drop and its name is not stored. - Move the calls, don't drop them.
TRACK_EVENThas no REST route. If you are moving to@civitai/sdk,app.host.track(eventName, properties)sends the same message.
See Custom events for the declaration, the limits and where the numbers show up.
Reading and writing
For the document store, use @civitai/sdk's app.storage.collection(name) rather than a fetch through useApi. Only the SDK gets the data service, Civitai's faster storage path; a direct fetch to /api/v1/blocks/storage always goes to civitai.com. A React app on @civitai/blocks-react adds @civitai/sdk beside it (npm install @civitai/sdk@latest; 0.33.0 or later) and keeps its hooks for everything else.
Start both bridge clients in the same tick, before React renders. Each answers the host's first BLOCK_INIT, and the host stops sending it once one of them has answered, so a client that starts later never receives it: an initialize() called from a component after the hooks have connected waits out timeoutMs (10 s by default), then rejects with unavailable; if the hooks' client is the late one, the hooks never connect. Construct the hooks' client with getTransport() from @civitai/blocks-react (getTransport honours only its first call, so a dev harness that passes it options must still run first), and call initialize() with no token in the same module, the simplest way to keep both in one tick:
// src/platform/civitai.ts: imported by main.tsx before it renders
import { getTransport } from '@civitai/blocks-react';
import { initialize } from '@civitai/sdk';
getTransport(); // the hooks' bridge client, listening from now
export const civitai = initialize(); // the SDK's, listening in the same tickThe two packages keep separate bridge clients, so options a dev harness passes to the hooks' getTransport() do not reach the SDK's. Under dev:harness, allow the dev server's origin for @civitai/sdk too: set VITE_BLOCK_ALLOWED_PARENT_ORIGINS to it, or call getTransport({ allowedParentOrigins }) from @civitai/sdk before initialize(). Otherwise initialize() ignores the harness's BLOCK_INIT and rejects the same way.
// src/platform/entries.ts: a capability, named the way your app thinks about it
import { civitai } from './civitai';
interface Entry {
title: string;
body?: string;
}
export async function listEntries(cursor?: string) {
const app = await civitai;
// `entries` is a collection your manifest declares.
return app.storage.collection<Entry>('entries').list({ limit: 50, cursor });
}
export async function addEntry(entry: Entry) {
const app = await civitai;
return app.storage.collection<Entry>('entries').create(entry);
}The SDK owns the token, the 401 retry and the error envelope: a refusal is a StorageError with a code (error codes). Everything about collections, lists, conditional writes and limits is in Storing data. Its REST reference is for clients other than a block.
The legacy /api/v1/blocks/app-storage/* and /api/v1/blocks/shared-storage/* routes are shut down since 2026-11-10 and answer 410; do not port onto them.
For the other /api/v1/blocks/* routes, useApi above is the pattern. Routes are addressed by path, so a route the API gains needs no package release:
- Treat every refusal as a refusal. No route has a success shape that means "could not read", so branch on the error, never on an empty result. A missing cursor proves a scan completed only if you read it from the right place; otherwise you get a silent one-page truncation.
- Read
message ?? error. Block-scope middleware rejections carryerror; service-layer refusals carrymessage. Branch on the HTTP status.
Listing only rows the viewer wrote
The legacy shared-storage/list?mine=true filter is gone with its route. In the document store, list({ author: 'me' }) lists only the documents the signed-in viewer wrote (Lists). It needs a signed-in viewer: a signed-out one is refused sign_in_required, so check useBlockContext().viewer before you call it.
Reading a collection's items
GET /api/v1/blocks/collections/{id} (scope collections:read:self; a private collection also needs collections:read:private, and without it answers 404) answers { collection, items, nextCursor }, and returns only a collection's image and video items. Other items are dropped after the page is read, so a page can be short or empty while more remain: keep paging while nextCursor is present, never stop on a short page. Each item carries mediaId, type ('image' or 'video'), url, width, height, creator, nsfwLevel, a reactTicket when one could be signed, and:
| Field | Type | Meaning |
|---|---|---|
addedAt | string | null | When the item was added to this collection, as an ISO 8601 string (2026-03-04T05:06:07.000Z). This is not when the image itself was uploaded. Always present; null when the time is unknown. |
duration | number | The video's length in seconds, always greater than zero. Only on a 'video' item whose length is known. On an image, or a video of unknown length, the key is absent: never null or 0. Test for it with 'duration' in item. |
Host UI stays on the bridge
Only the host can draw this UI, so @civitai/blocks-react's hooks remain the path on either transport:
import { useResourcePicker } from '@civitai/blocks-react';
const { open } = useResourcePicker();
const picked = await open({ resourceType: 'Checkpoint' });
if (picked) {
console.log(picked.modelName, picked.versionId);
}A dismissal resolves to nothing chosen — that is an answer, not an error.
Do not do this
app.orchestration is not a replacement for the workflow routes
The block workflow routes delegate to procedures carrying the per-call Buzz budget, the per-viewer and per-app daily caps, the maturity clamp, and the app-block:<appId> attribution tag. app.orchestration is the raw orchestrator and has none of them.
On the default credential app.orchestration rejects before it sends (since @civitai/sdk@0.5.0). On an auth: "oauth" block the substitution type-checks, passes tests and reaches the orchestrator. Submit through /api/v1/blocks/workflows/*, which in @civitai/sdk is app.workflows. Those routes take the block token only, so an auth: "oauth" block cannot use them; see choosing your credential.
Likewise prefer POST /api/v1/blocks/workflows/query (app.workflows.list()) to orchestration.queryWorkflows({ tags }): the route forces the app tag from the token server-side, while the client trusts caller-supplied tags.
Testing
Move the fake to fetch, and record what was requested, not only what came back:
const calls: string[] = [];
globalThis.fetch = (async (input: RequestInfo | URL) => {
calls.push(String(input));
return new Response(JSON.stringify({ items: [], metadata: { nextCursor: null } }), {
status: 200,
headers: { 'content-type': 'application/json' },
});
}) as typeof fetch;Then assert on calls — the requests your app made, not just the values it rendered. A fixture that fits on one page cannot see a dropped cursor parameter.
For the document store, test against createFakeStorage instead of a faked fetch.
Keep your existing mock host for the calls that remain on the bridge — the resource picker, Buzz purchase, sign-in, publishing.
Known gaps
Document these as gaps; do not design around them yet.
| Gap | State |
|---|---|
useImageUpload / OPEN_IMAGE_UPLOAD | No REST twin, and deliberately so — it raises host UI. @civitai/sdk exposes it as host.openImageUpload (either credential), which is the same bridge message behind a different package. |
usePublishGenerationOutputs | Same shape, and staying on the bridge by design — host chrome is the consent control. @civitai/sdk's host.publishGenerationOutputs is the same message. |
useBlockAnalytics / TRACK_EVENT | No REST twin — a fire-and-forget bridge message, recorded only when the manifest declares the event. @civitai/sdk carries it as host.track. See Custom events. |
| Anonymous app-storage reads | REST returns 403 where the bridge resolved a read to null; handle both. |
useBuzzAccounts, useBuzzTransactions, useDailyCompensation, useWildcardPack | Not carried. |
Because of the first two, a block that uploads images or publishes generation outputs cannot reach zero bridge messages — by design.
Troubleshooting
initialize()throws on the default block token:@civitai/sdk0.4.0 refused that token; 0.5.0 and later accept it, and this page needs 0.14.0. Upgrade it.
Next
- Concepts → Transport models — the mental model.
- Hooks reference — the bridge surface, in full.
- Generation reference — what the bridge can and cannot do.
- How an app earns — the two money rails (digital goods and the per-generation author fee) behind the goods and Buzz hooks, and the
reason/codevalues every one of these routes can refuse with.