> [Agent navigation index](/llms.txt)

# Contentful Clients

Use typed Delivery and Management clients for published or draft reads, content-model inspection, caching, retries, and incremental synchronization.

## Configure Delivery or Preview reads

First [generate your model types](/docs/contentful-typegen.md), declare the `CONTENTFUL_*` values in
your [environment schema](/docs/environment-schema.md), and configure the static server data cache
shown in [data cache policies](/docs/caching-policies.md). Import clients from the server-only
`brix/contentful/server` subpath and keep them in server-only modules; browser-safe types, guards,
`resolveLinks`, and direct contracts come from `brix/contentful`.
Create a request-derived service so credentials and timing follow the request context while reads
share the configured cache:

`src/contentful.server.ts`

```ts
import { createContentfulClient } from "brix/contentful/server";
import { brixServer } from "#brix/server";
import type { ContentTypeMap } from "#/contentful-types.ts";

export const getContentful = brixServer.createService((c) =>
  createContentfulClient<ContentTypeMap>({
    spaceId: c.env.CONTENTFUL_SPACE_ID,
    accessToken: c.env.CONTENTFUL_ACCESS_TOKEN,
    environment: c.env.CONTENTFUL_ENVIRONMENT,
    cache: brixServer.dataCache.public("1h"),
    timings: c.timings,
  }),
);

```

`createService` memoizes one client per request. Do not import this module back into
`src/brix.server.ts`; if server setup itself needs CMS data, create that client in an independent
server-only module.

If your server instead configures `dataCache: (c) => config`, use
`brixServer.dataCache(c).public("1h")`; that form creates a coordinator per request. Reuse the same
store and namespace when those coordinators should share persisted data.

This measures each native HTTP attempt under the `contentful` dependency through response-body
consumption. Cache and memory hits exclude upstream work; remote cache I/O is measured separately as
`cache.dynamodb` (including S3 overflow) or `cache.fastly`. For a shared cache flight, the initiator
owns upstream and cache-write spans while joiners own their own cache reads. Retry delays and schema
validation are excluded. Do not manually measure Contentful methods or attach the current request's
timing scope to a shared client; `createService` keeps the client request-scoped while lower-level
pools can remain shared.

`environment` defaults to `master`; `host` defaults to `cdn.contentful.com`. Set `host: "preview.contentful.com"` for draft reads. The equivalent EU Delivery and Preview hosts are supported. Non-loopback custom hosts must use HTTPS and require `allowCustomHostWithAccessToken: true`; reserve that opt-in for a trusted proxy. Loopback HTTP URLs are accepted for local mocks.

Invalid host or token policy throws while creating the client. Request methods return typed `ResultPromise` values, so use `.unwrap()`, `.unwrapOr()`, `.map()`, or `.match()` for expected outcomes.

## Query entries and assets

Call the request-derived client from a page loader, API route, or other server operation. In this
excerpt, `c` is that operation's Brix context, while `pageId` and `slug` are application inputs:

```ts
const contentful = getContentful(c);
const page = await contentful.getEntry("page", pageId, { locale: "en-GB" }).unwrap();
const hotel = await contentful
  .findEntry("hotel", { "fields.slug": slug, locale: "en-GB" })
  .unwrap();
const hotels = await contentful
  .getEntries("hotel", {
    locale: "en-GB",
    limit: 20,
    skip: 0,
    order: "-sys.createdAt",
    include: 3,
    "fields.city": "stockholm",
    "fields.stars[gte]": 4,
    "fields.amenities[in]": ["pool"],
  })
  .unwrap();
const asset = await contentful.getAsset("asset-id", { locale: "sv-SE" }).unwrap();
const related = await contentful
  .getEntries("hotel", {
    "sys.id[in]": ["hotel-1", "hotel-2"],
    "metadata.tags.sys.id[all]": ["featured"],
  })
  .unwrap();

```

Successful calls return generated, model-aware entry fields. `.unwrap()` turns an expected request
failure into a panic; use `match`, narrowing, or another Result operation when the caller should
render a not-found or provider-error state.

`getEntry` and `findEntry` return `ContentfulEntryNotFoundError` when absent; `findEntry` returns the first match of a `limit: 1` query. `getEntry` requests `include: 10`, Contentful's maximum link depth, unless you pass a smaller `include`; `getEntries` and `findEntry` send `include` only when you set it, so Contentful's default of one level applies. Collections preserve `total`, `skip`, `limit`, and includes metadata. Typed options cover locale, pagination, selection, ordering, full-text search, include depth, equality, range, list, match, existence, and known linked-field filters, including generated many-reference fields such as `fields.categories.sys.id`. System and metadata filters cover `sys.id` (with `[ne]`, `[in]`, and `[nin]`), `sys.createdAt` and `sys.updatedAt` ranges, `metadata.tags.sys.id[in|nin|all]`, `metadata.tags[exists]`, and the `links_to_entry` and `links_to_asset` reverse lookups. List values are arrays that Brix joins with commas.

`getAsset` reads the space's default locale unless you pass `locale`. A literal `locale: "*"`
returns a locale-mapped `SyncAsset`, for example `asset.fields.file["sv-SE"]`.

`getEntry`, `getEntries`, and `findEntry` accept typed readonly `select` arrays, not strings:

```ts
const selected = await contentful
  .getEntry("page", pageId, {
    locale: "*",
    include: 3,
    select: ["sys.id", "fields.slug", "fields.parentPage", "fields.publishInLanguage"],
  })
  .unwrap();

```

Brix preserves complete `sys` metadata for response validation and link resolution, replacing
narrower `sys.*` selections with `sys`. Include the reference fields whose links you need.
Fixed arrays narrow root `fields` to the selected keys and reject
unknown field names at compile time. Selected optional
fields stay optional, and wildcard locale maps are preserved. Linked-entry field types are not
projected by the root selection. Use `"fields"` to select all fields. A selection without any `fields` path, such as `["sys.id"]`,
returns entries with `fields: {}`.

Use `as const` for reusable arrays and pass them directly without `.join(",")`.
A variable-length typed array returns optional fields from its possible keys. Without `select`,
the full model is unchanged. Native caching separates
different selections; `cache: false` still bypasses it.

Generic wrappers can forward `GetEntriesOptions<T[K]>` and optional options without casts.
Broad `locale?: string` options retain a union of single-locale and all-locale field types.
Broad `select` options make fields optional. Preserve literal options when a wrapper needs precise
return types.

Entry reads automatically resolve included entry and asset links while preserving metadata. Collection items can link to other root items in the same response. Missing links become `null`. Included assets without a processed file yet,
such as fresh drafts on the Preview API, also resolve to `null` rather than failing the read. Sync remains unresolved by design.

Each root entry resolves at most the requested `include` levels of links: 10 for `getEntry` unless
you pass a smaller value, and Contentful's default of one level for `getEntries` and `findEntry`
when you omit `include`. A link beyond that depth becomes `null` even if its target is elsewhere in
the response, so request a deeper `include` when an adapter reads nested references. A link back to
an entry already being resolved on the same path, such as a self-link or `child.fields.parent`,
also becomes `null`, never a raw link object or a circular JavaScript object. This matches the
generated `IX | null` field types, so adapters handle one case.

Within one root, Brix resolves an entry once per remaining depth and reuses that object wherever
the entry appears at the same depth. Cycle cuts follow the first path that reached it: if
`root -> a -> c` resolves `c` first and cuts `c.fields.a`, then `root -> b -> c` sees the same
`c` with `a` set to `null`, even though `a` is not on that path. A shared entry can likewise hold a
resolved copy of an entry that is an ancestor on another path. This keeps resolution proportional to
depth times entries on densely linked content, so treat every link as possibly `null`.

Collection reads build entry and asset lookup indexes once per response, including native wire-cache
hits. Each root keeps separate traversal state: a cycle reached from one root does not truncate
another root's links. Resolved graphs are not cached across calls; the include bound keeps their
size proportional to the requested depth rather than to the collection.

With `locale: "*"`, entry reads preserve locale-keyed fields and resolve links inside each locale,
including nested parent entries, arrays, and Rich Text. Included assets retain their locale-keyed
fields too. No extra requests are made: the referenced resources must be in the response, within
the requested `include` depth. Ordinary JSON objects inside fields are not recursively resolved.
The client infers locale-mapped return types from a literal `locale: "*"`, recursively including
linked entries and assets. Each locale lookup can be `undefined` because translations may be
missing. JSON and location values stay intact inside their outer locale map. Omitted or specific
locale codes keep single-locale types; a dynamic `string`, an optional wildcard, or a union that
includes `"*"` returns a union of both shapes. Keep reusable wildcard options literal with
`{ locale: "*" } as const`, and branch before making the call when you need a precise return type
for a dynamic locale. Existing generated content-model types need no regeneration.
`ContentfulClient<ContentTypeMap>` is available for explicit service or dependency annotations.
Direct-contract consumers can call `resolveLinks(entry, includes, { locale: "*" })` explicitly.

Delivery calls retry 429, 500, 502, 503, and 504 by default, making three total attempts and honoring Contentful retry headers up to the 10-second `maxDelay` cap. When a header requests a longer
wait, such as an hourly rate-limit reset, the call returns that HTTP error immediately instead of
sleeping or retrying. Override the client `retry` option when the application's latency budget requires a different policy. The option replaces the whole default rather than merging with it: list every status in `on`, and set `maxAttempts` and `respectRetryAfter: true` again if you still want them (omitted `maxAttempts` means one attempt, and `maxDelay` defaults to 10 seconds).

## Bound and cancel reads

Set `timeout` in milliseconds on `createContentfulClient` for a default deadline. Entry, collection,
find, asset, `syncPage`, and `sync` options accept per-call `timeout` and `signal`:

```ts
const result = await getContentful(c).getEntries("page", {
  locale: "en",
  timeout: 2_000,
  signal: c.req.raw.signal,
});

```

The deadline includes cache waiting, HTTP body reads, retries and retry delays. `sync` shares one
deadline and caller signal across every page; it does not restart the budget for each continuation.
Sync still bypasses caching and returns no partial resources or checkpoint on failure. Cancelling
one cached read detaches that caller without cancelling a shared origin load needed by another caller.

Omission preserves the configured default; explicit per-call `timeout: undefined` clears it.
Without either timeout there is no Brix deadline. Values must be whole milliseconds from 0 through
2,147,483,647; zero schedules immediate expiry. Invalid values return `request-encoding` before
fetching. Cancellation returns `aborted`; expiry returns `timeout` with status 408. Neither can serve
stale fallback for that caller. Synchronous link resolution cannot be preempted. These options apply
to Delivery and Preview clients, not the separate Management client or webhook invalidation.

Native `ContentfulRequestError.kind` exposes the underlying API category: `request-encoding`,
`network`, `timeout`, `aborted`, `http`, `decode`, or `response-validation`. Check it rather than
classifying failures by status alone: decode errors can retain HTTP 200 and response-validation
errors use status 0. Every `ContentfulRequestError` requires a `kind`, including application-created
errors. Log selected categories/statuses, not complete errors, provider data, or causes.

Pass `request: { signal }` to `createContentfulClient` to cancel entry, collection, find, asset and
sync reads, including retries, cache waits and response-body consumption. Do not reuse this client
outside that request. The optional synchronous `request.onAttempt` runs before each actual HTTP
attempt; custom budget callbacks should abort their shared signal before throwing on exhaustion.
For signed adapter endpoints, use `request: getContentfulLoadingContext(c)?.request` from
`brix/contentful/server` in both canonical resolution and loader services. This shares the framework's deadline
and upstream attempt budget. Construct the clients during resolution/loading, after authentication
middleware; see [adapter limits](/docs/contentful-rendering.md).
Request-level and per-call signals both apply: cancelling one read detaches that caller, while
cancelling the request stops all its reads. Per-call options cannot bypass request cancellation.

## Cache Delivery reads

The `cache` option covers entry, collection, find, and asset reads. Cache identity includes the host, space, environment, credentials, locale, and complete query. Bypass an individual read with `{ cache: false }`.

Equivalent proxy base paths such as `/cda` and `/cda/` share cache identity and invalidation;
distinct hosts and base paths remain separate. Credentials partition cached reads, but
invalidation spans credentials for the same host, base path, space, and environment.

When configured with `request`, in-flight loads share only between clients using that same request
object. Cancelling/exhausting one request cannot fail another request's flight. Persisted values still
share by normal source/query/cache identity. Cache hits and same-request joiners do not consume an
upstream attempt. Requests without this option retain the normal cross-request flight sharing.

Preview, sync, and Management calls never use this cache. `invalidateCache()` invalidates all native Delivery reads for that host, space, and environment and automatically forwards the client's configured `timings` to the store operation. Use a shared store for replicas and [verified webhooks](/docs/contentful-webhooks.md) to trigger invalidation. This does not purge edge pages, browser data, or Contentful's CDN; see [caching](/docs/caching.md).

## Synchronize content incrementally

```ts
const initial = await contentful.sync(undefined, { type: "Entry", limit: 100 }).unwrap();
await applyResources(initial);
await saveSyncToken(initial.nextSyncToken);

const delta = await contentful.sync(initial.nextSyncToken, { limit: 100 }).unwrap();
await applyResources(delta);
await saveSyncToken(delta.nextSyncToken);

```

`sync` follows all continuation pages and returns raw `entries`, `assets`, `deletedEntries`, `deletedAssets`, and `nextSyncToken`. `type` applies only to the initial sync; a continuation token already carries its scope. The page `limit` is preserved across requests. Pass `undefined` to start an initial sync; an empty
token string returns `ContentfulSyncError` without a request instead of silently resynchronizing
everything.

If an upstream response repeats a page continuation token within one `sync` call, including the
supplied initial token, Brix returns `ContentfulSyncError` before requesting the page again.
No partial resources or new checkpoint are returned. Keep the saved checkpoint and investigate
the upstream response before retrying. Token values are not included in this error. An unchanged
final `nextSyncToken` is valid; only repeated page continuations are rejected.

`applyResources` and `saveSyncToken` are your persistence operations. Apply resource changes before
advancing the saved token, ideally in one transaction. Make updates idempotent so a failed token save
can safely replay the same delta. Saving a token first can skip changes after a crash.

Use `syncPage` only when the caller must own pagination:

```ts
let page = await contentful.syncPage({ type: "Entry", limit: 100 }).unwrap();
await applyResources(page);
while (page.nextPageToken !== null) {
  page = await contentful.syncPage({ syncToken: page.nextPageToken, limit: 100 }).unwrap();
  await applyResources(page);
}
await saveSyncToken(page.nextSyncToken);

```

Each page carries exactly one continuation: intermediate pages return `nextPageToken` with
`nextSyncToken: null`, and the final page returns `nextPageToken: null` with the `nextSyncToken` to
persist. Comparing `nextPageToken` with `null` narrows the final token to a `string`. Persist only
the final `nextSyncToken`. Both methods return resources already separated into `entries`,
`assets`, `deletedEntries`, and `deletedAssets`; sync output is not link-resolved.

## Inspect models with the Management client

Use the CMA client in server-side scripts, never in browser code:

```ts
import { createContentfulCmaClient } from "brix/contentful/server";
import { loadEnv } from "#brix/env/script";

const env = await loadEnv();
const cma = createContentfulCmaClient({
  spaceId: env.CONTENTFUL_SPACE_ID,
  accessToken: env.CONTENTFUL_CMA_TOKEN,
  environment: "master",
  includeDrafts: true,
});

const contentTypes = await cma.getContentTypes().unwrap();

```

Pagination is automatic. Omit `includeDrafts` to read published models; set it to `true` to include unpublished content types. `host` defaults to `api.contentful.com`; set `host: "api.eu.contentful.com"` for an EU data-residency space. Loopback URLs work for local mocks, and other HTTPS hosts require `allowCustomHostWithAccessToken: true`.

## Call the direct contracts

The clients are built on API contracts exported from browser-safe `brix/contentful`:
`getEntriesContract`, `getAssetContract`, and `syncContract` for the Delivery and Preview APIs, and
`getContentTypesContract` (published) and `getAllContentTypesContract` (including drafts) for the
Management API. Every path starts with `/spaces/:spaceId/environments/:environment`. Prefer the
typed clients: they add model types, link resolution, retries, caching, sync pagination, and typed
Contentful errors. Use a contract directly only when composing a request the clients do not offer:

```ts
import { getEntriesContract, resolveLinks } from "brix/contentful";
import { executeApi } from "#brix";

const result = await executeApi(getEntriesContract, {
  baseUrl: "https://cdn.contentful.com",
  headers: { Authorization: `Bearer ${accessToken}` },
  params: { spaceId, environment: "master" },
  query: { content_type: "page", include: 2, locale: "en-GB" },
});

const pages = result.map((collection) =>
  collection.items.map((entry) =>
    resolveLinks(entry, collection.includes ?? {}, { locale: "en-GB" }),
  ),
);

```

`spaceId` and `accessToken` come from server configuration; keep tokens out of browser bundles.
Direct calls return `ApiRequestError` failures rather than Contentful error classes, send `select`
as Contentful's comma-separated string, and leave links unresolved until you call `resolveLinks`.
`resolveLinks` has no depth bound; it nulls missing targets and cycle back-references.
Response validation checks the Contentful envelope and system metadata only; entry `fields` stay
`unknown` until an adapter or your own projection narrows them.
