# Preview

The dashboard shows a record on the connected site before it is published. It mints a **preview token** and opens `{site_url}{preview_path}?token=...&path=...` (plus `&locale=...` when the editor previews one language) in a frame (the web editor) or a WebView (the mobile app). The site's preview route checks the token with Borkol through [`GET /v1/api/objects/preview`](#get-v1apiobjectspreview), then redirects to the record's own path with the token in the `borkol_preview` query parameter. The page passes the token to every fetcher, which sends it as `X-Borkol-Preview` and skips the cache. The site never verifies a token itself and holds no preview secret.

`site_url` and `preview_path` are the connected site's settings (Settings > Website); `preview_path` defaults to `/api/borkol/preview`.

## The preview route

`borkol init` writes `app/api/borkol/preview/route.ts` with `export const GET = previewHandler()` from `@borkol/content/next`. The handler reads `token` (and `locale`, when present) from the link, calls `GET /v1/api/objects/preview` with the site key and the token, and answers `307` to the `path` Borkol returns with `?borkol_preview={token}`. It never follows the `path` of the link, and it redirects only to a path on the site: one leading `/`, never `//` or `/\`, no scheme, query or fragment. The redirect, and every refusal, carries `Referrer-Policy: no-referrer`, `X-Robots-Tag: noindex` and `Cache-Control: private, no-store`.

| Answer | When |
| --- | --- |
| `307` to `{path}?borkol_preview={token}` | Borkol accepts the token. |
| `401` | No token, or Borkol answers `403 invalid_preview` (expired, forged or another store's token). |
| `404` | The record has no address (`path` is `null`), as on a singleton. |
| `500` | `BORKOL_API_URL` or `BORKOL_SITE_KEY` is not set on the site. |
| `502` | Borkol is unreachable, answers an error, or returns a `path` that is not a path on the site. |

## Preview tokens

A preview token is opaque to the site: pass it on as it is. It opens **one record of one store for 60 minutes**:

- **Store-bound.** It works only together with that store's own API key. With another store's key it answers `403 invalid_preview`.
- **Record-bound.** Only the token's own record reads its draft. Every other record in the same response reads live: published values, live addresses, and drafts of other records stay hidden.
- **Time-bound.** After 60 minutes it answers `403 invalid_preview`; opening the preview again mints a fresh one. Until then it stays valid for its full 60 minutes, even after the team member who opened it is removed or the push key is rotated, and its preview reads keep their own budget for that time (see [The preview budget](#the-preview-budget)).

The token is useless without the store's site key, but treat it as a secret while it lives: keep it out of logs, analytics and the `Referer` header (send `Referrer-Policy: no-referrer` and `X-Robots-Tag: noindex` on preview pages). `withBorkol` sends both on every URL that carries `borkol_preview`, and `previewHandler()` on its redirect.

## The X-Borkol-Preview header

Three reads take the header: `GET /v1/api/objects/types/{key}/records`, `GET /v1/api/objects/types/{key}/records/by-slug/{slug}` and `GET /v1/api/objects/records/{id}`.

| Header | What happens |
| --- | --- |
| absent or empty | Nothing changes: the response is the live one, byte for byte. |
| a valid token | The token's record is served as its draft, whatever its status (draft, scheduled or published): staged values replace the live ones in `values` and staged addresses replace the live ones in `slugs`. Its draft address resolves in `filter[path]` and in `by-slug`, and lists of its type include it. That record, and only that one, gains `status`; every other record keeps the live shape. The response carries `Cache-Control: private, no-store`. |
| anything else | `403 {"code": "invalid_preview"}`, never a silent live read. |

`status` is one of:

| Value | Meaning |
| --- | --- |
| `draft` | Never published. |
| `scheduled` | Published with a `published_at` in the future. |
| `changed` | Live, with edits staged for the next publish. |
| `published` | Live, nothing staged. |

Search (`q`), sorting and value filters still run on the live values; only `filter[path]` knows the draft address. A draft address may run through the address of a parent page that is not published yet, so a new page under a new parent can be previewed before either goes live. Expanded references (`include=refs`) always read live: the token's record shows inside another record as its live version, and its draft references to unpublished records stay hidden.

```bash title="Request"
curl "https://api.borkol.com/v1/api/objects/types/page/records?filter[path]=/about-us" \
  -H "Authorization: Bearer {site_key}" \
  -H "X-Borkol-Preview: {token}"
```

```json title="Response"
{
  "data": [
    {
      "id": "9d3f2c1a-6b7e-4f80-9a1b-2c3d4e5f6a7b",
      "parent_id": null,
      "position": 0,
      "status": "changed",
      "values": { "title": { "en": "About us" } },
      "published_at": "2026-11-01T09:00:00.000000Z",
      "created_at": "2026-10-30T14:12:03.000000Z",
      "updated_at": "2026-11-01T09:00:00.000000Z",
      "slugs": { "en": "about-us" }
    }
  ],
  "links": { "first": "...", "last": "...", "prev": null, "next": null },
  "meta": { "current_page": 1, "from": 1, "last_page": 1, "per_page": 25, "to": 1, "total": 1 }
}
```

## The token in the URL, passed to fetchers

The token travels in the URL, not in a cookie: a cookie set inside a frame on another origin is third party, and browsers (Safari first) block it. A cached fetcher cannot read cookies or headers either. So the page reads the token from its `borkol_preview` search param and passes it to every read:

```ts title="lib/borkol.ts"
import { createFetchers } from "@borkol/content/next";
import type content from "../borkol.content";

export const borkol = createFetchers<typeof content>();
```

```tsx title="app/[[...path]]/page.tsx"
import { Suspense } from "react";
import { borkol } from "../../lib/borkol";

export default function Page(props: PageProps<"/[[...path]]">) {
  return (
    <Suspense fallback={null}>
      <Content {...props} />
    </Suspense>
  );
}

async function Content({ params, searchParams }: PageProps<"/[[...path]]">) {
  const [{ path = [] }, query] = await Promise.all([params, searchParams]);
  const preview = typeof query.borkol_preview === "string" ? query.borkol_preview : undefined;
  const page = await borkol.getByPath(`/${path.join("/")}`, { preview });
  // ...
}
```

Every getter of [`@borkol/content`](/api/build-a-site/package) takes `{ preview }` and sends `X-Borkol-Preview` only when it is set. The fetchers of `createFetchers` read live content inside `'use cache'` (tag `borkol`, life `max`) and a read with a token outside it, so a draft never lands in the cache a visitor reads from. With `cacheComponents` (which `withBorkol` turns on) `searchParams` is request data: read it inside a `<Suspense>` boundary, as above. Without the package, the same rule holds: a read with a token must skip your cache.

## Refresh after an autosave

`<BorkolPreview appOrigin={...} />` from `@borkol/content/next`, rendered once in the root layout, keeps the open preview current. `borkol init` adds it after `{children}`:

```tsx title="app/layout.tsx"
<BorkolPreview appOrigin={process.env.BORKOL_APP_ORIGIN ?? "https://app.borkol.com"} />
```

It is a client component, which sees only `NEXT_PUBLIC_*` env, so the layout (a server component) passes the dashboard origin in. On a page whose URL carries `borkol_preview` it exchanges two messages with the editor:

| Message | From, to | What happens |
| --- | --- | --- |
| `{"type": "borkol:ready"}` | site to `window.parent`, target origin `appOrigin` (never `*`) | Posted on load and after each refresh. The editor waits 4 seconds for it, then offers **Open in new tab**. In a React Native WebView it also goes to `ReactNativeWebView.postMessage` as JSON. |
| `{"type": "borkol:refresh"}` | editor to the frame, target origin the site's | Posted after each autosave. The site accepts it only when `event.origin` is `appOrigin` and `event.source` is `window.parent`, then calls `router.refresh()`, which keeps the URL and its token. |

On any other page it renders nothing and loads no extra script, and after a client navigation that drops `borkol_preview` it stops listening. The mobile app does not post messages: its WebView reloads the same URL after each autosave.

## frame-ancestors

The web editor shows the preview in a frame on `https://app.borkol.com`, so the site must allow that origin to frame it:

```http
Content-Security-Policy: frame-ancestors 'self' https://app.borkol.com
```

`withBorkol` from `@borkol/content/next` adds this header for every path (see [The package](/api/build-a-site/package)).

## The preview budget

Preview reads have a budget of their own: **120 requests per minute per store**, apart from the live budget of [Errors and rate limits](/api/getting-started/errors-and-rate-limits#429-too-many-attempts-rate-limiting). An editor refreshing a preview never slows the live site down. Only a request whose `X-Borkol-Preview` holds a token valid for the store counts against the preview budget; a request with an invalid or expired token counts against the live budget, so a made-up header never buys extra requests.

## GET /v1/api/objects/preview

What a preview token opens. The site's preview route calls it before it redirects, and redirects only to the `path` it returns. Requires the `objects:read` scope and the token in `X-Borkol-Preview`.

| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `X-Borkol-Preview` | header | yes | The token from the preview URL's `token`. |
| `locale` | query, string | no | The language of `path`: an enabled content language of the store. Default the store's default language. |

```bash title="Request"
curl "https://api.borkol.com/v1/api/objects/preview" \
  -H "Authorization: Bearer {site_key}" \
  -H "X-Borkol-Preview: {token}"
```

| Field | Type | Description |
| --- | --- | --- |
| `record_id` | string | The record the token opens. |
| `type_key` | string | Its type's key. |
| `path` | string or null | The record's draft address in `locale` (staged address, type prefix and parent addresses, unpublished parents included), `/` for the home page. `null` when the record has no address, as on a singleton. |
| `locale` | string | The language of `path`. |
| `expires_at` | string | When the token expires (ISO 8601). |

```json title="Response"
{
  "record_id": "9d3f2c1a-6b7e-4f80-9a1b-2c3d4e5f6a7b",
  "type_key": "page",
  "path": "/about-us",
  "locale": "en",
  "expires_at": "2026-11-12T10:42:17.000000Z"
}
```

The response carries `Cache-Control: private, no-store`.

### Errors

- `403` `{"code": "invalid_preview", "message": "..."}` when the header is missing, the token is malformed or expired, or it belongs to another store.
- `404` when the record was deleted after the token was minted.
- `422` with `errors.locale` when `locale` is not an enabled content language.
- `403` module and scope errors as on [Records](/api/objects/records).

## POST /v1/api/objects/preview-tokens

Mints a preview token without the dashboard, for `borkol doctor`'s round trip and for tests. Requires the `objects:schema` scope, so only the push key can call it.

| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `record_id` | string (uuid) | no | The record to open. Default the home page: the root record of the Pages type whose address in the default language is `home`. |
| `locale` | string | no | The language of the `path` in `url`. Default the store's default language. |

```bash title="Request"
curl -X POST "https://api.borkol.com/v1/api/objects/preview-tokens" \
  -H "Authorization: Bearer {push_key}" \
  -H "Content-Type: application/json" \
  --data '{}'
```

Status: `200 OK`.

| Field | Type | Description |
| --- | --- | --- |
| `token` | string | The preview token, valid for 60 minutes. |
| `expires_at` | string | When it expires (ISO 8601). |
| `url` | string | `{site_url}{preview_path}?token={token}&path={path}`, the path being the record's draft address, plus `&locale={locale}` when `locale` was sent. `path` is left out when the record has none. |

```json title="Response"
{
  "token": "eyJ0Ijoic2Fsb24iLCJyIjoi...In0.mJ3k...",
  "expires_at": "2026-11-12T10:42:17.000000Z",
  "url": "https://bakery.example/api/borkol/preview?token=eyJ0Ijoic2Fsb24iLCJyIjoi...In0.mJ3k...&path=%2F"
}
```

### Errors

- `422` `{"code": "no_site", "message": "No website is connected. Connect one under Settings > Website first."}` when the store has no connected site.
- `422` `{"code": "no_home", "message": "..."}` without `record_id` when the store has no home page.
- `404` when `record_id` names no record of this store.
- `422` with `errors.record_id` or `errors.locale` for a value of the wrong shape.
- `403` `{"message":"Invalid ability provided."}` when the key lacks `objects:schema`.
