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

# Contentful Live Preview

Give editors a protected, standalone preview for adapter-backed entries, with inspector attributes and live updates from Contentful's official SDK.

Complete [rendering adapter setup](/docs/contentful-rendering.md) first. You need a Contentful Preview
API token, a separate randomly generated preview secret, and a preview URL reachable from the
editor's browser. This integration previews an individual entry with its adapter; it does not
reconstruct an arbitrary application's full page and request state.

## Enable the preview entry

Enable the generated browser integration:

`vite.config.ts`

```ts
import { defineBrixConfig } from "brix/vite";

export default defineBrixConfig({ contentfulPreview: true });

```

Configure credentials only on the server, through the preview integration from the server-only
`brix/contentful/server` subpath:

`src/brix.server.ts`

```ts
"use server";

import { createContentfulPreviewIntegration } from "brix/contentful/server";
import type { Context } from "brix/hono";
import { defineBrixServer } from "brix/server";
import { brix } from "./brix.ts";
import type { CoercedEnvSchema } from "./env.generated.d.ts";
import { env } from "./env.server.ts";

type ServerContext = Context<{ Bindings: Readonly<CoercedEnvSchema> }>;

export const brixServer = defineBrixServer(brix, {
  env,
  integrations: [
    createContentfulPreviewIntegration((c: ServerContext) => ({
      accessToken: c.env.CONTENTFUL_PREVIEW_TOKEN,
      secret: c.env.CONTENTFUL_PREVIEW_SECRET,
      spaceId: c.env.CONTENTFUL_SPACE_ID,
      targetOrigin: "https://app.contentful.com",
      timeout: 5_000,
    })),
  ],
});

```

TypeScript cannot infer the server's request context inside the nested factory call, so an
unannotated callback receives Hono's untyped `Context` (`c.env` is `any`). Annotate the parameter as
shown to type `c.env`; static options need no annotation. Integrations mount in array order, each one
may appear once, and `defineBrixServer` rejects objects that an integration factory did not create.
The Preview and client-loading integrations work in either order.

Both halves are required: enabling only one side fails with a message naming the missing
`contentfulPreview: true` or `createContentfulPreviewIntegration()`, and Preview also requires at
least one discovered adapter module.

Use static options for one space or a callback for request-specific tenants. Static options are
validated when the integration is created, for example
`[createContentfulPreviewIntegration] accessToken must not be empty`; callback results are validated
on first use in each preview request. The callback runs only for the preview route. The options are:

- `spaceId`, `secret`, and (in fixture mode) `accessToken` — required and nonempty.
- `targetOrigin` — one HTTPS origin or an array of origins allowed to frame the preview. It
  defaults to `https://app.contentful.com` and `https://app.eu.contentful.com`; set it when editors
  use another Contentful host.
- `host` — a trusted Preview API endpoint instead of `preview.contentful.com`. Custom token hosts
  also require `allowCustomHostWithAccessToken: true`, as for the Delivery client.
- `assetsUrl` — passed to adapter components as `assetsUrl` in the preview.
- `timeout` — a fixture-mode read deadline, described below.
- `loaders: true` — opt into saved-draft loaders, described in
  [Load saved draft data](/docs/contentful-preview.md#load-saved-draft-data).

The Contentful environment and locale come from the preview URL, not from these options. The
preview route always sends a Content-Security-Policy `frame-ancestors` directive limited to the
target origins, even when `contentSecurityPolicy: false` disables the application's own policy, and
omits `X-Frame-Options` only on that route.

The optional `timeout` applies to fixture-mode Preview API reads (`loaders` omitted or `false`). It
uses the [native client deadline](/docs/contentful-client.md#bound-and-cancel-reads), including body reads
and retries; omission preserves the existing no-deadline default. The route forwards its request's
abort signal to the native read. A failed upstream read still produces the sanitized preview failure
response; no provider details or credentials are exposed. This option is not available with
`loaders: true` and does not change real-loader budgets.

## Configure Contentful preview URLs

Configure each supported content type with its literal content type ID:

```text
https://example.com/_/contentful/preview/{locale}/{env_id}/card/{entry.sys.id}?secret=<CONTENTFUL_PREVIEW_SECRET>

```

Contentful replaces `{locale}`, `{env_id}`, and `{entry.sys.id}`. Replace `card` yourself for each model. The route verifies the secret and adapter support before fetching the entry through the Preview API. A wrong secret, a content type without an adapter, and a missing entry all return 404; a failed Preview API read returns a generic 502 without provider details. Responses use `no-store` and `no-referrer`, and only the preview route relaxes framing for configured Contentful origins.

Never put the Preview API token in the URL, browser props, or adapter fallback data. The URL contains only the separate preview secret and should still be treated as sensitive.

## Make adapters preview-ready

Use `preview.getProps(fieldName)` to add inspector attributes to the element that displays a field. Normal production rendering has no preview context, so no inspector attributes or controls are emitted.

The standalone preview renders an entry without its page, so it cannot supply props a parent would
pass or run a page's loaders. Adapters therefore declare deterministic fallbacks, and TypeScript
enforces them whether or not Preview is enabled: an adapter with a `loader` must set `preview.data`
(response-schema input), and an adapter whose `propsOf` props include required keys must set
`preview.props`. `layout: "padded"` adds standalone spacing; `controls` adds editor select controls.

```tsx
import { propsOf } from "brix/contentful/rendering";
import { z } from "brix/zod";

export const CardListAdapter = createAdapter({
  contentType: "cardList",
  props: propsOf<{ appearance: "light" | "dark" }>(),
  loader: {
    response: z.strictObject({
      cards: z.array(z.strictObject({ title: z.string(), href: z.string() })),
    }),
    handler: async (entry, c, signal) => {
      const { loadCards } = await import("./cards.server.ts");
      return { cards: await loadCards(entry, c, signal) };
    },
  },
  preview: {
    props: { appearance: "light" },
    data: { cards: [] },
    layout: "padded",
  },
  component: ({ entry, loaded, preview, props }) => {
    if (loaded.status === "pending") return <p role="status">Loading cards…</p>;
    if (loaded.status === "error") return <p>Cards unavailable</p>;
    return (
      <CardList
        heading={entry.fields.heading}
        headingAttributes={preview?.getProps("heading")}
        appearance={props.appearance}
        cards={loaded.data.cards}
      />
    );
  },
});

```

By default the standalone preview uses fallback data rather than server loader results. Keep it nonsecret and deterministic. The generated integration subscribes to untransformed entry updates, applies inspector mode, and can render adapter-defined select controls.

Preview renders drafts, and Contentful enforces required fields only when an entry is published.
A new entry opened in Live Preview before its title is typed has no `title`, even though the
[generated type](/docs/contentful-typegen.md) marks it required. Write preview-reachable adapters so
missing required fields render a placeholder instead of throwing, for example
`entry.fields.title ?? ""` rather than `entry.fields.title.toUpperCase()`.

Adapters that call `useTranslate()` or `useLocale()` from `#brix` work in the preview as they do on
pages. The preview island hydrates under the application's translation provider and receives the
messages its adapters use, so live edits re-render translated text. That text uses the request's
[resolved application locale](/docs/translations-setup.md#resolve-locale-consistently): the preview
route is not localized, so Brix uses `resolveLocale` if it returns a locale and `defaultLocale`
otherwise. The `{locale}` segment of the preview URL is the Contentful entry locale (for example
`en-US`); it selects entry content and does not choose the application's translations.

The controls panel shows the controls declared by the previewed entry's adapter and by adapters for
entries linked from it. Control names share one namespace: when two adapters declare the same name,
the first declaration (starting from the previewed entry) renders the select. Each adapter receives
only the controls it declares in `preview.controls`. A value outside its own options falls back to
its first option. An adapter without controls receives `null`. Adapters that render entries absent
from the previewed graph, such as entries in loader results, receive the defaults of the controls
they declare, even when the previewed graph declares none.

For [adapter loaders](/docs/contentful-rendering.md#declare-loader-responses), `preview.data`
and explicit prepared success fixtures contain response-schema input. Brix JSON-normalizes and
validates them, then passes parsed output to the component; invalid fixtures produce
`{ status: "error", reason: "failed" }` without invoking the handler. Keep schemas synchronous,
deterministic, and browser-safe. Storybook also uses fixtures, not a running application server or
automatic loader requests. Never put secrets in fixtures: the fixture source is browser-bundled
regardless of whether validation succeeds.

## Load saved draft data

To opt into saved-draft loaders, set the preview option `loaders: true` and add
[`createContentfulClientLoadingIntegration`](/docs/contentful-rendering.md#authorize-client-introduced-adapters)
to the same `integrations` array, before or after the Preview integration. Without it, real-loader
preview fails with `Real-loader preview requires createContentfulClientLoadingIntegration()`.
The preview secret is still required. Loading middleware must establish an authenticated editor
session; its scope must be `preview`, with a principal and a bounded expiry. The canonical resolver
owns Preview API credentials in this mode, so the fixture-mode `accessToken` is not required.

Contentful frames the preview from `app.contentful.com`, so every request from the preview,
including the preview page and its grant and load POSTs, is a third-party request to your origin.
Browsers do not send `SameSite=Lax` or `Strict` cookies there. A session cookie for real-loader
preview must be `SameSite=None; Secure`, and `Partitioned` where browsers restrict third-party
cookies. You can also use a non-cookie session mechanism. Otherwise the preview page returns 403
`Preview session required`, and browser loads report that the preview session is unavailable,
even though the same URL works when opened directly.

On the preview page route, loading middleware and the `scope` callback both run before Brix
resolves the saved root, so `getContentfulLoadingContext(c)` is `undefined` in both. Select Preview
session policy from the request path (`/_/contentful/preview/...`), not from that context; a `scope`
that checks `getContentfulLoadingContext(c)?.scope.mode` there falls through to a non-Preview scope
and the page returns 403 `Preview session required`. On the grant and load POSTs the
context holds the verified identity and scope.
Select `preview.contentful.com`, the Preview token and a separate private data-cache partition in
both the resolver and handler services. A `preview` label alone does not select draft credentials.

Application-owned Preview clients can set a native default `timeout` and forward each resolver or
loader's signal to `getEntry`/`getEntries`. These bound those native requests only; they do not replace
the real-loader authorization, resource cancellation, or loader budgets. Standard Preview API hosts
continue to bypass the delivery data cache, and delivery webhook invalidation does not refresh an
editor's browser resource.

For the loading/grant endpoints, forward `getContentfulLoadingContext(c)?.request` (from
`brix/contentful/server`) into each native
client's `request` configuration to share the endpoint's attempt budget and cancellation. During
initial Preview SSR use the resolver/loader's `signal` as `request: { signal }` instead. These controls
do not select credentials or replace the authenticated editor session; see [adapter limits](/docs/contentful-rendering.md).

Initial SSR resolves the authorized saved root and prepares reached loaders. Browser mounts use
the same permission-only loading endpoint. The protected `POST /_/contentful/preview/grants` route
accepts a distinct signed preview-root permission, rechecks the current session, and collects
eligible entries from the canonical saved graph without running loaders. It does not sign arbitrary
editor snapshots. Public grants cannot be substituted for preview-root permissions.

Initial payloads contain selected client-consumed and already-prepared client-reachable results,
not every server-only adapter result. Save/session reset clears that resource generation, including
prepared values; hydration data is not a fallback that can resurrect stale private results. Mounted
children may wait while an authorized parent loads descendant grants, then missing grants terminate
with a diagnostic. Entries invented only by arbitrary client code, or absent from both the saved
graph and authorized parent responses, have no automatic renewal source. Save the linked dependency
or return it from an authorized parent; Brix does not sign unsaved fields or arbitrary dependency IDs.

Typing still updates original entry fields locally. SDK save events invalidate the preview resource,
refresh permissions, and refetch mounted loaders from the saved draft. Older responses are ignored;
entry edits and select controls remain local. Newly linked unsaved entries may show the saved-data
diagnostic until saved. During refresh the same loader-backed component receives `loaded.status === "pending"`,
then success/error without a framework remount. Declare hooks before branches and keep shared controls
in a stable subtree to retain component-local and DOM state. A terminal permission diagnostic may
replace the adapter; state retention is not promised across that error boundary or an unmount.
Expired sessions require reopening an authorized preview. All real-loader
preview HTML is `private, no-store`; keep that policy at the edge. `preview.data` is a fixture, not a
production pending/error fallback.

## Diagnose a preview that does not load

- A 404 means a wrong secret, a content type without a discovered adapter, or an entry the Preview
  API cannot find. Check the literal content type ID in the URL, the adapter module name
  (`*.adapter.ts` or `*.adapter.tsx`), and that the URL secret matches the server configuration;
  never substitute the Preview API token.
- A 502 means the Preview API read failed: check the token, space, environment, `host`, and
  `timeout`.
- A 403 `Preview session required` in loader mode, when the URL works opened directly, usually
  means the framed request carried no editor session: check the cookie's `SameSite=None; Secure`
  (and `Partitioned`) attributes. It also occurs when `scope` derives Preview mode from
  `getContentfulLoadingContext(c)`, which is `undefined` on the preview page route.
- If framing is blocked, check `targetOrigin` and any CSP added by your proxy or hosting platform.
- If the entry renders but extra content is empty, inspect the adapter's `preview.data` and
  `preview.props` in fixture mode, or the current preview session and canonical saved draft in loader mode.

Test with a draft edit in Contentful and confirm both live text updates and inspector selection.
Production rendering remains unchanged: inspector attributes, controls, draft credentials, and
standalone fallback data are confined to the protected preview flow.
