Client SDK
@beechcms/client is the official TypeScript SDK for fetching, querying, and managing BeechCMS content across any JavaScript runtime (Next.js Server Components, Astro, Remix, Nuxt, Node.js, Cloudflare Workers, and mobile apps).
To ensure zero bundle bloat and eliminate frontend credential leakage, the SDK implements architectural submodule segregation into dedicated, purpose-built subpaths:
Every read goes through one entry point — client.collection(seed) — which returns a typed fluent query builder that compiles to the documented Public REST API query string. There is no second query language: .where(), .orderBy(), .include() and friends serialize into the same filter, orderBy, include parameters you could type by hand.
@beechcms/client/browser: Safe read-only client for client-side and browser environments. Mutation methods (create,update) are physically omitted from both types and bundle runtime.@beechcms/client/server: Read and write client with mutation operations (create,update) merged onto the same fluent builder, secret-key authentication, and advanced fetch options (nextcache tags, revalidation, AbortSignal). Deletion is intentionally omitted from public client scopes.@beechcms/client/webhooks: Dedicated, zero-dependency submodule for HMAC-SHA256 signature verification (verifyBeechWebhookSignature), error handling (WebhookVerificationError), and strongly typed event deserialization (constructWebhookEvent<T>).@beechcms/client/richtext: Isomorphic, zero-dependency TipTap AST HTML renderer (renderRichText/renderRichTextHtml), plain-text extractor (richTextToPlainText/extractPlainText), and AST normalizer/sanitizer utilities (normalizeRichtextDocument,escapeHtml,isSafeUrl).@beechcms/client: Root entrypoint exporting shared contracts, TypeScript types (BeechResult,BeechProblem,ListQuery,ListMeta,Listable,Single,RequestOptions,ListOptions,BeechClientBaseConfig,BeechBrowserClientConfig,BeechServerClientConfig), query serializer (buildSearchParams), canonical media URL builders (media,mediaSrcSet), and re-exporting webhook signature utilities.
Installation
pnpm add @beechcms/client
# or
npm install @beechcms/clientArchitecture & Submodule Overview
| Entrypoint | Primary Purpose | Environment | Exposed Operations / Utilities |
|---|---|---|---|
@beechcms/client/browser | Read-Only Client | Browsers, SPAs, Client Components, Mobile | createBeechBrowserClient(), createBeechClient(), collection() → .list() / .first() (no mutation methods) |
@beechcms/client/server | Read & Write Client | Node.js, Next.js Server Components, Workers | createBeechServerClient(), createBeechClient(), collection() → .list() / .first() / .create() / .update() |
@beechcms/client/webhooks | Webhook Verification | Node.js, Edge Runtimes, Serverless | verifyBeechWebhookSignature(), constructWebhookEvent<T>(), WebhookVerificationError, BEECH_SIGNATURE_HEADER |
@beechcms/client/richtext | TipTap AST Rendering | Universal (Node, Edge, Browser) | renderRichText(), renderRichTextHtml(), richTextToPlainText(), extractPlainText(), normalizeRichtextDocument(), escapeHtml(), isSafeUrl() |
@beechcms/client | Core Types & Contracts | Universal | buildSearchParams(), media(), mediaSrcSet(), BeechResult<T>, BeechProblem, RequestOptions, ListQuery, ListMeta, Webhook utilities |
Keys and roles
| Key | Client option | Allows | Configured in | Local value | Use from |
|---|---|---|---|---|---|
| Publishable | publishableKey | GET / HEAD / OPTIONS reads | wrangler.jsonc vars (committed) as BEECH_PUBLISHABLE_KEY | beech_pk_dev | Browser and server |
| Secret | secretKey | Reads and writes | .dev.vars locally as BEECH_SECRET_KEY; npx wrangler secret put BEECH_SECRET_KEY in production with a generated beech_sk_live_… value | beech_sk_dev | Server only |
The key authenticates and the seed authorizes: allowPublicRead / allowPublicEdit still apply to both keys. allowPublicPost gates anonymous form submissions only: the secret key creates entries without it. See the permission model.
A new project serves beech_pk_dev in production too, unless you change BEECH_PUBLISHABLE_KEY. This is safe because the key is read-only.
Server code that only reads can use the browser client with the publishable key.
WARNING
Never pass the secret key to browser code or to a NEXT_PUBLIC_ / VITE_ / PUBLIC_ variable. createBeechBrowserClient throws when publishableKey starts with beech_sk_, and the browser client has no create / update (a compile-time error). The API refuses beech_sk_dev outside ENV=development (403 public-api-dev-secret-key).
Migrating from apiKey
apiKey was removed. Passing it throws apiKey was removed: pass publishableKey to createBeechBrowserClient (or secretKey / createBeechServerClient). For the Worker side, see moving a 0.10.x project to publishable and secret keys.
Browser Client (@beechcms/client/browser)
The browser entrypoint is strictly read-only. It is designed for client-side web applications where the publishable key is safe to expose, but mutation endpoints and write credentials must never be bundled.
Quick Start
import { createBeechBrowserClient } from '@beechcms/client/browser'
// Alternatively: import { createBeechClient } from '@beechcms/client/browser'
export const beech = createBeechBrowserClient({
baseUrl: process.env.NEXT_PUBLIC_BEECH_API_URL || 'https://api.yourdomain.com',
publishableKey: process.env.NEXT_PUBLIC_BEECH_PUBLISHABLE_KEY!,
})NOTE
baseUrl and publishableKey are required non-empty strings. Omitting one, passing apiKey, or passing a beech_sk_ value throws when the client is created.
1. List Entries with Filters & Pagination
// Fetch published articles in descending chronological order
const result = await beech
.collection('articles')
.where({ status: 'published', category: 'technology' })
.orderBy('created_at', 'desc')
.limit(10)
.page(1)
.list()
if (!result.error) {
const { data: posts, meta } = result.data
console.log(`Loaded ${posts.length} of ${meta.total} posts:`, posts)
} else {
// Normalized RFC 9457 problem details
console.error(`Error (${result.error.status}): ${result.error.title} - ${result.error.detail}`)
}2. Fetch a Single Entry by Slug or ID
.first() applies limit=1 and unwraps the list response into a Single<T>:
// Lookup by URL slug
const slugResult = await beech.collection('articles').where({ slug: 'spring-release' }).first()
// Lookup by UUID
const idResult = await beech
.collection('articles')
.where({ id: 'c7a82e9b-4321-4f8a-92bf-304918239012' })
.first()
if (!slugResult.error) {
const post = slugResult.data.data
console.log(post.title, post.body)
}IMPORTANT
An empty result is not null: .first() returns a 404 BeechProblem with type: 'not_found'. Branch on result.error?.status === 404 to tell "no match" apart from a transport or authorization failure.
Fluent Query Builder
collection(seed) returns a FluentQuery<TRow>. Every method returns the same builder (chainable, mutating — one builder is one query), and nothing is sent until .list() or .first() is awaited.
Method reference
| Method | Compiles to | Notes |
|---|---|---|
.where(filter) | filter (JSON {logic, where[]}) | Repeated calls merge field-by-field |
.logic('AND' | 'OR') | filter.logic | Combines every condition in the chain. Default AND |
.whereRelation(alias, subquery) | nested in condition inside filter | Filters through a relation target — see below |
.orderBy(field, 'asc' | 'desc') | orderBy + orderDir | Single sort key; a second call replaces the first. Direction defaults to desc |
.search(term) | search | Full-text search across searchable branches |
.select(fields) | fields | Projection; typed against keyof TRow |
.include(relations) | include | Relation expansion, depth 1, max 3 branches |
.limit(n) | limit | Clamped to 100 by the serializer |
.page(n) | page | 1-based |
.lang(code) | lang | Response language for localized fields — a locale code or 'all'. See Localization |
.list(options?) | GET /api/v1/public/:seed | Resolves BeechResult<Listable<TRow>> |
.first(options?) | same, with limit=1 | Resolves BeechResult<Single<TRow>> |
.build() | — | Returns the URLSearchParams without issuing a request. Useful for debugging and cache keys |
// Inspect exactly what the chain sends — no request is made
const params = beech.collection('articles').where({ views: { gte: 100 } }).orderBy('views').build()
console.log(params.toString())
// filter=%7B%22logic%22%3A%22AND%22%2C%22where%22%3A%5B...&orderBy=views&orderDir=descSupported Filter Operators
.where() accepts a { field: comparator } map. Comparators support the following operators:
| Operator | Description | Example |
|---|---|---|
eq / neq | Equal / Not equal | { status: { eq: 'published' } } |
gt / gte | Greater than / Greater than or equal | { views: { gte: 100 } } |
lt / lte | Less than / Less than or equal | { price: { lte: 50 } } |
contains / not_contains | Substring match | { title: { contains: 'Release' } } |
starts_with / ends_with | String prefix / suffix | { slug: { starts_with: 'guide-' } } |
in / not_in | Set inclusion | { category: { in: ['news', 'updates'] } } |
is_empty / is_not_empty | Null or empty check | { coverImage: { is_not_empty: true } } |
has_tag / has_any_tag / has_all_tags | Tag containment | { tags: { has_any_tag: ['typescript', 'api'] } } |
TIP
Scalar Equality Shorthand: For simple equality filters, you can pass scalar values directly (e.g. { status: 'published' } is automatically expanded to { status: { eq: 'published' } } by the query builder).
An invalid operator ({ price: { bogus: 1 } }) throws a TypeError at serialization time — before any request leaves the process.
// Combine several axes in one chain
const result = await beech
.collection('articles')
.where({ views: { gte: 100 }, tags: { has_any_tag: ['typescript', 'api'] } })
.search('edge rendering')
.select(['id', 'title', 'slug', 'views'])
.orderBy('views', 'desc')
.limit(20)
.list()Relation Expansion (.include())
.include() asks the server to resolve related entries in the same round trip, removing the N+1 follow-up requests. Expanded targets arrive under _includes on each entry, keyed by relation alias — the raw foreign-key value stays untouched at the root:
const result = await beech
.collection('posts')
.where({ slug: 'my-first-post' })
.include(['category_id', 'related_posts'])
.first()
if (!result.error) {
const post = result.data.data as Post & {
_includes?: { category_id?: Category; related_posts?: Post[] }
}
post.category_id // ' 8a01f92e-…' — the raw id, always present
post._includes?.category_id?.name // 'Technology' — the expanded target
}Server-side limits (enforced, not clamped silently):
- Depth 1 only —
include(['category_id.author'])is refused with400 invalid-include. - Max 3 branches per request.
- Public policy gate — a branch expands only if its resolved policy is public and the target seed sets
allowPublicRead: true. Expansion never widens what an API key may read. - Works alongside
.select(): omitting the foreign key from the projection still populates_includes.
_includes is not yet part of the generated row types; cast or extend the row type as shown until the schema generator publishes the relation → target map.
Localization (.lang())
For seeds with localized fields, .lang(code) picks the response language. Localized fields then come back as plain values in that language, and .where() / .orderBy() on them compare in it:
const result = await beech
.collection('products')
.where({ slug: 'trail-shoe' })
.lang('en')
.first()
if (!result.error) {
result.data.data.name // 'Trail shoe' — or the default-locale value if no English translation exists
}- Fallback, not failure. A missing translation falls back to the project default locale (then to any stored translation). A well-formed code the project does not register falls back the same way, so a stale
.lang('fr')keeps rendering. A malformed code (.lang('english')) resolves to a400 invalid-langproblem. - Without
.lang()the server negotiates fromAccept-Language, then the default locale. In the browser,fetchsends the visitor'sAccept-Languageautomatically; on the server, forward it withRequestOptions.headers. - Which language was served? Single-language responses carry
Content-Language..list()results expose it onresult.headers?.get('Content-Language'). - Every language.
.lang('all')returns each localized field as a{ locale: value }dictionary. Generated row types describe the single-language shape (stringfor a localizedtextfield), so cast the row when you use'all'.
// Server-side rendering: follow the visitor's browser language
const list = await beechAdmin
.collection('products')
.limit(20)
.list({ headers: { 'Accept-Language': request.headers.get('Accept-Language') ?? '' } })
// Build a language switcher from every translation
const all = await beech.collection('products').where({ slug: 'trail-shoe' }).lang('all').first()
const names = (all.data?.data as unknown as { name: Record<string, string> } | undefined)?.name
// { it: 'Scarpa da trail', en: 'Trail shoe' }Writing translations. create() and update() accept a plain value (stored as the default-locale translation) or a dictionary for each localized field. Writes merge: locales you do not name are kept, and { fr: null } clears one locale. update() has no .lang(); pass Accept-Language in RequestOptions.headers to choose the language of the echoed data. With a generated registry, cast the dictionary input, since the row types model the single-language shape:
const result = await beechAdmin.collection('products').update(
'550e8400-e29b-41d4-a716-446655440000',
{ name: { en: 'Trail running shoe' } },
{ headers: { 'Accept-Language': 'en' } },
)
if (result.error?.status === 409) {
// entry-update-conflict: a concurrent write changed the entry — re-read and retry
}See Public API → Localization for the full negotiation and merge rules.
Filtering Through a Relation (.whereRelation())
.whereRelation(alias, { where, logic }) filters the collection by a condition evaluated against the target of a declared relation branch — a server-side subquery, not a client-side second pass:
// Posts whose category is named "Tech"
const { data } = await beech
.collection('posts')
.whereRelation('category_id', { where: { name: 'Tech' } })
.list()
// Composes with ordinary conditions in the same filter payload
const recent = await beech
.collection('posts')
.where({ status: 'published' })
.whereRelation('author_id', { where: { name: { contains: 'Jane' } }, logic: 'AND' })
.orderBy('created_at', 'desc')
.list()It encodes into the existing filter parameter as a nested in condition, so no new query grammar reaches the server. Limits mirror Relation Subquery Filters:
- Max 2 relation subqueries per request; each inner
wherecarries at most 5 conditions. - Depth 1 — a subquery inside a subquery returns
400. - Resolved target-id sets above 200 (or parent sets above 500) are refused with
400, never truncated. - The inner query resolves against published entries only.
NOTE
.whereRelation() types the alias against the row's own keys, but the inner where field names are Record<string, FieldFilter> — validated server-side, not at compile time, since the server does not yet publish a relation → target-seed type map.
Server Client (@beechcms/client/server)
The server entrypoint is intended for secure backend environments (Next.js Server Actions, Route Handlers, Astro endpoints, Cloudflare Workers, Node.js scripts). It includes write capabilities (create, update) and supports runtime RequestOptions (e.g., Next.js caching and revalidation tags).
Quick Start
import { createBeechServerClient } from '@beechcms/client/server'
// Alternatively: import { createBeechClient } from '@beechcms/client/server'
export const beechAdmin = createBeechServerClient({
baseUrl: process.env.BEECH_API_URL || 'https://api.yourdomain.com',
secretKey: process.env.BEECH_SECRET_KEY!,
})NOTE
Requests sent with the secret key skip the Time-Trap and honeypot checks. Seed flags still apply. Anonymous browser forms use the dedicated Forms SDK (@beechcms/forms-react) with no key.
1. Creating Content (create)
Submits a POST request to /api/v1/public/:seed/add:
const result = await beechAdmin.collection('articles').create({
title: 'Announcing BeechCMS 1.0',
slug: 'announcing-beechcms-1-0',
category: 'news',
status: 'published',
body: {
type: 'doc',
content: [
{
type: 'paragraph',
content: [{ type: 'text', text: 'Welcome to BeechCMS!' }],
},
],
},
})
if (!result.error) {
console.log('Created article with ID:', result.data.data.id)
} else {
console.error('Validation or server error:', result.error.errors || result.error.detail)
}2. Updating Content (update)
Submits a PUT request to /api/v1/public/:seed/edit/:id:
const result = await beechAdmin.collection('articles').update(
'c7a82e9b-4321-4f8a-92bf-304918239012',
{
title: 'Announcing BeechCMS 1.0 (Updated)',
},
)
if (!result.error) {
console.log('Updated article successfully:', result.data.data)
}3. Request Options & Next.js Revalidation
RequestOptions configures Next.js cache revalidation tags, fetch cache modes, abort signals, and custom HTTP headers. The query itself lives in the chain, so options are the only argument the terminal methods take:
.list(options?)and.first(options?)— options are the sole argument..create(input, options?)— second argument..update(id, input, options?)— third argument.
// Revalidation on a fluent read
const result = await beechAdmin
.collection('articles')
.where({ status: 'published' })
.limit(20)
.list({
next: {
revalidate: 3600, // Revalidate every hour in Next.js
tags: ['articles'],
},
headers: {
'X-Custom-Client': 'Website-SSR',
},
signal: AbortSignal.timeout(5000), // 5-second abort signal
})
// Custom audit header with .update() (third argument)
const updateResult = await beechAdmin.collection('articles').update(
'c7a82e9b-4321-4f8a-92bf-304918239012',
{ title: 'Announcing BeechCMS 1.0 (Patched)' },
{ headers: { 'X-Audit-Reason': 'editorial-fix' } },
)Type Safety & Generics
The client takes a Seed registry generic: a map of seed slug → row interface. collection() restricts its argument to the registry keys, and .select() / .orderBy() restrict theirs to the keys of the selected row.
Recommended: generate the registry from live D1
Do not hand-maintain the registry. beech types generate introspects the deployed schema and writes beech.generated.ts, exporting BeechDatabase (aliased as SeedRegistryTypes) plus a SCHEMA_FINGERPRINT constant:
npx beech types generate # → beech.generated.ts (local D1)
npx beech types generate --remote -o src/types/beech.tsimport { createBeechBrowserClient } from '@beechcms/client/browser'
import { SCHEMA_FINGERPRINT, type BeechDatabase } from './beech.generated'
export const beech = createBeechBrowserClient<BeechDatabase>({
baseUrl: process.env.NEXT_PUBLIC_BEECH_API_URL!,
publishableKey: process.env.NEXT_PUBLIC_BEECH_PUBLISHABLE_KEY!,
schemaFingerprint: SCHEMA_FINGERPRINT,
})
await beech.collection('artciles') // ✗ compile error — not a seed slug
await beech.collection('articles').select(['titel']) // ✗ compile error — not a branch aliasGenerated types go stale the moment someone applies a schema change. Pass the generated SCHEMA_FINGERPRINT as schemaFingerprint (both clients accept it) and every response whose X-Schema-Revision header differs returns a 409 problem with type: 'schema_drift' instead of data typed against the old schema. Without schemaFingerprint the check is off.
TIP
The runtime check fires only once a request is made. Guard drift in CI as well: beech types check regenerates in memory and fails on mismatch, without touching the working tree:
npx beech types check --remote -o src/types/beech.ts # exits 1 when committed types are staleFor manifest-vs-deployed drift, npx beech schema diff already exits 1 on its own.
Hand-written registry (dynamic or partial schemas)
import type { TipTapDoc, RichtextEnvelopeV1 } from '@beechcms/client/richtext'
import { createBeechBrowserClient } from '@beechcms/client/browser'
// 1. Define content models
export interface Article {
id: string
slug: string
title: string
category: string
body: TipTapDoc | RichtextEnvelopeV1
cover_image?: string
views: number
status: 'draft' | 'published'
created_at: number
}
export interface Author {
id: string
name: string
bio?: string
}
// 2. Define the Seed registry map
export interface AppContentRegistry {
articles: Article
authors: Author
}
// 3. Initialize typed client
export const beech = createBeechBrowserClient<AppContentRegistry>({
baseUrl: 'https://api.yourdomain.com',
publishableKey: process.env.NEXT_PUBLIC_BEECH_PUBLISHABLE_KEY!,
})
// Types are automatically inferred!
const listRes = await beech.collection('articles').where({ status: 'published' }).list()
if (!listRes.error) {
// listRes.data.data is typed as Article[]
const firstTitle = listRes.data.data[0].title
}NOTE
The typed surface stops at the row: .where() field names and .whereRelation() inner conditions are Record<string, FieldFilter>, validated server-side. Untyped JavaScript consumers can omit the generic entirely — collection() then accepts any string and returns Record<string, unknown> rows.
Webhook Signature Verification (@beechcms/client/webhooks)
BeechCMS sends HMAC-SHA256 signatures in the x-beechcms-signature header on automation webhook events. The @beechcms/client/webhooks submodule provides constant-time, zero-dependency cryptographic verification implemented entirely via standard Web Crypto (crypto.subtle).
Methods & Constants
constructWebhookEvent<T>(options): Verifies the HMAC-SHA256 signature and returns the deserialized JSON payload typed asT. ThrowsWebhookVerificationErrorif the signature is invalid or secret/payload is missing.verifyBeechWebhookSignature(options): ReturnsPromise<boolean>in constant time (timingSafeEqual). Never throws runtime exceptions on invalid signatures or malformed inputs.BEECH_SIGNATURE_HEADER: Constant string'x-beechcms-signature'.
Example: Next.js App Router Webhook Route Handler
// app/api/webhooks/beech/route.ts
import {
BEECH_SIGNATURE_HEADER,
constructWebhookEvent,
WebhookVerificationError,
} from '@beechcms/client/webhooks'
interface ArticleWebhookPayload {
event: 'entry.created' | 'entry.updated' | 'entry.published'
seed: string
entry: {
id: string
slug: string
title: string
}
}
export async function POST(request: Request) {
const signature = request.headers.get(BEECH_SIGNATURE_HEADER)
const rawPayload = await request.text()
try {
const event = await constructWebhookEvent<ArticleWebhookPayload>({
payload: rawPayload,
signature,
secret: process.env.BEECH_WEBHOOK_SECRET!,
})
console.log(`Verified webhook event "${event.event}" for entry:`, event.entry.id)
// Trigger on-demand revalidation or sync
return Response.json({ received: true })
} catch (error) {
if (error instanceof WebhookVerificationError) {
return new Response(`Unauthorized: ${error.message}`, { status: 401 })
}
return new Response('Invalid webhook payload', { status: 400 })
}
}TipTap RichText Rendering (@beechcms/client/richtext)
BeechCMS stores RichText fields as TipTap AST JSON trees wrapped in Botanical schema envelopes ({ schemaVersion: 1, doc: { ... } }).
The @beechcms/client/richtext submodule is an isomorphic, zero-dependency renderer that transforms TipTap ASTs into sanitized, semantic HTML and plain text without requiring @tiptap/html, ProseMirror, or synthetic DOM polyfills (jsdom). It runs universally on Cloudflare Workers, Node.js, and browsers.
Features & Security Invariants
- Fail-Safe Normalization: Automatically unwraps schema envelopes (
{ schemaVersion: 1, doc }) and raw doc objects. Invalid inputs gracefully return"". - Automatic XSS Protection: Strict character escaping (
&,<,>,",') and strict URL protocol validation (http:,https:,mailto:,tel:, or relative paths, blockingjavascript:anddata:schemes). - Full AST Support: Headings (
h1–h6, withtextAlignsupport), paragraphs, blockquotes, code blocks (<pre class="richtext-code-block"><code>), lists (bullet, ordered, task lists with checkboxes), tables (headers, rows, cells, colspan, rowspan), horizontal rules, line breaks (hardBreak), images (with safesrc,alt, andtitle), and formatting marks (bold/strong,italic/em,underline/u,strike/s,code,link,highlight,superscript,subscript, andtextStylecolors).
API Reference
import {
renderRichText,
renderRichTextHtml, // Functional alias for renderRichText
richTextToPlainText,
extractPlainText, // Functional alias for richTextToPlainText
normalizeRichtextDocument, // Validates and extracts AST doc from raw value or envelope
escapeHtml, // Strict HTML character escaping
isSafeUrl, // Strict protocol safety validator
RICHTEXT_SCHEMA_VERSION, // Schema version constant (1)
} from '@beechcms/client/richtext'
import type {
TipTapDoc,
TipTapNode,
TipTapMark,
TipTapMarkType,
RichtextEnvelopeV1,
} from '@beechcms/client/richtext'1. Rendering Semantic HTML (renderRichText / renderRichTextHtml)
// app/blog/[slug]/page.tsx
import { beech } from '@/lib/beech'
import { renderRichText } from '@beechcms/client/richtext'
export default async function BlogPostPage({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params
const result = await beech.collection('articles').where({ slug }).first()
if (result.error) return <div>Post not found</div>
const post = result.data.data
const htmlContent = renderRichText(post.body)
return (
<article className="prose max-w-2xl mx-auto py-8">
<h1>{post.title}</h1>
<div dangerouslySetInnerHTML={{ __html: htmlContent }} />
</article>
)
}2. Extracting Clean Plain Text (richTextToPlainText / extractPlainText)
Extracts unformatted text with whitespace separation between block elements, stripping tags and metadata. Ideal for generating SEO meta descriptions, OpenGraph summaries, and RSS feeds:
import { richTextToPlainText } from '@beechcms/client/richtext'
const rawAst = post.body // TipTap AST or Envelope V1
const plainSnippet = richTextToPlainText(rawAst)
// Output clean snippet:
console.log(plainSnippet)
// => "Welcome to BeechCMS. In this article, we explore modern headless architecture..."
// Perfect for Next.js metadata:
export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params
const result = await beech.collection('articles').where({ slug }).first()
if (result.error) return { title: 'Not Found' }
const snippet = richTextToPlainText(result.data.data.body).slice(0, 160)
return {
title: result.data.data.title,
description: snippet,
}
}Media URL Builders (media & mediaSrcSet)
The root @beechcms/client package provides zero-dependency URL builders for generating canonical media transformation URLs and responsive srcset strings for BeechCMS media routes:
1. Generating Canonical Variant URLs (media)
media(keyOrUrl, options) generates the deterministic, canonical query URL for named presets. It cleans up redundant defaults (format=original, quality=medium) and prevents parameter permutation attacks:
import { media } from '@beechcms/client'
// Root-relative URL: "/api/media/1717000000-a1b2c3d4-photo.jpg?preset=card"
const cardUrl = media('1717000000-a1b2c3d4-photo.jpg', { preset: 'card' })
// Absolute URL with format & quality:
// "https://api.yourdomain.com/api/media/1717000000-a1b2c3d4-photo.jpg?preset=card&format=webp&quality=high"
const webpUrl = media('1717000000-a1b2c3d4-photo.jpg', {
baseUrl: 'https://api.yourdomain.com',
preset: 'card',
format: 'webp',
quality: 'high',
})2. Generating Responsive srcset Attributes (mediaSrcSet)
mediaSrcSet(keyOrUrl, presets, options) builds an ordered, de-duplicated srcset string using scale presets (w-<width>):
import { media, mediaSrcSet } from '@beechcms/client'
export function ArticleImage({ assetKey }: { assetKey: string }) {
return (
<img
src={media(assetKey, { preset: 'card', format: 'webp' })}
srcSet={mediaSrcSet(assetKey, ['w-640', 'w-1280', 'w-1920'], { format: 'webp' })}
sizes="(max-width: 768px) 100vw, 640px"
alt="Article cover"
loading="lazy"
/>
)
}NOTE
mediaSrcSet accepts only scale presets (w-<width>). Supplying a fixed crop preset (like card or thumbnail) throws a TypeError, preventing misleading intrinsic width descriptors. For details on available presets and edge cache behavior, see Media Engine Reference.
Result Handling & RFC 9457 Problem Details
Both @beechcms/client/browser and @beechcms/client/server encapsulate network errors into a deterministic BeechResult<T> discriminated union ({ data: T; error: null } | { data: null; error: BeechProblem }). Requests never throw unexpected network exceptions:
const result = await beech.collection('articles').list()
if (!result.error) {
// TypeScript narrows result to: { data: Listable<Article>, error: null }
console.log(result.data.data)
} else {
// TypeScript narrows result to: { data: null, error: BeechProblem }
console.error('HTTP Status:', result.error.status)
console.error('Title:', result.error.title)
console.error('Detail:', result.error.detail)
// Validation errors array from 422 responses
if (result.error.errors) {
result.error.errors.forEach((err) => console.error(`${err.field}: ${err.message}`))
}
}Exactly one of data and error is set. Two client-side problem types complete the server's codes:
type | status | When |
|---|---|---|
about:blank with title Network Error | 0 | fetch itself failed (offline, DNS, CORS). |
invalid-response | the HTTP status (usually 200) | A successful response without a JSON body. The usual cause is a baseUrl that points at the dashboard (/admin) or at a site that answers every path with HTML; detail names the URL and the content type received. |
Related Guides
- Forms SDK (@beechcms/forms-react) — Interactive React form components and hooks with zero-secret invisible anti-bot defenses.
- Public REST API — Direct HTTP endpoints, query parameter specifications, and authentication headers.
- Automations & Webhooks — Triggering webhooks and notifications on content mutations.