Reference
TypeScript SDK
@citron/sdk is a small client with no runtime dependencies. It runs on Node 18.17+, edge runtimes and in browsers, and ships as ESM and CommonJS.
Install#
The SDK is not on npm yet. We send it as a package tarball: ask us and we will share it with your team.
# Not on npm yet: install the package tarball we send you
npm install ./citron-sdk-0.1.0.tgz| Import | What it holds |
|---|---|
@citron/sdk | createClient, errors, types, generateTypes, and the webhook helpers. |
@citron/sdk/webhooks | verifyWebhook, constructWebhookEvent, signWebhookBody; nothing else, for the smallest edge bundles. |
@citron/sdk/next | citronTags and createRevalidateHandler for the Next.js App Router. |
Create a client#
import { createClient } from '@citron/sdk';
export const citron = createClient({
baseUrl: 'https://api.console.citronos.com', // "…/v1" is accepted too
apiKey: process.env.CITRON_API_KEY, // ck_pub_… (content and GraphQL only)
locale: 'bg', // flatten localized fields to Bulgarian
richtext: 'html', // html | json | both (API default: both)
orgSlug: 'your-org', // for contact, forms and booking helpers
timeoutMs: 10_000, // per attempt
retry: { retries: 2, baseDelayMs: 300, maxDelayMs: 10_000 }, // or false
cache: false, // true / { ttlMs } for an in-memory ETag cache
});| Option | Default | |
|---|---|---|
baseUrl | required | The API origin. A trailing /v1 is accepted. |
apiKey | none | ck_pub_… or ck_prev_…. Needed for content and GraphQL, not for contact, forms or booking. |
locale | none | Flatten localized fields to this locale on every content call. |
preview | false | Read drafts (status=draft). Needs a ck_prev_ key; with a ck_pub_ key the client refuses to start. |
richtext | API default (both) | html, json or both. |
orgSlug | none | Workspace slug for the contact and booking helpers. |
timeoutMs | 10000 | Per attempt; 0 disables. |
retry | { retries: 2, baseDelayMs: 300, maxDelayMs: 10000 } | Or false. |
cache | false | true revalidates with ETags; { ttlMs } also serves from memory for that long. |
headers, fetchOptions, fetch | none | Sent with every request; fetch replaces globalThis.fetch. |
Read content#
| Method | Calls | Returns |
|---|---|---|
collection(slug).list(options) | GET /v1/content/{slug} | { data, meta, nextCursor } |
collection(slug).get(slugOrId, options) | GET /v1/content/{slug}/{slugOrId} | The entry; throws on 404. |
collection(slug).find(slugOrId, options) | the same | The entry or null. |
collection(slug).single(options) | GET /v1/content/{slug} | A singleton’s document. |
collection(slug).all(options) | every page | An async iterator of entries. |
List options map onto the REST parameters: limit → pageSize, page or cursor, filter, sort, fields, populate, locale, richtext, preview, plus rawLocales: true to get { bg, en } maps even when the client has a locale. Every call also takes headers, signal and fetchOptions.
const { data, meta } = await citron.collection('products').list({
locale: 'en',
filter: {
category: 'station', // filter[category]=station
capacity: { gte: 5 }, // filter[capacity][gte]=5
code: { in: ['BIO-6', 'BIO-10'] }, // filter[code][in]=BIO-6,BIO-10
},
sort: '-publishedAt', // or { field: 'publishedAt', order: 'desc' }
page: 1,
limit: 20, // sent as pageSize
});
console.log(meta.total, data.length);Types from your collections#
The citron-sdk typegen command reads the collection definitions your key can see and writes a TypeScript file. Pass its map to createClient and collection slugs, fields, filters and populate are all checked by the compiler.
npx citron-sdk typegen \
--base-url https://api.console.citronos.com \
--api-key "$CITRON_API_KEY" \
--org your-org \
--out src/citron.generated.ts| Flag | Environment | |
|---|---|---|
--base-url | CITRON_BASE_URL | API origin. |
--api-key | CITRON_API_KEY | A delivery key of the workspace. |
--org | CITRON_ORG | Workspace slug (the key must belong to it). |
--out | Output file; - prints to stdout. Default citron.generated.ts. | |
--from | Read definitions from a saved JSON file instead of the API. |
import { createClient } from '@citron/sdk';
import type { CitronCollections } from './citron.generated';
const citron = createClient<CitronCollections>({
baseUrl: 'https://api.console.citronos.com',
apiKey: process.env.CITRON_API_KEY,
locale: 'en',
});
const { data } = await citron.collection('products').list({ filter: { category: 'station' } });
const name: string | null | undefined = data[0]?.data.name; // typed from the collection
// @ts-expect-error: a misspelt collection is a compile error
citron.collection('prodcts');Each collection gets a …Data type (localized fields flattened, what you get with locale) and a …Raw type (localized fields as CitronLocaleMap<T>, what you get with rawLocales: true). Live collections are skipped, since the delivery API does not serve them. Run the command again whenever a collection changes.
GraphQL#
citron.graphql(query, variables, options) resolves data and throws CitronGraphQLError when the response has errors. { persisted: true } sends the hash first and the query only when the API asks for it. See GraphQL.
// persisted: true does both steps for you and uses GET by default
const data = await citron.graphql<{ products: { data: { slug: string | null }[]; meta: { total: number } } }>(
'query ($n: Int) { products(pageSize: $n) { data { slug } meta { total } } }',
{ n: 10 },
{ persisted: true },
);
console.log(data.products.meta.total);Contact, forms and booking#
| Method | Calls |
|---|---|
submitContact(input, { turnstileToken, idempotencyKey, orgSlug }) | POST /v1/public/{orgSlug}/contacts |
forms.get(key) | GET /v1/forms/{key} (never cached) |
forms.submit(key, data, { renderToken, turnstileToken, referrer, utm }) | POST /v1/forms/{key}/submissions |
booking.types(), booking.slots(params), booking.book(input) | /v1/public/{orgSlug}/appointment-types, …/appointments/slots, …/appointments |
Each write sends an Idempotency-Key, generated when you do not pass one; pass your own to keep it across page reloads. See forms, contact and booking.
const types = await citron.booking.types({ orgSlug: 'your-org' });
const slots = await citron.booking.slots(
{ typeId: types[0].id, mode: 'online', from: new Date(), to: new Date(Date.now() + 14 * 86_400_000) },
{ orgSlug: 'your-org' },
);
const appointment = await citron.booking.book(
{
contact: { name: 'Ivan Petrov', email: 'ivan@example.com', phone: '+359888000000' },
appointmentTypeId: types[0].id,
staffUserId: slots[0].staffUserId,
mode: 'online',
startsAt: slots[0].startsAt,
},
{ idempotencyKey, orgSlug: 'your-org' },
);
console.log(appointment.id, appointment.status);Webhooks#
verifyWebhook(rawBody, signatureHeader, secret, { maxAgeSeconds }) returns true or false and compares in constant time. constructWebhookEvent verifies and parses in one step and throws WebhookVerificationError. Both use Web Crypto. See webhooks.
import { constructWebhookEvent, WebhookVerificationError } from '@citron/sdk/webhooks';
// Any runtime with Request/Response: Node 18+, edge, Workers
export async function handleCitronWebhook(req: Request): Promise<Response> {
const raw = await req.text(); // the RAW body: re-serialised JSON has different bytes
try {
const event = await constructWebhookEvent(raw, req.headers.get('x-citron-signature'), process.env.CITRON_WEBHOOK_SECRET!, {
maxAgeSeconds: 24 * 3600, // optional; the signed "at" makes old deliveries refusable
});
console.log(event.event, event.collection, event.entry.slug);
return new Response(null, { status: 204 });
} catch (err) {
if (err instanceof WebhookVerificationError) return new Response(null, { status: 401 });
throw err;
}
}Errors, retries and timeouts#
Every failure is a CitronError with status (0 when there was no response), code, message, requestId, details and retryAfter, plus isNotFound and isRetryable. The subclasses are CitronNetworkError, CitronTimeoutError and CitronGraphQLError.
import { CitronGraphQLError, isCitronError } from '@citron/sdk';
try {
await citron.collection('products').get('does-not-exist');
} catch (err) {
if (err instanceof CitronGraphQLError) {
console.error(err.errors, err.data); // GraphQL errors and partial data
} else if (isCitronError(err)) {
console.error(err.status, err.code, err.message, err.requestId, err.details);
if (err.isNotFound) { /* render your 404 */ }
if (err.isRetryable) { /* 0, 408, 429 or 5xx; err.retryAfter when the server said */ }
} else {
throw err;
}
}- Retries cover 408, 429, 500, 502, 503, 504 and network errors, with exponential backoff and jitter, for GETs, GraphQL and writes that carry an
Idempotency-Key. ARetry-Afterlonger thanmaxDelayMsthrows at once withretryAfterset. - The SDK’s own codes:
NETWORK_ERROR,TIMEOUT,CONFIG_ERROR,INVALID_CURSOR,INVALID_FILTER,INVALID_RESPONSE,GRAPHQL_ERROR. The API’s codes are listed on errors.
Next.js App Router#
Leave the SDK cache off and let Next.js cache: pass fetchOptions: { next: { revalidate, tags } } per call, tag with citronTags, and revalidate from a webhook.
// lib/citron.ts
import { createClient } from '@citron/sdk';
import { citronTags } from '@citron/sdk/next';
export const citron = createClient({
baseUrl: process.env.CITRON_BASE_URL!,
apiKey: process.env.CITRON_API_KEY!,
locale: 'bg',
richtext: 'html',
});
export const getProduct = (slug: string) =>
citron.collection('products').find(slug, {
populate: ['related'],
fetchOptions: { next: { revalidate: 3600, tags: citronTags('products', slug) } },
});Keys and runtimes#
- Keep keys in server environment variables. A
ck_pub_key only reads published content, but it is rate-limited per key, so a key in a public bundle lets anyone spend your budget. - Never send a
ck_prev_key to a browser: it reads every draft. - Contact, forms and booking need no key, so those helpers are safe in the browser.
- On a runtime without a global
fetch, pass one in the client config.
This reference covers the public API only and follows the API’s compatibility contract: public responses only ever gain fields. The OpenAPI description of these routes is at /developers/openapi.json.