# Content draft preview

A preview cookie lets one browser see drafts through your real pages. Requests without it read `published`, and the site shows no editing UI. Your app sets the cookie from its own route. The Console editor does not: its side browser uses [preview frames](https://vitehub.dev/docs/content/preview#preview-frames).

## Enable preview

`content.preview.enable(event)` signs a token and sets it as a cookie on the response. `content.preview.disable(event)` clears it.

```ts [server/api/preview.post.ts] fragment
import { content } from '../content'

export default defineEventHandler(async (event) => {
  const user = await getUser(event) // your Auth session
  if (!await content.can({ user, collection: 'posts', action: 'read' }))
    throw createError({ statusCode: 403 })
  return await content.preview.enable(event) // { setCookie, expiresAt }
})
```

```ts [server/api/preview.delete.ts]
import { content } from '../content'

export default defineEventHandler(event => content.preview.disable(event))
```

`enable()` is trusted server API, like `save()` and `publish()`, and skips `authorize`. Check `content.can()` with `read` first. The token previews every collection, so check each one the user may open, or the ones the page renders.

| Call | Behavior |
| --- | --- |
| `content.preview.enable(event, { maxAge? })` | Adds the preview cookie to the response and returns `{ setCookie, expiresAt }`. `maxAge` is in seconds: 60 to 86400, default 3600. |
| `content.preview.disable(event)` | Adds a cookie that expires now. Returns `{ setCookie, expiresAt: null }`. |
| `content.preview.run(event, callback)` | Runs `callback` in preview if the event has a valid cookie, else unchanged. |
| `content.preview.active()` | `true` in a request with a valid preview cookie, where every read uses `draft`. `false` in a preview frame and with [`?vitehub-content-published`](https://vitehub.dev/docs/content/preview#published-reads). |
| `content.preview.sign({ collection, id, maxAge? })` | Returns `{ token, expiresAt }` for a [preview frame](https://vitehub.dev/docs/content/preview#preview-frames) of one document, without a cookie. Check `content.can({ user, collection, id, action: 'read' })` first. |
| `content.preview.frame()` | In a preview frame request, `{ collection, id, document? }`: the signed document and the on-screen version the frame posted. Else `undefined`. |

`event` is an H3 event or a Web `Request`. With a `Request`, set the returned `setCookie` header yourself.

## What a preview request reads

With a valid cookie, every Content read uses `draft`:

- `/api/content/**`, so `createContentClient()` in the browser, and server fetches that forward the cookie.
- `content.get()`, `content.list()`, `content.navigation()`, `content.search()`, and `content.handler()`.
- `content.collection(name).get()`, `list()`, and the Collection handler. An explicit `{ ref: 'published' }` still reads `published`.

`status()`, `revisions()`, and plugin methods such as SQL queries do not change. A save shows on the next preview request, because preview reads check the draft head and refresh when it moved.

Each request gets its own grant through `AsyncLocalStorage`, so parallel preview and public requests never see each other's content.

## Where the request is scoped

A generated Nitro plugin wraps Nitro's request entry. The whole request runs in the preview scope: route rules, middleware, cached routes, pages, and server routes. Requests without the cookie pass through. Your server code does not change.

This works with the `vitehub()` Vite plugin and the `vite-hub/nuxt` module on Nitro 3, with no Nitro experimental flag. Nuxt `useFetch()` during SSR forwards the cookie, so the rendered page shows the draft too.

Preview needs the host's `AsyncLocalStorage` request context. On Cloudflare Workers, turn on the `nodejs_als` compatibility flag in the Worker configuration. Without this API, ViteHub reports a configuration error before it serves requests.

Call `content.preview.run(event, callback)` yourself only for requests outside Nitro, such as a test or a custom server.

## Preview frames

The Console editor shows the document's page in a side browser. The page renders through your routes with the on-screen fields and body, before anything saves. The collection needs a `url` on the Console origin, such as `documents({ url: '/blog/:id' })`.

```ts [server/content.ts] fragment
posts: documents({ path: 'posts/**/*.md', url: '/blog/:id', fields: { title: z.string() } }),
```

```ts [server/routes/blog/[...id].get.ts] fragment
const post = await content.collection('posts').get(id) // the document on screen in a preview frame
return html`<h1 ${contentField('posts', post.id, 'title')}>${post.data.title}</h1>`
```

The Draft view posts a form to the page URL with `?vitehub-content-preview`. The form field of that name holds `{ token, document? }` as JSON: a `content.preview.sign({ collection, id })` token (15 minutes in the Console) and the on-screen version. The Console signs only after `content.can()` allows `read` of that document. The Nitro plugin checks the token and runs the page as a `GET` of its URL, without the parameter.

A frame token reads the draft of its one document only:

- `content.collection(name).get(id)` and that collection's `list()`, without `ref` or `revision`, return the posted version of the signed document, or its stored draft if the form has none. Other documents in `list()` are `published`.
- Every other read is `published`: other documents and collections, never-published drafts, `raw()`, Comark reads such as `content.get()`, `content.list()`, `queryCollection()`, `navigation()`, and `search()`, and `/api/content/**`. A page that reads the signed document through Comark shows its published version.
- An explicit `{ ref: 'draft' }` or `{ revision }` in server code is trusted and reads what it names. Do not pass it from request input.
- A form that posts another document, or a token changed in any part, gets `403`. Frame tokens and preview cookie tokens are not interchangeable. Use `enable()` to preview the whole site.
- Nested requests, such as `/api/content/**` during SSR, keep the frame scope. A preview cookie does not widen it.
- Nothing is stored. The response is `private, no-store` and `noindex`, and skips Nitro's cache. In Nuxt, the page keeps its payload in the HTML, even with a `cache`, `swr`, or `isr` rule. A later `_payload.json` request cannot carry the form, so it would read `published`.
- A form without a valid token, or with a cross-site `Sec-Fetch-Site` or `Origin`, gets `403`. `Origin` must match the page URL and protocol, which comes from `x-forwarded-proto` behind a proxy or from TLS. The parameter on a `GET` grants nothing. The token is in the form body, never the URL. A cross-site form is refused before its body is read. The body is at most 1 MiB. The plugin counts bytes as they arrive, ignores `Content-Length`, and answers `403` at the first byte over.

The ViteHub pill uses the same form on the site. When a page's document has an unpublished draft, its [**View draft** button](https://vitehub.dev/docs/development/console#work-from-a-page) posts a form without `document` to the page in the same tab, which shows the saved draft. It finds the document with the Console `resolve` action. That matches the page path against collection `url` patterns on `published`, then `draft`, and checks `read` access. To mark changes, it loads the page with `?vitehub-content-published` in a hidden frame.

The Published view loads the page with a `GET` of `?vitehub-content-published`, as a guest sees it. Elements with `contentField()` attributes select their field in the editor. In the Draft view, top-level text fields change in place.

A same-origin redirect, such as a locale, canonical, or sign-in redirect, keeps the document on screen. The browser follows it with the same form, so the token and document stay in the body, never in a URL or cookie:

- The plugin answers with a `307` to the same `Location`, adding `?vitehub-content-preview=<hop>`. The rest of the query and the fragment stay. A `307` keeps the method and body, so the browser posts the form to the next page, and the plugin checks the token and document again. Each page runs as a `GET` of its URL, without the form.
- The browser keeps the cookies. It sets each redirect's `Set-Cookie`, and sends each page its cookies for that URL by `Path`, `Domain`, `Secure`, `SameSite`, and expiry. The server never copies a `Cookie` header between URLs, so a cookie for `/admin` never reaches `/account` through a redirect.
- Same origin means the scheme, host, and port of the frame URL, from the `Host` header and the protocol above. `X-Forwarded-Host` does not count. A cross-origin redirect, a sixth redirect, or an invalid `Location` gets a private error page before the browser can post the form there. Its `<meta name="vitehub-content-preview-error">` (`contentPreviewErrorName`) holds the message, which the Console shows with **Retry**. The Draft label never shows another site, or a page without the on-screen document.
- The page sees a `GET`, and the frame address has the parameter. A client router that reads the query sees `vitehub-content-preview`. The Console address bar hides it. A redirect from a page script or `<meta http-equiv="refresh">` loads the next page with a `GET` without the form, so it reads `published`.
- Each request in the chain has the Console page's `Referer` and `Origin`, as browsers send for redirects. A Console page Content Security Policy whose `form-action` does not allow the site origin blocks the form and its redirects.

Pages must allow a frame from their own origin: `frame-ancestors 'self'` or none, and no `X-Frame-Options: DENY`. Data the page fetches from the browser after load has no frame scope. It reads `published`, or `draft` with a preview cookie.

## Published reads

A browser with a preview cookie reads drafts on every page. A request with `?vitehub-content-published` reads `published` with the same cookie, as the Console's Published view does:

- Every Content read without `ref` or `revision` is `published`, and `content.preview.active()` is `false`. Nested requests and `content.preview.run()` calls stay `published`. The cookie does not widen them.
- A request whose `Referer` is a same-origin page with the parameter is `published` too, such as a `fetch()` from the Published view. Without a `Referer`, for example with `Referrer-Policy: no-referrer`, or after client-side navigation to a URL without the parameter, the cookie applies again.
- An HTTP redirect to the same host name, such as a canonical or locale redirect, gets the parameter in its `Location`. The rest of the URL stays, so the landing page and each later redirect read `published` too. The host comes from the request URL or `X-Forwarded-Host`. A redirect to another host does not change and gets no token. Neither does a redirect from a page script or `<meta http-equiv="refresh">`.
- The cookie does not change. The response sets no cookie, and requests without the parameter still preview the whole site.
- The parameter only removes draft access. It needs no token and never reads a draft or posted document. A frame form needs its own token.
- The page sees its URL with the parameter. The response is `private, no-store` and `noindex`, and skips Nitro's cache, so the page shows current published content.
- An explicit `{ ref: 'draft' }` or `{ revision }` in server code is trusted and reads what it names.

`contentPreviewPublishedParameter` from `@vite-hub/content` and `@vite-hub/content/client` holds the parameter name.

## Signing key

Content signs preview tokens with HMAC-SHA256 and `VITEHUB_CONTENT_KEY`: 32 random bytes as base64 or hex.

```sh
export VITEHUB_CONTENT_KEY="$(openssl rand -base64 32)"
```

Content reads it from the process environment, then the Cloudflare Worker environment. Every instance needs the same key.

| Situation | Behavior |
| --- | --- |
| Key set | Tokens verify on every instance until they expire. |
| No key, `NODE_ENV` is `development` or `test` | Content uses a random key for this process and warns once. Tokens break on restart. |
| No key in any other environment | `enable()` throws `CONTENT_R0010`. Preview cookies are ignored, so requests read `published`. |
| Key is not 32 bytes | `enable()` throws `CONTENT_R0010`. Preview cookies are ignored with one warning. |

Rotating the key ends every open preview. ViteHub has no app-wide secret to reuse. `BETTER_AUTH_SECRET` exists only with Auth, and `VITEHUB_CONNECTIONS_KEY` belongs to Connections.

## Cookie and token

The cookie is `vitehub-content-preview` with `Path=/`, `HttpOnly`, `SameSite=Strict`, and `Max-Age` set to the token lifetime. It is `Secure` unless the request used plain `http`, such as `http://localhost`. Behind a proxy, the protocol comes from `x-forwarded-proto`.

The token is `v1.<expiry>.<signature>`. The signature covers the expiry and a purpose string. Content checks it in constant time with `crypto.subtle.verify()`. A bad signature, a past expiry, or an expiry over 24 hours ahead is ignored.

> **Warning**

The token is not bound to a user or session. Anyone with the cookie reads drafts until it expires. `disable()` clears it only in the browser that sends the request. Keep `maxAge` short.

## Caching

Preview responses have `Cache-Control: private, no-store` and `X-Robots-Tag: noindex, nofollow`. Content sets them after your handler, so route headers cannot make a draft public. Other responses keep their headers.

Nitro's cache skips preview requests. Cached handlers, `cache` or `swr` route rules, and cached functions run directly. They never read or write a cache entry, and never share an in-flight render with a public request. So pages that read Content can use `swr` safely. Nitro has no global bypass hook, so ViteHub puts a small module in front of Nitro's cache module.

> **Warning**

A CDN or reverse proxy caches by URL and does not know the cookie. If it caches HTML, make it skip its cache for requests with the `vitehub-content-preview` cookie. Otherwise the previewer gets the cached published page. `private, no-store` stops a correct CDN from storing the draft response.

See [Limits and errors](https://vitehub.dev/docs/content/limits-and-errors) for every Content error code.

<!-- vitehub-docs:section-links -->
## In this section

- [Overview](https://vitehub.dev/raw/docs/content.md)
- [Get started](https://vitehub.dev/raw/docs/content/get-started.md)
- [Configure](https://vitehub.dev/raw/docs/content/configure.md)
- [Server API](https://vitehub.dev/raw/docs/content/server-api.md)
- [Agent capability](https://vitehub.dev/raw/docs/content/agent-capability.md)
- [Limits and errors](https://vitehub.dev/raw/docs/content/limits-and-errors.md)
- [Draft preview](https://vitehub.dev/raw/docs/content/preview.md) (this page)
- [Console editor](https://vitehub.dev/raw/docs/content/console.md)
- [Editing together](https://vitehub.dev/raw/docs/content/editing-together.md)
- [Scheduling](https://vitehub.dev/raw/docs/content/scheduling.md)
- [SEO](https://vitehub.dev/raw/docs/content/seo.md)
- [CLI](https://vitehub.dev/raw/docs/content/cli.md)

Next: [Console editor](https://vitehub.dev/raw/docs/content/console.md)

All pages: [llms.txt](https://vitehub.dev/llms.txt)
