@preprio/toolkit 0.6.0-alpha.9 → 1.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/README.md +111 -1363
  2. package/dist/astro/index.cjs +1555 -182
  3. package/dist/astro/index.d.cts +201 -1
  4. package/dist/astro/index.d.ts +201 -1
  5. package/dist/astro/index.js +1557 -29
  6. package/dist/{chunk-5QIWVDP2.js → chunk-33GWVTRJ.js} +1 -1
  7. package/dist/chunk-A2J7R4LR.js +256 -0
  8. package/dist/{chunk-WQBKQG4R.js → chunk-DSJ22P6J.js} +6 -1
  9. package/dist/chunk-KM2GME62.js +1255 -0
  10. package/dist/chunk-UTKH7DOI.js +58 -0
  11. package/dist/chunk-V7MCHPE7.js +85 -0
  12. package/dist/{chunk-J66UOCK6.js → chunk-WBMN4L7G.js} +1680 -579
  13. package/dist/chunk-Y7JWV7WV.js +374 -0
  14. package/dist/codegen/index.cjs +82 -0
  15. package/dist/codegen/index.d.cts +70 -0
  16. package/dist/codegen/index.d.ts +70 -0
  17. package/dist/codegen/index.js +64 -0
  18. package/dist/index.cjs +3729 -553
  19. package/dist/index.d.cts +403 -19
  20. package/dist/index.d.ts +403 -19
  21. package/dist/index.js +345 -24
  22. package/dist/live-preview-HCBNBC6C.js +19 -0
  23. package/dist/nextjs/components.cjs +1872 -754
  24. package/dist/nextjs/components.d.cts +5 -51
  25. package/dist/nextjs/components.d.ts +5 -51
  26. package/dist/nextjs/components.js +8 -299
  27. package/dist/nextjs/index.cjs +1228 -181
  28. package/dist/nextjs/index.d.cts +247 -92
  29. package/dist/nextjs/index.d.ts +247 -92
  30. package/dist/nextjs/index.js +1629 -111
  31. package/dist/nextjs/live-action.cjs +298 -0
  32. package/dist/nextjs/live-action.d.cts +12 -0
  33. package/dist/nextjs/live-action.d.ts +12 -0
  34. package/dist/nextjs/live-action.js +68 -0
  35. package/dist/nextjs/live.cjs +2010 -0
  36. package/dist/nextjs/live.d.cts +54 -0
  37. package/dist/nextjs/live.d.ts +54 -0
  38. package/dist/nextjs/live.js +287 -0
  39. package/dist/nuxt/chunk-5RBZPRQN.js +350 -0
  40. package/dist/nuxt/chunk-LUKVPOJ2.js +32 -0
  41. package/dist/nuxt/index.cjs +15 -16
  42. package/dist/nuxt/index.d.cts +167 -6
  43. package/dist/nuxt/index.d.ts +167 -6
  44. package/dist/nuxt/index.js +402 -15
  45. package/dist/nuxt/live-preview-KO4IKWTX.js +1234 -0
  46. package/dist/nuxt/live.cjs +1928 -0
  47. package/dist/nuxt/live.d.cts +45 -0
  48. package/dist/nuxt/live.d.ts +45 -0
  49. package/dist/nuxt/live.js +216 -0
  50. package/dist/{types-BYH9XqmN.d.cts → pixel-DqU7NvgW.d.cts} +102 -5
  51. package/dist/{types-BYH9XqmN.d.ts → pixel-DqU7NvgW.d.ts} +102 -5
  52. package/dist/react/components.cjs +1865 -480
  53. package/dist/react/components.d.cts +43 -8
  54. package/dist/react/components.d.ts +43 -8
  55. package/dist/react/components.js +1865 -480
  56. package/dist/sveltekit/chunk-5RBZPRQN.js +350 -0
  57. package/dist/sveltekit/chunk-LUKVPOJ2.js +32 -0
  58. package/dist/sveltekit/index.cjs +15 -16
  59. package/dist/sveltekit/index.d.cts +111 -10
  60. package/dist/sveltekit/index.d.ts +111 -10
  61. package/dist/sveltekit/index.js +398 -15
  62. package/dist/sveltekit/live-preview-KO4IKWTX.js +1234 -0
  63. package/dist/sveltekit/live.cjs +1940 -0
  64. package/dist/sveltekit/live.d.cts +61 -0
  65. package/dist/sveltekit/live.d.ts +61 -0
  66. package/dist/sveltekit/live.js +220 -0
  67. package/package.json +132 -71
  68. package/src/astro/PreprToolbar.astro +7 -1
  69. package/src/astro/PreprTrackingPixel.astro +2 -4
  70. package/src/nuxt/PreprToolbar.vue +12 -1
  71. package/src/nuxt/PreprTrackingPixel.vue +2 -4
  72. package/src/sveltekit/PreprToolbar.svelte +17 -2
  73. package/src/sveltekit/PreprTrackingPixel.svelte +2 -4
  74. package/dist/astro/chunk-UN4JADNU.js +0 -173
  75. package/dist/astro/graphql.cjs +0 -1078
  76. package/dist/astro/graphql.d.cts +0 -300
  77. package/dist/astro/graphql.d.ts +0 -300
  78. package/dist/astro/graphql.js +0 -984
  79. package/dist/astro/index-XT_z-RYT.d.cts +0 -130
  80. package/dist/astro/index-XT_z-RYT.d.ts +0 -130
  81. package/dist/chunk-3NCEVJJ3.js +0 -10
  82. package/dist/chunk-S5RWVMDJ.js +0 -148
  83. package/dist/chunk-XL4Y7FGW.js +0 -499
  84. package/dist/graphql/codegen.cjs +0 -557
  85. package/dist/graphql/codegen.d.cts +0 -23
  86. package/dist/graphql/codegen.d.ts +0 -23
  87. package/dist/graphql/codegen.js +0 -99
  88. package/dist/graphql.cjs +0 -1020
  89. package/dist/graphql.d.cts +0 -335
  90. package/dist/graphql.d.ts +0 -335
  91. package/dist/graphql.js +0 -448
  92. package/dist/nextjs/chunk-CMV6ZP6E.js +0 -549
  93. package/dist/nextjs/graphql.cjs +0 -1836
  94. package/dist/nextjs/graphql.d.cts +0 -498
  95. package/dist/nextjs/graphql.d.ts +0 -498
  96. package/dist/nextjs/graphql.js +0 -1422
  97. package/dist/nextjs/server-BL-sqZvu.d.cts +0 -156
  98. package/dist/nextjs/server-BL-sqZvu.d.ts +0 -156
  99. package/dist/nuxt/chunk-XWOABVMW.js +0 -417
  100. package/dist/nuxt/graphql.cjs +0 -1085
  101. package/dist/nuxt/graphql.d.cts +0 -297
  102. package/dist/nuxt/graphql.d.ts +0 -297
  103. package/dist/nuxt/graphql.js +0 -985
  104. package/dist/nuxt/server-8v6OHbsw.d.cts +0 -158
  105. package/dist/nuxt/server-8v6OHbsw.d.ts +0 -158
  106. package/dist/pixel-DwW7cXJm.d.cts +0 -49
  107. package/dist/pixel-DwW7cXJm.d.ts +0 -49
  108. package/dist/server-Brr1UgtW.d.ts +0 -59
  109. package/dist/server-DJuS3YU0.d.cts +0 -59
  110. package/dist/sveltekit/chunk-3S5RA6G5.js +0 -413
  111. package/dist/sveltekit/graphql.cjs +0 -1091
  112. package/dist/sveltekit/graphql.d.cts +0 -302
  113. package/dist/sveltekit/graphql.d.ts +0 -302
  114. package/dist/sveltekit/graphql.js +0 -991
  115. package/dist/sveltekit/server-CO847mEV.d.cts +0 -98
  116. package/dist/sveltekit/server-CO847mEV.d.ts +0 -98
package/README.md CHANGED
@@ -1,50 +1,87 @@
1
1
  # @preprio/toolkit
2
2
 
3
- > **Stable, pre-1.0.** The core is stable and published to `latest`. The package follows
4
- > semver: minor and patch releases never break the public API, and any breaking change
5
- > ships as a major bump with a migration entry in
6
- > [Breaking changes](https://github.com/preprio/prepr-toolkit/blob/main/RELEASING.md#breaking-changes).
7
- >
8
- > **Framework support.** The Next.js and Astro integrations are tested end to end. The
9
- > Nuxt, SvelteKit, and vanilla wrappers share the same core but have seen less real-world
10
- > use. If you hit a problem with any of them, please
11
- > [open an issue](https://github.com/preprio/prepr-toolkit/issues).
3
+ [![npm version](https://img.shields.io/npm/v/@preprio/toolkit.svg)](https://www.npmjs.com/package/@preprio/toolkit)
4
+ [![npm downloads](https://img.shields.io/npm/dm/@preprio/toolkit.svg)](https://www.npmjs.com/package/@preprio/toolkit)
5
+ [![license](https://img.shields.io/npm/l/@preprio/toolkit.svg)](https://github.com/preprio/prepr-toolkit/blob/main/LICENSE)
12
6
 
13
- A framework-agnostic TypeScript library that provides preview functionality, visual editing, and A/B testing for [Prepr CMS](https://prepr.io). Ships thin wrappers for Next.js, Nuxt, Astro, and SvelteKit on top of a vanilla core that runs anywhere.
7
+ Preview, visual editing, live preview and personalization for [Prepr CMS](https://prepr.io), for Next.js, Nuxt, Astro, SvelteKit, React and any other stack. One framework-free core with a thin wrapper per framework.
14
8
 
15
- Every integration is the same three steps:
9
+ ## What's included
16
10
 
17
- 1. **Middleware** — resolves the visitor's customer ID, segment, and A/B variant into request headers.
18
- 2. **Layout** — mounts the preview toolbar and the tracking pixel.
19
- 3. **Data fetching** — forwards the Prepr headers on your GraphQL requests, so Prepr returns personalized content.
11
+ - **Preview toolbar** — view the site as any segment or A/B variant.
12
+ - **Visual editing** — click any text or image on the page to open its field in Prepr.
13
+ - **Live preview** — the page shows what an editor types in Prepr, before they save.
14
+ - **Personalization and A/B testing** — middleware that resolves the visitor, segment and variant into the headers Prepr's GraphQL API reads.
15
+ - **Tracking pixel** — typed loader for Prepr's tracking script.
20
16
 
21
- Jump to your framework: [Next.js](#nextjs) · [Astro](#astro) · [SvelteKit](#sveltekit) · [Nuxt](#nuxt) · [React without a framework](#react-no-framework) · [anything else](#any-other-framework).
17
+ No CSS to import and no provider to wrap your app in. The toolbar renders in a shadow-DOM custom element, so its styles and yours never meet.
22
18
 
23
- Coming from `@preprio/prepr-nextjs`? See the [migration guide](https://github.com/preprio/prepr-toolkit/blob/main/MIGRATION.md).
19
+ ## Requirements
20
+
21
+ - Node.js 18.17 or later
22
+ - A Prepr GraphQL URL: in Prepr, **Settings → Access tokens → GraphQL Preview**. It looks like `https://graphql.prepr.io/{YOUR_ACCESS_TOKEN}`. Check **Enable edit mode** on the token for click-to-edit and live preview.
23
+
24
+ | Framework | Supported versions | Live preview while typing |
25
+ | -------------------- | --------------------------------------------------- | ------------------------- |
26
+ | Next.js | 13 and later (App Router) | Next.js 16 and later |
27
+ | Astro | tested with Astro 7; preview pages render on demand | yes |
28
+ | SvelteKit | Svelte 5 | yes |
29
+ | Nuxt | Vue 3.3 and later | yes |
30
+ | React (no framework) | React 17 and later | no |
31
+ | Anything else | any server that can build a WHATWG `Request` | server-rendered HTML |
32
+
33
+ All framework packages are optional peer dependencies: you only need the ones behind the entry points you import.
24
34
 
25
- ## Quick Start (Next.js)
35
+ ## Install
26
36
 
27
37
  ```bash
28
38
  npm install @preprio/toolkit
29
- # or
30
- pnpm add @preprio/toolkit
31
39
  ```
32
40
 
33
- Add your Prepr GraphQL URL (Settings → Access tokens in Prepr) to your `.env`. The toolkit reads **no environment variables itself** — the name is yours; you pass the value in explicitly:
41
+ ## Choose your entry point
42
+
43
+ | You use | Import from | Guide |
44
+ | -------------------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------- |
45
+ | Next.js | `@preprio/toolkit/nextjs` | [Next.js](https://github.com/preprio/prepr-toolkit/blob/main/packages/toolkit/docs/nextjs.md) |
46
+ | Astro | `@preprio/toolkit/astro` | [Astro](https://github.com/preprio/prepr-toolkit/blob/main/packages/toolkit/docs/astro.md) |
47
+ | SvelteKit | `@preprio/toolkit/sveltekit` | [SvelteKit](https://github.com/preprio/prepr-toolkit/blob/main/packages/toolkit/docs/sveltekit.md) |
48
+ | Nuxt | `@preprio/toolkit/nuxt` | [Nuxt](https://github.com/preprio/prepr-toolkit/blob/main/packages/toolkit/docs/nuxt.md) |
49
+ | React, no framework | `@preprio/toolkit/react` | [React](https://github.com/preprio/prepr-toolkit/blob/main/packages/toolkit/docs/react.md) |
50
+ | Express, Hono, other | `@preprio/toolkit` | [Any other framework](https://github.com/preprio/prepr-toolkit/blob/main/packages/toolkit/docs/other-frameworks.md) |
51
+
52
+ Coming from `@preprio/prepr-nextjs`? See the [migration guide](https://github.com/preprio/prepr-toolkit/blob/main/MIGRATION.md).
53
+
54
+ ## How it fits together
55
+
56
+ Every integration is the same three steps, plus one optional step:
57
+
58
+ 1. **Middleware** resolves the visitor's id, segment and A/B variant into request headers.
59
+ 2. **Layout** mounts the preview toolbar and the tracking pixel.
60
+ 3. **Data fetching** forwards those headers on your GraphQL requests, so Prepr returns personalized content.
61
+ 4. **Live preview** (optional) runs your query results through one helper.
62
+
63
+ Two rules hold everywhere:
64
+
65
+ - **The toolkit reads no environment variables.** You pass every value in, so it behaves the same in every framework and bundler.
66
+ - **Preview is one boolean that you own.** Pass it as `preview` to the middleware and gate `getToolbarProps` on it. Resolve it from whatever already separates your environments. A hardcoded `true` turns preview on in production too.
67
+
68
+ ## Quick start (Next.js)
69
+
70
+ Other frameworks follow the same steps: [Astro](https://github.com/preprio/prepr-toolkit/blob/main/packages/toolkit/docs/astro.md), [SvelteKit](https://github.com/preprio/prepr-toolkit/blob/main/packages/toolkit/docs/sveltekit.md), [Nuxt](https://github.com/preprio/prepr-toolkit/blob/main/packages/toolkit/docs/nuxt.md).
71
+
72
+ **1. Add your GraphQL URL to `.env`.** The name is yours.
34
73
 
35
74
  ```bash
36
75
  PREPR_GRAPHQL_URL=https://graphql.prepr.io/{YOUR_ACCESS_TOKEN}
37
76
  ```
38
77
 
39
- **`middleware.ts`**
78
+ **2. Add the middleware** in `proxy.ts` (`middleware.ts` with a `middleware` function on Next.js 15 and older):
40
79
 
41
80
  ```typescript
42
81
  import type { NextRequest } from 'next/server';
43
82
  import { createPreprMiddleware } from '@preprio/toolkit/nextjs';
44
83
 
45
- export function middleware(request: NextRequest) {
46
- // `preview` is the only gate. Resolve it however your deployment already
47
- // does — VERCEL_ENV, NODE_ENV, a branch check, your own feature flag.
84
+ export function proxy(request: NextRequest) {
48
85
  const preview = process.env.VERCEL_ENV !== 'production';
49
86
  return createPreprMiddleware(request, { preview });
50
87
  }
@@ -54,7 +91,7 @@ export const config = {
54
91
  };
55
92
  ```
56
93
 
57
- **`app/layout.tsx`**
94
+ **3. Mount the toolbar and the pixel** in `app/layout.tsx`:
58
95
 
59
96
  ```tsx
60
97
  import type { ReactNode } from 'react';
@@ -81,14 +118,14 @@ export default async function RootLayout({
81
118
  <body>
82
119
  {children}
83
120
  {toolbarProps && <PreprToolbar {...toolbarProps} />}
84
- {accessToken && <PreprTrackingPixel id={accessToken} />}
121
+ <PreprTrackingPixel id={accessToken} />
85
122
  </body>
86
123
  </html>
87
124
  );
88
125
  }
89
126
  ```
90
127
 
91
- **Data fetching** — spread `getPreprHeaders()` into every Prepr GraphQL request:
128
+ **4. Forward the Prepr headers** on every GraphQL request:
92
129
 
93
130
  ```typescript
94
131
  import { getPreprHeaders } from '@preprio/toolkit/nextjs';
@@ -104,1372 +141,83 @@ const response = await fetch(process.env.PREPR_GRAPHQL_URL!, {
104
141
  });
105
142
  ```
106
143
 
107
- No CSS import is needed. The toolbar renders into a shadow-DOM custom element (`<prepr-toolbar>`) with its styles inlined, so it can neither leak into nor inherit from your page's stylesheets.
108
-
109
- ## Prerequisites
110
-
111
- - **Node.js 18.17 or later**
112
- - **A Prepr account** — [prepr.io](https://prepr.io)
113
- - **A Prepr GraphQL URL**:
114
- 1. Go to Settings → Access tokens and open your **GraphQL Preview** access token.
115
- 2. Copy the full GraphQL URL — always `https://graphql.prepr.io/{YOUR_ACCESS_TOKEN}`.
116
- 3. Check **"Enable edit mode"** on the token and save (required for click-to-edit).
117
-
118
- Per-framework peer dependencies — all optional; installing without them is fine as long as you only import the entry points you have dependencies for:
119
-
120
- | Entry point | Peer dependencies |
121
- | --------------------------------- | ------------------------------------------------------- |
122
- | `@preprio/toolkit` (vanilla core) | none |
123
- | `@preprio/toolkit/react` | `react` >= 17, `react-dom` >= 17 |
124
- | `@preprio/toolkit/nextjs` | `next` >= 13, `react` >= 17, `react-dom` >= 17 |
125
- | `@preprio/toolkit/astro` | none (`.astro` components compile in your own pipeline) |
126
- | `@preprio/toolkit/sveltekit` | `svelte` (only for the `.svelte` components) |
127
- | `@preprio/toolkit/nuxt` | `vue` (only for the `.vue` components) |
128
-
129
- ## The preview gate
130
-
131
- Three rules hold across every framework:
132
-
133
- 1. **The toolkit reads no environment variables.** Every value reaches it as an explicit argument, so behavior is identical across frameworks and bundlers. Because the GraphQL URL embeds an access token, keep it server-side unless you intend it to be public.
134
-
135
- 2. **Preview mode is one boolean: the `preview` option you pass to the middleware.** Resolve it from whatever already distinguishes your environments — `VERCEL_ENV`, `NODE_ENV`, SvelteKit's `dev`, Astro's `import.meta.env.DEV`, a branch check, your own feature flag. A hardcoded `{ preview: true }` enables preview everywhere, **production included**.
136
-
137
- 3. **`getToolbarProps` is ungated — it fetches whenever you call it.** Gate the call on the same flag you pass the middleware:
138
-
139
- ```typescript
140
- const toolbarProps = preview ? await getToolbarProps(token) : null;
141
- ```
142
-
143
- It never throws: a failed segment fetch degrades to an empty segment list, so no `try`/`catch` or error boundary is required.
144
-
145
- ## Next.js
146
-
147
- The [Quick Start](#quick-start-nextjs) above is the complete basic setup. This section covers the extras.
148
-
149
- Despite the `create` prefix, `createPreprMiddleware` runs per request — it does not return a handler.
150
-
151
- ### Chaining with existing middleware
152
-
153
- Pass an existing `NextResponse` as the second argument to fold Prepr's headers and cookies onto a response another middleware already produced:
154
-
155
- ```typescript
156
- import { NextResponse, type NextRequest } from 'next/server';
157
- import { createPreprMiddleware } from '@preprio/toolkit/nextjs';
158
-
159
- const preview = process.env.VERCEL_ENV !== 'production';
160
-
161
- export function middleware(request: NextRequest) {
162
- const response = NextResponse.next();
163
-
164
- if (request.nextUrl.pathname.startsWith('/admin')) {
165
- response.headers.set('x-admin-route', 'true');
166
- }
167
-
168
- return createPreprMiddleware(request, response, { preview });
169
- }
170
- ```
171
-
172
- With next-intl (return its redirects before Prepr runs):
173
-
174
- ```typescript
175
- import type { NextRequest } from 'next/server';
176
- import createIntlMiddleware from 'next-intl/middleware';
177
- import { createPreprMiddleware } from '@preprio/toolkit/nextjs';
178
-
179
- const intlMiddleware = createIntlMiddleware({
180
- locales: ['en', 'de', 'fr'],
181
- defaultLocale: 'en',
182
- });
183
-
184
- const preview = process.env.VERCEL_ENV !== 'production';
185
-
186
- export function middleware(request: NextRequest) {
187
- const intlResponse = intlMiddleware(request);
188
-
189
- if (intlResponse.status >= 300 && intlResponse.status < 400) {
190
- return intlResponse;
191
- }
192
-
193
- return createPreprMiddleware(request, intlResponse, { preview });
194
- }
195
- ```
196
-
197
- To skip Prepr for some routes entirely, return early with `NextResponse.next()` before calling `createPreprMiddleware` — or exclude them in `config.matcher`.
198
-
199
- ### Tracking pixel
200
-
201
- The pixel collects the interaction data that powers personalization and A/B testing. Include it in **all** environments, preview and production alike — the Quick Start layout already does. `PreprTrackingPixel` renders nothing and loads the CDN script on mount, so its position in the tree does not matter.
202
-
203
- ### Fetching content
204
-
205
- `createPreprClient` sends codegen-typed queries to Prepr and returns Prepr's personalization verdict next to the data. It lives on its own subpath and needs the `graphql` package, which graphql-codegen already installs (otherwise: `npm install graphql`).
206
-
207
- ```typescript
208
- import { createPreprClient } from '@preprio/toolkit/nextjs/graphql';
209
- import { GetPageBySlugDocument } from '@/gql/graphql';
210
-
211
- const prepr = createPreprClient({ url: process.env.PREPR_GRAPHQL_URL! });
212
-
213
- // Same response for every visitor: goes through the Data Cache, tagged 'prepr'.
214
- const { data } = await prepr.query(GetPageBySlugDocument, { slug });
215
-
216
- // This visitor's segment / A-B variant: forwards the Prepr headers, never cached.
217
- const { data, personalized } = await prepr.query(
218
- GetPageBySlugDocument,
219
- { slug },
220
- { personalize: true },
221
- );
222
- ```
223
-
224
- Codegen's default client-preset output works as is; `documentMode: 'string'` works too.
225
-
226
- `personalized` is `true` when the queried fields contain segment variants or A/B tests, at any depth. Use it to decide whether a page can be served statically.
227
-
228
- To serve pages from the cache until you publish, set `revalidate: false` and call `revalidateTag('prepr')` from a Prepr publish webhook. With `revalidate` unset, the installed Next version's fetch caching default applies. With Cache Components, a webhook can refresh only the pages showing the changed item instead: see [Refreshing on publish](#refreshing-on-publish).
229
-
230
- Tags you pass per query in `init.next.tags` are added to the client's `cacheTags`, never in place of them.
231
-
232
- In preview, pass `preview: true`: queries skip the cache and stega markers stay in text for click-to-edit. They are always stripped from URL-like fields.
233
-
234
- Custom headers go in two places. Client-level `headers` (`createPreprClient({ url, headers })`) are sent with every request and keep queries cacheable, so use them for fixed values such as a header your proxy requires. Per-query `headers` (or `init.headers`) may carry per-visitor values, so they make that request `no-store`.
235
-
236
- #### Personalization with Cache Components
237
-
238
- With [Cache Components](https://nextjs.org/docs/app/getting-started/cache-components) (`cacheComponents: true`), a personalized page is still served from the cache, whole: every variant of every A/B test and personalization group is in the prerendered page, and each page view's decision, fetched while the page loads, shows the visitor's variant. Nothing streams, the page never waits for Prepr, and no default variant shows first to be swapped out. You keep your own query and your own components.
239
-
240
- **Do you need this?** Only if your pages are cached. A page that renders per request already gets this visitor's variants from `query(..., { personalize: true })`; render the result as is and skip this section.
241
-
242
- A normal page needs two changes, plus the [proxy](#the-proxy):
243
-
244
- ```tsx
245
- import { PreprStack } from '@preprio/toolkit/nextjs/graphql';
246
-
247
- // 1. Fetch every variant, in a cached function. Same query, one extra option.
248
- async function getPage(slug: string) {
249
- 'use cache';
250
- const { data } = await prepr.query(
251
- PageDocument,
252
- { slug },
253
- { variants: true },
254
- );
255
- return data;
256
- }
257
-
258
- export default async function Page({
259
- params,
260
- }: {
261
- params: Promise<{ slug?: string[] }>;
262
- }) {
263
- const slug = (await params).slug?.join('/') || '/';
264
- const data = await getPage(slug);
265
-
266
- // 2. Render the list through PreprStack instead of directly.
267
- return (
268
- <PreprStack
269
- items={data.Page.content}
270
- render={(items, { index }) => <Sections items={items} offset={index} />}
271
- />
272
- );
273
- }
274
- ```
275
-
276
- ##### Your components: one extra prop
277
-
278
- `PreprStack` splits the list into blocks (what never varies, each personalization group, each A/B test) and calls `render` once per block. Each call receives items exactly as a query without personalization would return them: the variant this visitor gets, with every list nested inside an item narrowed down the same way.
279
-
280
- Because `render` runs per block, a position counted inside `Sections` (`items.map((item, i) => …)`) starts at 0 in every block. `index` is where the block starts in the whole page; add it, and the first section still owns the `<h1>` and the priority image:
281
-
282
- ```tsx
283
- // Before
284
- <Sections items={data.Page.content} />
285
-
286
- // After
287
- <PreprStack
288
- items={data.Page.content}
289
- render={(items, { index }) => <Sections items={items} offset={index} />}
290
- />
291
-
292
- // Sections: the only change is `offset + i`
293
- function Sections({ items, offset = 0 }: { items: Section[]; offset?: number }) {
294
- return items.map((item, i) => <Section key={item._id} item={item} position={offset + i} />);
295
- }
296
- ```
297
-
298
- A group takes one position, whichever variant shows. A group that shows nothing to a visitor (only a segment variant, no default) still takes its position: the page is prerendered before anyone's segment is known.
299
-
300
- **The one rule:** a `variants: true` result holds every variant. Every list you render from it goes through `PreprStack`, or visitors see all variants at once.
301
-
302
- ##### Fitting your page
303
-
304
- | Your page has… | Do this |
305
- | --------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
306
- | One page-builder list (`content`, `sections`, `stack`) | One `PreprStack` around it. |
307
- | Personalized lists inside sections (cards, buttons, models in a section) | Nothing. They are narrowed down with the section they sit in. |
308
- | Several lists (hero, body, sidebar) | One `PreprStack` per list. |
309
- | A personalized list outside any list you already wrap (e.g. `Page.buttons`) | Its own `PreprStack`. |
310
- | Data used outside rendering (`generateMetadata`, JSON-LD) | `resolveVariants(data)` gives the default variants and A. |
311
- | Impression tracking for Prepr's metrics | `trackVariants` on `PreprStack`; see [Impressions and conversions](#impressions-and-conversions). |
312
- | No personalization on a page | Nothing to change. `PreprStack` renders it as is and the proxy sends no request. |
313
-
314
- ##### Impressions and conversions
315
-
316
- Prepr's tracking pixel counts impressions of an element carrying `data-prepr-variant-key`, and clicks on any `data-prepr-variant-event` element inside it ([Prepr docs](https://docs.prepr.io/personalization/setting-up-personalization#track-impressions-and-conversions)). The client already fetches every variant's key, so you never select `_context { variant_key }` yourself.
317
-
318
- Opt in with `trackVariants`, and `PreprStack` puts the key on the section each personalized and A/B variant renders:
319
-
320
- ```tsx
321
- <PreprStack items={data.Page.content} trackVariants render={…} />
322
- ```
323
-
324
- For variants nested inside a section (cards, buttons, models), and outside Next.js, spread `preprVariantProps(item)` on the element that shows the item:
325
-
326
- ```tsx
327
- <article {...preprVariantProps(card)}>…</article>
328
- ```
329
-
330
- Conversions stay your choice: put `data-prepr-variant-event` (or `data-prepr-variant-event="QuoteRequest"`) on the element that counts, for example once in your button component.
331
-
332
- - Keys are added after the page hydrates; the pixel picks them up then. Each item of a variant tags the element it renders, in order. A variant that renders a different number of elements than it has items (a section with several root elements, or one rendering nothing) tags only its first element.
333
- - With `trackVariants`, each variant sits in a `display: contents` wrapper. It takes no box, but CSS child combinators (`>`) and `:first-child` from the stack's parent no longer reach the sections.
334
- - An element that already has `data-prepr-variant-key` keeps it, so existing manual tagging keeps working.
335
- - `trackVariants` tags only the variant that is shown, once it is shown. A section holding a personalized list (a logo strip whose logos vary) gets the key of the variant it shows. Do not tag stack sections yourself (with your own `_context { variant_key }` or `preprVariantProps`): that puts a key on every variant in the page, including the invisible default that holds its space while the decision is on its way, and Prepr's pixel counts any tagged element in view, invisible or not.
336
-
337
- ##### The proxy
338
-
339
- One call in `proxy.ts` gives `PreprStack` what it needs: the visitor's Prepr headers and customer id, and the answers to the browser's decision requests: the visitor's variant of every A/B test and personalization group on a page, in one Prepr request. Pages themselves pass straight through and never wait for Prepr. Tell it which query each URL renders; most sites route every page through one query:
340
-
341
- ```ts
342
- // proxy.ts
343
- import { createPreprProxy } from '@preprio/toolkit/nextjs/graphql';
344
-
345
- const handlePrepr = createPreprProxy({
346
- client: prepr,
347
- // URL → the query that page renders with `variants: true`; null for non-CMS URLs.
348
- page: (url) => ({
349
- document: PageDocument,
350
- variables: { slug: url.pathname },
351
- }),
352
- preview: process.env.PREPR_ENV === 'preview',
353
- });
354
-
355
- export function proxy(request: NextRequest) {
356
- return handlePrepr(request); // add your own cookies or headers to this response
357
- }
358
- ```
359
-
360
- ```tsx
361
- // app/layout.tsx, once: decides every client-side navigation
362
- import { PreprPersonalizationSwitch } from '@preprio/toolkit/nextjs';
363
-
364
- <PreprPersonalizationSwitch />;
365
- ```
366
-
367
- Deriving the decision query from `PageDocument` needs Prepr's schema, which a fresh server instance downloads before its first decision. Build the decision query ahead of time instead and pass it as `decision`: the codegen plugin (see [Using your own GraphQL client](#using-your-own-graphql-client)) writes it next to your query, and the proxy sends it as is.
144
+ **5. Verify it works.**
368
145
 
369
- ```ts
370
- import { PageDecisionQuery } from './gql/prepr-queries';
371
-
372
- page: (url) => ({
373
- document: PageDocument,
374
- decision: PageDecisionQuery, // no schema download at runtime
375
- variables: { slug: url.pathname },
376
- }),
377
- ```
378
-
379
- API routes, `/_next/` and URLs whose last segment has a file extension (`/logo.png`, but also `/docs/v1.2`) are skipped. A decision request for any other URL `page` maps to a query sends one decision query; a page without groups gets an empty answer. Pass `onlyIf: (request) => boolean` to skip Prepr for some requests, such as crawlers, which then get the default variants. In preview it also sends the editor through the [draft route](#preview) first. `createPreprMiddleware` and `preprDraftRedirect` stay exported for proxies that need them separately; decision requests are answered by `createPreprProxy` only.
380
-
381
- ##### A/B tests
382
-
383
- A/B tests go through the same decision as segment groups: both variants are in the prerendered page, hidden until the page view's decision shows the visitor's one. Prepr assigns a variant per experiment, from the visitor's customer id and that experiment's split, so the decision is the only reliable source; one stored bucket per visitor cannot follow a 20/80 and a 50/50 test at once. A is the default, also for crawlers and when Prepr cannot be asked. Pass `bucket` to `PreprStack` only when the route already knows it. Under a strict Content-Security-Policy, pass `nonce` to `PreprStack`.
384
-
385
- ##### How each visitor gets their variant
386
-
387
- Every page view is decided. Nothing is reused from a prefetch, the router cache or another page's view; the browser only reuses a decision this tab already got for the same URL (see **Reuse** below).
146
+ 1. Run the site with preview on. The Prepr toolbar button shows on the right edge of the page.
147
+ 2. Pick a segment. The page updates with that segment's content.
148
+ 3. Open a content item's preview in Prepr and click text on the page. Prepr opens the field.
388
149
 
389
- - **Page loads.** The page is the same for every visitor and is sent at once, from the cache. An inline script at the start of each `PreprStack` asks the proxy for this view's decision as soon as it is parsed, so Prepr answers while the rest of the page, its styles and scripts (the tracking pixel included) still load. The personalized sections show the visitor's variant when the answer arrives; everything else never waits for it.
390
- - **Client-side navigations.** When the visitor hovers over a link (or presses it, on touch devices), `PreprPersonalizationSwitch` asks the proxy for the target page's decision. Clicks are never held: when the answer is in by the click, which hovering mostly ensures, the new page paints with the visitor's variants; otherwise its personalized sections show when the answer arrives. Prefetches still bring the page itself; only the decision is fetched.
391
- - **Never the default first.** Until a view's decision is in, its personalized sections are not shown: the default variant keeps its space, invisible, so the page does not move when the visitor's variant appears (only by any difference in height). The default variant only shows when it is the decision: for visitors in none of the segments, for requests `onlyIf` skips, and when Prepr does not answer within `timeoutMs` (default 3000). Navigations started from code ask for a decision when the page opens; the personalized sections appear when it arrives.
392
- - **Reuse.** Back and Forward show a page as this tab last showed it, at once, without asking Prepr. Any other view of a URL this tab got a decision for (kept in `sessionStorage`) shows it at once too: under 10 seconds old without asking again, since Prepr needs a few seconds to process a visitor's activity anyway; up to 30 minutes old while a new decision is asked for in the background. When that one differs, it changes only the sections still below the screen; a section the visitor can see, or has scrolled past, keeps its variant for that view, so nothing they are reading is swapped or moves under them. The next view shows the new decision. A page without personalization answers with no groups, which is trusted for an hour with no background check, so links to it cost nothing; when that page renders personalization by then (published since), it asks at once. A URL with other UTM parameters is another view; a failed answer is kept for 10 seconds and never replaces a real one.
393
- - **"Right" means what Prepr knows when the visitor clicks.** Prepr assigns segments from the visitor's tracked activity. If it has not yet processed the pixel event of the previous page view, the decision cannot include it, and the visitor sees that segment from a later page view.
394
- - **Costs.** The page carries the HTML of every variant, and an item with groups nested inside it once per combination of their variants. `render` gets `defaultVariant`: give `priority` images only to the default variant and `loading="lazy"` to the others, or the browser downloads every variant's hero image. Every page load with personalization, and every link hovered or pressed (also a press that turns into a scroll), is at most one decision request when this tab has no fresh decision for that URL, answered from Prepr's cache when other visitors had the same answer.
395
- - Without JavaScript, visitors see the default variants.
150
+ Nothing showing? See [Troubleshooting](https://github.com/preprio/prepr-toolkit/blob/main/packages/toolkit/docs/troubleshooting.md).
396
151
 
397
- ##### Deploying
152
+ ## Set up live preview
398
153
 
399
- Pages are sent without waiting for Prepr; only the personalized sections wait for their decision, and most of that time is spent at Prepr, in two steps:
154
+ Live preview shows an editor's unsaved changes in Prepr's side-by-side preview while they type. Outside the editor it does nothing and loads nothing.
400
155
 
401
- - **Who is the visitor?** For a visitor Prepr has not seen before, it first works out their segments, which takes a few hundred milliseconds on pages with segment groups. A returning visitor is resolved at once.
402
- - **The answer.** Prepr's CDN caches each decision per page, segment set and A/B bucket, and shares it between visitors who get the same. A cached answer takes tens of milliseconds; working one out takes most of a second, once per page and combination until Prepr's cache drops it.
156
+ **1. Finish the quick start for your framework.** Live preview builds on the toolbar setup.
403
157
 
404
- Under steady traffic most answers come from that cache. Your deployment adds the rest:
158
+ **2. Prepare Prepr.** Use the **GraphQL Preview** token with **Enable edit mode** checked, and set the environment's preview URL to a deployment that runs with preview on.
405
159
 
406
- - **Region.** Run your functions, the proxy included, in the region closest to your visitors and to Prepr.
407
- - **Keep connections open.** Node.js closes idle connections after a few seconds. On the Node.js runtime, give the client a `fetch` that keeps them longer; this affects only the client's own requests:
160
+ **3. Make the preview frameable.**
408
161
 
409
- ```ts
410
- import { Agent } from 'undici';
162
+ - Serve it over **HTTPS**. Inside the editor your site is a cross-site iframe; browsers keep its cookies only as `SameSite=None; Secure`, which the middleware sets on HTTPS.
163
+ - If you send a `Content-Security-Policy`, allow your Prepr environment in `frame-ancestors`, and send no `X-Frame-Options` on preview:
411
164
 
412
- const keepAlive = new Agent({ keepAliveTimeout: 60_000 });
413
- export const prepr = createPreprClient({
414
- url: process.env.PREPR_GRAPHQL_URL!,
415
- fetch: (input, init) =>
416
- fetch(input, { ...init, dispatcher: keepAlive } as RequestInit),
417
- });
165
+ ```
166
+ Content-Security-Policy: frame-ancestors 'self' https://acme.prepr.io
418
167
  ```
419
168
 
420
- - **Instances.** On Vercel, Fluid Compute reuses a function instance, and its open connections, across requests, so under steady traffic the connection stays warm. Each fresh instance pays the setup on its first request; keep instances warm with your platform's settings if your traffic is low.
421
- - **No schema at runtime.** Pass the codegen plugin's decision query as `decision` (see [The proxy](#the-proxy)), so a fresh instance does not download Prepr's schema before its first decision.
422
- - **Timeout.** When Prepr does not answer within `timeoutMs` (default 3000), the personalized sections show the default variants, with nothing swapped in later. Lower it to cap how long they can stay hidden.
423
-
424
- ##### Preview
425
-
426
- Run preview in [draft mode](https://nextjs.org/docs/app/guides/draft-mode), so editors see an edit on the next load instead of the cached page:
427
-
428
- ```ts
429
- // app/api/prepr/draft/route.ts
430
- export const GET = createPreprDraftRoute({ preview });
431
-
432
- // proxy.ts, before anything else
433
- const draft = preprDraftRedirect(request, { preview });
434
- if (draft) return draft;
435
- ```
436
-
437
- Outside preview both do nothing (the route answers 404). Keep the route out of your proxy `matcher`, or pass its path as `route` when it lives elsewhere. Inside the Prepr editor, browsers that refuse the draft cookie get the cached page instead, so keep a publish webhook (below) in place.
438
-
439
- ##### Refreshing on publish
440
-
441
- `revalidateTag('prepr')` refreshes every Prepr page on every publish. To refresh only the pages that show the changed item, tag each cached page with its items and let a Prepr webhook revalidate the item's tag.
442
-
443
- 1. **Tag the page with its items.** Add `tagItems: true` to the query inside `'use cache'`. The entry gets a `prepr:<_id>` tag for every item in the result, at any depth; with `variants: true` that is every variant's items, so a change to any variant reaches the page.
444
-
445
- ```tsx
446
- async function getPage(slug: string) {
447
- 'use cache';
448
- const { data } = await prepr().query(
449
- GetPageBySlugDocument,
450
- { slug },
451
- { variants: true, tagItems: true },
452
- );
453
- return data;
454
- }
455
- ```
456
-
457
- With your own client, call `cacheTag(...preprCacheTags(data))` inside `'use cache'` instead.
458
-
459
- 2. **New items are covered too.** A new item is in no cached result yet, so `tagItems` also tags two kinds of query with their model's `prepr:model:<model>` tag, which a publish of any item of that model revalidates:
460
- - list queries (`Posts { items { … } }`), so a new post joins the list;
461
- - lookups that found nothing (`Page(slug: "new")` returning `null`), so publishing that page replaces the cached "not found".
462
-
463
- Other pages that depend on which items exist (a sitemap, a count) can add the tag themselves:
464
-
465
- ```ts
466
- import { cacheTag } from 'next/cache';
467
- import { preprModelTag } from '@preprio/toolkit/nextjs/graphql';
468
-
469
- cacheTag(preprModelTag('Post')); // the model's name in Prepr or its GraphQL type
470
- ```
471
-
472
- The model name is compared without case, spaces or punctuation, so `'Blog post'` (what webhooks send) and `BlogPost` (the GraphQL type) give the same tag. A model whose API ID was renamed away from its name does not match.
473
-
474
- 3. **Add the webhook route.**
475
-
476
- ```ts
477
- // app/api/prepr/webhook/route.ts
478
- import { createPreprWebhookRoute } from '@preprio/toolkit/nextjs';
479
-
480
- export const POST = createPreprWebhookRoute({
481
- secret: process.env.PREPR_WEBHOOK_SECRET,
482
- });
483
- ```
484
-
485
- Keep the route out of your proxy `matcher`.
486
-
487
- 4. **Create the webhook in Prepr.** Under **Settings → Webhooks**, add `https://<your-site>/api/prepr/webhook` with the events `content_item.published`, `content_item.unpublished`, `content_item.deleted` and `content_item.invalidated`, plus `asset.changed`, `asset.deleted` and `schema.changed`. Other events are acknowledged and ignored, so subscribing to more does no harm. Save, then copy the webhook's **ID** into `PREPR_WEBHOOK_SECRET`: Prepr signs every request with it.
488
-
489
- The route checks the `Prepr-Signature` header (an HMAC-SHA256 of the body, keyed with the webhook ID, as hex or base64) and answers 401 to a missing or wrong signature, or to a request older than five minutes. A valid event revalidates:
490
-
491
- | Tag | When | Reaches |
492
- | --------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- |
493
- | `prepr:<id>` | `content_item.published`, `.unpublished`, `.deleted`, `.invalidated`; `asset.changed`, `.deleted` | pages showing that item or asset |
494
- | `prepr:model:<model>` | `content_item.published`, `.unpublished`, `.deleted` | list queries, lookups that found nothing, pages tagged by you |
495
- | `prepr:any` | the same events as `prepr:<id>` | pages with more items than Next.js's tag limit |
496
- | `prepr:schema` | `schema.changed` | the schema the client rewrites queries with |
497
-
498
- Draft edits (`content_item.changed`, `.created`), visitor and segment events revalidate nothing: they change no published page.
499
-
500
- Revalidation uses `revalidateTag(tag, { expire: 0 })`, so the next request after a publish gets the new page. Pass `profile: 'max'` to serve the old page once more while the new one renders in the background.
501
-
502
- Next.js accepts at most 128 tags per `cacheTag()` call. A page with more items is tagged `prepr:any` instead (`PREPR_ANY_ITEM_TAG`), so it refreshes on every event, as with `revalidateTag('prepr')`. The response lists the revalidated tags, which Prepr shows on the webhook's detail page.
503
-
504
- `tagItems` makes that query skip the Data Cache: a Data Cache entry carries only the client's `cacheTags`, so after an item tag is revalidated, the `'use cache'` function would re-run against the stale response. The `'use cache'` entry is the cache. The client's `cacheTags` still apply to the entry, so `revalidateTag('prepr')` keeps refreshing everything. `tagItems` needs Next.js 16 and throws outside a `'use cache'` function.
505
-
506
- <details>
507
- <summary>How it works</summary>
508
-
509
- - **`variants: true`** adds `personalize: false` to every personalizable field in your query, at any depth, and selects each item's `_context`. The client learns which fields are personalizable from one schema introspection request per client, kept in the Data Cache.
510
- - **Decisions** send your query cut down to the lists that hold segment groups, selecting only `_context`, with the visitor's headers and never cached. Prepr decides from everything the middleware forwards: customer profile, UTM parameters, visitor IP, HubSpot id. A page without segment groups makes no request. `prepr.decide()` does the same inside a render, for rendering variants yourself with `resolveVariants`; `PreprStack` does not need it.
511
- - **`PreprStack`** renders every variant of each segment group, and each item with groups nested inside it once per combination of their variants, in `display: contents` wrappers that stay hidden until the view's decision marks one to show. A group with no default variant still gets its place.
512
- - **A/B variants** are both in the HTML and picked by the same decision as segment groups. A hidden variant never becomes visible, so the tracking pixel records no impression for it.
513
- - **`hasAbTests`** sends your query without its leaf fields and no visitor headers, so Prepr's CDN caches it, and reads the answer from the `Vary` header. Answers are reused for a minute.
514
- - **Tags carry over.** The client's `'prepr'` fetch tag applies to the `'use cache'` entry, so `revalidateTag('prepr')` refreshes it without a `cacheTag()` call. `tagItems` adds a tag per item; see [Refreshing on publish](#refreshing-on-publish).
515
- - **Outside `'use cache'`, set `revalidate`** on the client (`false` or seconds). Otherwise a query outside both `'use cache'` and `<Suspense>` fails the build with "uncached data was accessed outside of `<Suspense>`".
516
-
517
- </details>
518
-
519
- `examples/nextjs-cache-components` is a runnable version.
520
-
521
- Do not catch and swallow errors from `query` without [`unstable_rethrow`](https://nextjs.org/docs/app/api-reference/functions/unstable_rethrow): Next.js signals dynamic rendering by throwing from inside `fetch`, and the client passes those signals through.
522
-
523
- #### Using your own GraphQL client
524
-
525
- Everything the toolkit's client does for personalization is two query rewrites and one helper. Use them with any client: Apollo, urql, or plain `fetch`.
526
-
527
- 1. **Variants query** (same for every visitor, cache it): `toVariantsQuery(query, schema)`.
528
- 2. **Decision query** (per visitor, never cached, with the visitor's Prepr headers): `toDecisionQuery(query, schema, { from: variantsData })`, then `decisionsFrom(data)`.
529
- 3. **Render** with `PreprStack` (Next.js) or `resolveVariants(data, { decisions, bucket })` anywhere.
530
-
531
- The rewrites need to know which fields take `personalize`: `loadPreprSchema(url)` fetches that once and keeps it in memory.
532
-
533
- ```ts
534
- import {
535
- decisionsFrom,
536
- loadPreprSchema,
537
- resolveVariants,
538
- toDecisionQuery,
539
- toVariantsQuery,
540
- } from '@preprio/toolkit/graphql';
541
-
542
- const url = process.env.PREPR_GRAPHQL_URL!;
543
- const schema = await loadPreprSchema(url);
544
-
545
- async function post(
546
- query: string,
547
- variables: object,
548
- headers: HeadersInit = {},
549
- ) {
550
- const res = await fetch(url, {
551
- method: 'POST',
552
- headers: { 'Content-Type': 'application/json', ...headers },
553
- body: JSON.stringify({ query, variables }),
554
- });
555
- const json = await res.json();
556
- if (!res.ok || json.errors)
557
- throw new Error(`Prepr GraphQL request failed (${res.status})`);
558
- return json.data;
559
- }
560
-
561
- const variables = { slug: '/' };
562
- const page = await post(toVariantsQuery(PAGE_QUERY, schema), variables); // cacheable
563
-
564
- const decisionQuery = toDecisionQuery(PAGE_QUERY, schema, { from: page });
565
- const decisions = decisionQuery
566
- ? decisionsFrom(await post(decisionQuery, variables, visitorPreprHeaders))
567
- : new Map();
568
-
569
- const content = resolveVariants(page.Page.content, { decisions, bucket });
570
- ```
571
-
572
- `visitorPreprHeaders` are the headers the middleware forwards (`getPreprHeaders()` in Next.js); `bucket` is the visitor's A/B bucket, when you know it; leave it out and A/B tests use the decision too (see below).
573
-
574
- With Apollo, parse the strings once and use them like any document:
575
-
576
- ```ts
577
- import { gql } from '@apollo/client';
578
-
579
- const PageVariants = gql(toVariantsQuery(PAGE_QUERY, schema));
580
- const { data: page } = await client.query({ query: PageVariants, variables });
581
-
582
- const decisionQuery = toDecisionQuery(PAGE_QUERY, schema, { from: page });
583
- const decisions = decisionQuery
584
- ? decisionsFrom(
585
- (
586
- await client.query({
587
- query: gql(decisionQuery),
588
- variables,
589
- context: { headers: visitorPreprHeaders },
590
- fetchPolicy: 'no-cache', // per visitor: never from Apollo's cache
591
- })
592
- ).data,
593
- )
594
- : new Map();
595
- ```
596
-
597
- **At build time with graphql-codegen.** The plugin writes both queries per named query into a file, so nothing is rewritten and no schema is loaded at runtime:
169
+ **4. Select `_id` in your queries.** Changes are matched by id. With GraphQL Codegen, one line adds it everywhere your schema has one:
598
170
 
599
171
  ```ts
600
172
  // codegen.ts
601
- generates: {
602
- 'src/gql/prepr-queries.ts': {
603
- plugins: ['@preprio/toolkit/graphql/codegen'],
604
- },
605
- },
606
- ```
607
-
608
- ```ts
609
- import {
610
- GetPageBySlugDecisionQuery,
611
- GetPageBySlugVariantsQuery,
612
- } from './gql/prepr-queries';
613
- ```
614
-
615
- Only named queries with personalizable fields get exports; two queries with the same name fail the run. The generated decision query asks about every personalizable list. When you have the variants result at hand, `toDecisionQuery(query, schema, { from })` is smaller and markedly faster for visitors Prepr has not seen before.
616
-
617
- A decision query without `from` also returns the visitor's variant of each A/B test, per experiment and its split; `from` limits it to the lists with segment groups. Otherwise pass a known bucket to `resolveVariants`.
173
+ import { preprIds } from '@preprio/toolkit/codegen';
618
174
 
619
- ### Image loader
620
-
621
- Prepr's stream CDN resizes at the edge. Routing `next/image` through the bundled loader makes Next request the exact width it needs, instead of pulling the full-resolution original and re-encoding it through `/_next/image`.
622
-
623
- Next joins `loaderFile` against the app root and checks it with `existsSync`, so a bare package specifier will not resolve. Add a one-line wrapper file in your app root:
624
-
625
- ```typescript
626
- // prepr-image-loader.ts
627
- export { default } from '@preprio/toolkit/nextjs/image-loader';
628
- ```
629
-
630
- ```typescript
631
- // next.config.ts
632
- export default {
633
- images: {
634
- loader: 'custom',
635
- loaderFile: './prepr-image-loader.ts',
175
+ const config = {
176
+ generates: {
177
+ 'src/gql/': { preset: 'client', documentTransforms: [preprIds] },
636
178
  },
637
179
  };
638
180
  ```
639
181
 
640
- The API emits each asset's real dimensions, so a Prepr URL renders as-is:
641
-
642
- ```
643
- https://393qibegr87z.b-cdn.net/w_800,h_600,fx_75,fy_67/b7ijwafd586-photo.jpg
644
- ```
645
-
646
- The loader rewrites `w_` to the width Next asks for and scales `h_` alongside it, holding the emitted ratio — for a cropped asset that ratio is the authored crop box, so the crop survives the resize. Focal points (`fx`/`fy`) are percentages and carry through unchanged, as does any other option in the segment. Quality is not a CDN option and is ignored. URLs with no transform segment pass through untouched — set `unoptimized` on those `<Image>`s.
647
-
648
- See the runnable example at `examples/nextjs` for the full source of truth.
649
-
650
- ## Astro
651
-
652
- **`src/middleware.ts`**
653
-
654
- ```typescript
655
- import { onPreprRequest } from '@preprio/toolkit/astro';
656
- import { defineMiddleware } from 'astro:middleware';
657
-
658
- export const onRequest = defineMiddleware((context, next) =>
659
- onPreprRequest(context, next, { preview: import.meta.env.DEV }),
660
- );
661
- ```
662
-
663
- **Layout** — the same preview flag gates `getToolbarProps`:
664
-
665
- ```astro
666
- ---
667
- import PreprToolbar from '@preprio/toolkit/astro/components/PreprToolbar';
668
- import PreprTrackingPixel from '@preprio/toolkit/astro/components/PreprTrackingPixel';
669
- import { extractAccessToken, getToolbarProps } from '@preprio/toolkit/astro';
670
-
671
- const preview = import.meta.env.DEV;
672
- const toolbarProps = preview
673
- ? await getToolbarProps(Astro.request.headers, import.meta.env.PREPR_GRAPHQL_URL)
674
- : null;
675
- const accessToken = extractAccessToken(import.meta.env.PREPR_GRAPHQL_URL);
676
- ---
677
-
678
- <html lang="en">
679
- <body>
680
- <slot />
681
- {toolbarProps && <PreprToolbar {...toolbarProps} />}
682
- {accessToken && <PreprTrackingPixel id={accessToken} />}
683
- </body>
684
- </html>
685
- ```
686
-
687
- **Data fetching** — the Astro helpers are synchronous and take the request's `Headers`:
688
-
689
- ```typescript
690
- import { getPreprHeaders } from '@preprio/toolkit/astro';
691
-
692
- const headers = getPreprHeaders(Astro.request.headers);
693
- ```
694
-
695
- Or let the client forward the headers (needs `graphql`, see [Fetching content](#fetching-content)):
696
-
697
- ```typescript
698
- import { createPreprClient } from '@preprio/toolkit/astro/graphql';
699
-
700
- const prepr = createPreprClient({ url: import.meta.env.PREPR_GRAPHQL_URL });
701
- const { data } = await prepr.query(
702
- GetPageBySlugDocument,
703
- { slug },
704
- { personalize: true, event: Astro },
705
- );
706
- ```
707
-
708
- `import.meta.env.DEV` is Astro's own dev flag; swap in whatever signal marks preview in your deployment.
709
-
710
- The `.astro` components ship as source, compiled by your own Astro/Vite pipeline. They use full-page navigation by default, matching Astro's MPA model — switching segment or variant re-runs the server-rendered output.
711
-
712
- See the runnable example at `examples/astro` for the full source of truth.
713
-
714
- ## SvelteKit
715
-
716
- **`src/hooks.server.ts`**
717
-
718
- ```typescript
719
- import { dev } from '$app/environment';
720
- import { preprHandle } from '@preprio/toolkit/sveltekit';
721
-
722
- export const handle = preprHandle({ preview: dev });
723
- ```
724
-
725
- **`src/routes/+layout.server.ts`** — the same flag gates `getToolbarProps`:
726
-
727
- ```typescript
728
- import { dev } from '$app/environment';
729
- import { env } from '$env/dynamic/private';
730
- import { getToolbarProps } from '@preprio/toolkit/sveltekit';
731
- import type { LayoutServerLoad } from './$types';
732
-
733
- export const load: LayoutServerLoad = async ({ request }) => {
734
- if (!dev) return { toolbarProps: null };
735
-
736
- const toolbarProps = await getToolbarProps(
737
- request.headers,
738
- env.PREPR_GRAPHQL_URL!,
739
- );
740
- return { toolbarProps };
741
- };
742
- ```
743
-
744
- **`src/routes/+layout.svelte`**
745
-
746
- ```svelte
747
- <script lang="ts">
748
- import PreprToolbar from '@preprio/toolkit/sveltekit/components/PreprToolbar';
749
- import PreprTrackingPixel from '@preprio/toolkit/sveltekit/components/PreprTrackingPixel';
750
- import type { LayoutData } from './$types';
182
+ No Codegen? See [the other two ways](https://github.com/preprio/prepr-toolkit/blob/main/packages/toolkit/docs/live-preview.md#preparing-your-queries).
751
183
 
752
- let { data, children }: { data: LayoutData; children: import('svelte').Snippet } = $props();
753
- </script>
184
+ **5. Run your query results through the live preview helper**, with your preview flag as `enabled`:
754
185
 
755
- {@render children()}
756
- <PreprTrackingPixel id="YOUR_ACCESS_TOKEN" />
757
- {#if data.toolbarProps}
758
- <PreprToolbar {...data.toolbarProps} />
759
- {/if}
760
- ```
761
-
762
- **Data fetching** — in `load` functions and endpoints, read the headers the hook already computed off `event.locals`:
186
+ | Framework | Code |
187
+ | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
188
+ | Next.js | `await normalizeQuery(GetPageDocument, data, { enabled: preview })` from `@preprio/toolkit/nextjs`, plus `<PreprRefresh enabled />` from `@preprio/toolkit/nextjs/live` in the root layout |
189
+ | Astro | `normalizeQuery(GetPageDocument, data, { enabled: preview, locals: Astro.locals })` from `@preprio/toolkit/astro` |
190
+ | SvelteKit | `normalizedQuery(GetPageDocument, data.result, { enabled: data.preview, onSave: invalidateAll })` from `@preprio/toolkit/sveltekit/live` |
191
+ | Nuxt | `useNormalizedQuery(GetPageDocument, data, { enabled: preview, onSave: refresh })` from `@preprio/toolkit/nuxt/live` |
763
192
 
764
- ```typescript
765
- import { getPreprHeadersFromLocals } from '@preprio/toolkit/sveltekit';
193
+ Full snippets per framework: [Next.js](https://github.com/preprio/prepr-toolkit/blob/main/packages/toolkit/docs/nextjs.md#live-preview) · [Astro](https://github.com/preprio/prepr-toolkit/blob/main/packages/toolkit/docs/astro.md#live-preview) · [SvelteKit](https://github.com/preprio/prepr-toolkit/blob/main/packages/toolkit/docs/sveltekit.md#live-preview) · [Nuxt](https://github.com/preprio/prepr-toolkit/blob/main/packages/toolkit/docs/nuxt.md#live-preview).
766
194
 
767
- const preprHeaders = getPreprHeadersFromLocals(event.locals);
768
- ```
769
-
770
- Or let the client forward them (needs `graphql`, see [Fetching content](#fetching-content)). Passing the event also routes the request through `event.fetch`:
771
-
772
- ```typescript
773
- import { createPreprClient } from '@preprio/toolkit/sveltekit/graphql';
774
-
775
- const prepr = createPreprClient({ url: env.PREPR_GRAPHQL_URL });
776
-
777
- export const load: PageServerLoad = async (event) => {
778
- const { data } = await prepr.query(
779
- GetPageBySlugDocument,
780
- { slug: event.params.slug },
781
- { personalize: true, event },
782
- );
783
- return { page: data.Page };
784
- };
785
- ```
786
-
787
- The `.svelte` components ship as source (compiled by your own Vite/Svelte pipeline) and mount client-side via `onMount`, so they never run during SSR.
788
-
789
- See the runnable example at `examples/sveltekit` for the full source of truth.
790
-
791
- ## Nuxt
792
-
793
- Requires Nitro's Node.js preset (the Nuxt default).
794
-
795
- **`server/middleware/prepr.ts`**
796
-
797
- ```typescript
798
- import { handlePreprRequest } from '@preprio/toolkit/nuxt';
799
-
800
- export default defineEventHandler((event) => {
801
- handlePreprRequest(event, { preview: import.meta.dev });
802
- });
803
- ```
804
-
805
- **`app/app.vue`** — resolve the toolbar props on the server, gated on the same flag:
806
-
807
- ```vue
808
- <script setup lang="ts">
809
- import { getToolbarProps } from '@preprio/toolkit/nuxt';
810
- import PreprToolbar from '@preprio/toolkit/nuxt/components/PreprToolbar';
811
- import PreprTrackingPixel from '@preprio/toolkit/nuxt/components/PreprTrackingPixel';
812
-
813
- const requestHeaders = useRequestHeaders();
814
- const { data: toolbarProps } = await useAsyncData('prepr-toolbar', async () => {
815
- if (!import.meta.dev) return null;
816
- return getToolbarProps(
817
- new Headers(requestHeaders as Record<string, string>),
818
- useRuntimeConfig().public.preprGraphqlUrl,
819
- );
820
- });
821
- </script>
822
-
823
- <template>
824
- <NuxtPage />
825
- <PreprTrackingPixel id="YOUR_ACCESS_TOKEN" />
826
- <PreprToolbar v-if="toolbarProps" v-bind="toolbarProps" />
827
- </template>
828
- ```
829
-
830
- **Data fetching** — the middleware folds the computed Prepr headers back onto the incoming request. Read them via `useRequestHeaders()` in composables, or straight off the h3 event in server routes:
831
-
832
- ```typescript
833
- import { getPreprHeadersFromEvent } from '@preprio/toolkit/nuxt';
834
-
835
- const preprHeaders = getPreprHeadersFromEvent(event);
836
- ```
837
-
838
- Or let the client forward them from a server route (needs `graphql`, see [Fetching content](#fetching-content)):
839
-
840
- ```typescript
841
- // server/api/page.get.ts
842
- import { createPreprClient } from '@preprio/toolkit/nuxt/graphql';
843
-
844
- const prepr = createPreprClient({ url: useRuntimeConfig().preprGraphqlUrl });
845
-
846
- export default defineEventHandler(async (event) => {
847
- const { data } = await prepr.query(
848
- GetPageBySlugDocument,
849
- { slug: getQuery(event).slug },
850
- { personalize: true, event },
851
- );
852
- return data;
853
- });
854
- ```
855
-
856
- `personalize: true` needs the h3 event. During client-side navigation there is none and the query throws `CONTEXT_ERROR`, so run personalized queries in server routes.
857
-
858
- The `.vue` components ship as source (compiled by your own Vite/Vue pipeline) and mount client-side via `onMounted`, so they never run during SSR.
859
-
860
- See the runnable example at `examples/nuxt` for the full source of truth.
861
-
862
- ## React (no framework)
863
-
864
- `@preprio/toolkit/react` carries the two components that need nothing but React — for Vite + React Router, TanStack Router, Remix SPA mode, or Create React App. Next.js users want the [Next.js section](#nextjs) instead; its `PreprToolbar` binds the App Router for you.
865
-
866
- ```tsx
867
- import { PreprPreview, PreprTrackingPixel } from '@preprio/toolkit/react';
868
-
869
- export function App() {
870
- return (
871
- <>
872
- <YourRoutes />
873
- {import.meta.env.DEV && <PreprPreview />}
874
- <PreprTrackingPixel id={import.meta.env.VITE_PREPR_TRACKING_ID} />
875
- </>
876
- );
877
- }
878
- ```
879
-
880
- Mount `PreprPreview` once per page — two copies start two editor bridges.
881
-
882
- ### Without personalization
883
-
884
- A client-rendered app with no segments and no A/B testing needs **no middleware and no server helpers at all**. The middleware exists to resolve segment and variant cookies into request headers; with both features off there are no headers to resolve. What remains — click-to-edit and the editor's scroll restore — is purely client-side:
885
-
886
- ```tsx
887
- <PreprPreview options={{ features: { segments: false, abTesting: false } }} />
888
- ```
889
-
890
- No `navigation` prop or router context is needed in this configuration; the component can mount anywhere in the tree.
891
-
892
- ### With personalization
893
-
894
- Segments and A/B testing need request headers, which need a server — either a framework with one (React Router in framework mode, Next.js) or your own backend using the [vanilla core](#any-other-framework).
895
-
896
- Once there is a server, pass a `navigation` adapter so segment and variant switches route softly instead of reloading:
897
-
898
- ```tsx
899
- import { useNavigate, useLocation } from 'react-router';
900
-
901
- const navigate = useNavigate();
902
- const location = useLocation();
903
-
904
- <PreprPreview
905
- {...toolbarProps}
906
- navigation={{
907
- navigate: (url) => navigate(url),
908
- currentPath: () => location.pathname + location.search,
909
- }}
910
- />;
911
- ```
912
-
913
- `navigation.reload` is optional and defaults to `window.location.reload()`. React Router has no soft-refresh equivalent, so leaving it unset is usually right.
914
-
915
- ### Tracking pageviews
916
-
917
- `loadTrackingPixel` queues one `pageload` event when it installs. Client-side route changes emit nothing on their own, so fire them yourself:
918
-
919
- ```tsx
920
- import { useEffect } from 'react';
921
- import { useLocation } from 'react-router';
922
- import { trackEvent } from '@preprio/toolkit';
923
-
924
- function usePreprPageviews() {
925
- const { pathname } = useLocation();
926
-
927
- useEffect(() => {
928
- trackEvent('pageload');
929
- }, [pathname]);
930
- }
931
- ```
932
-
933
- This double-counts the first pageview, since the pixel's own install event fires too. Skip the initial run with a ref if the exact count matters.
934
-
935
- The `id` is your access token, and in a client-rendered app it is public — bundled into JS and visible in devtools. Use a tracking-only token; do not derive it from a browser-exposed GraphQL URL, which would also expose content read access.
936
-
937
- ## Any other framework
938
-
939
- The core is runtime-neutral: it works off a WHATWG `Request` and hands back the headers to forward to Prepr plus the cookies to persist. Adapting it to Express, Hono, Fastify, or a plain server is roughly twenty lines.
940
-
941
- **Server** — translate your framework's request and response to and from those neutral shapes:
942
-
943
- ```javascript
944
- import { processPreprRequest } from '@preprio/toolkit';
945
-
946
- export function preprMiddleware({ preview } = {}) {
947
- return (req, res, next) => {
948
- const { requestHeaders, responseCookies } = processPreprRequest(
949
- toWebRequest(req),
950
- {
951
- preview,
952
- },
953
- );
954
-
955
- for (const cookie of responseCookies) {
956
- res.cookie(cookie.name, cookie.value, {
957
- maxAge: cookie.maxAge * 1000,
958
- path: cookie.path,
959
- });
960
- }
961
-
962
- res.locals.preprHeaders = requestHeaders;
963
- next();
964
- };
965
- }
966
- ```
967
-
968
- Forward the headers on your GraphQL fetch with `getPreprHeadersFromHeaders(requestHeaders)`, and resolve toolbar props with `getToolbarPropsFromHeaders(requestHeaders, graphqlUrl)`.
969
-
970
- **Client** — mount the toolbar imperatively:
971
-
972
- ```javascript
973
- import { createPreprPreview, loadTrackingPixel } from '@preprio/toolkit';
974
-
975
- loadTrackingPixel('YOUR_ACCESS_TOKEN');
976
-
977
- const controller = createPreprPreview({ props: toolbarProps });
978
- // later: controller.destroy()
979
- ```
980
-
981
- Serialize the server-computed props into the page — a `<script type="application/json">` tag works well — and read them back on the client. See the runnable example at `examples/express` for the full source of truth.
982
-
983
- ## API Reference
984
-
985
- ### Framework server helpers
986
-
987
- Each wrapper exposes the same five helpers, differing only in how they reach the request headers. The Next.js versions read `next/headers` and are async; the Astro, SvelteKit, and Nuxt versions take a standard `Headers` (`Astro.request.headers`, `event.request.headers`, or one built from `useRequestHeaders()`) and are sync, except `getToolbarProps`.
988
-
989
- | Helper | Next.js | Astro / SvelteKit / Nuxt | Returns |
990
- | ------------------ | ------------------------------ | --------------------------------------- | ------------------------------------------------------------------------------------------------------- |
991
- | `getPreprUUID` | `await getPreprUUID()` | `getPreprUUID(headers)` | Visitor's Prepr Customer ID, or `null` when the middleware did not run for this request. |
992
- | `getActiveSegment` | `await getActiveSegment()` | `getActiveSegment(headers)` | Active segment ID, or `null`. |
993
- | `getActiveVariant` | `await getActiveVariant()` | `getActiveVariant(headers)` | `'A'`, `'B'`, or `null`. |
994
- | `getPreprHeaders` | `await getPreprHeaders()` | `getPreprHeaders(headers)` | All Prepr headers as an object, ready to spread into a fetch. |
995
- | `getToolbarProps` | `await getToolbarProps(token)` | `await getToolbarProps(headers, token)` | `{ activeSegment, activeVariant, segments }`. Never throws — failures degrade to an empty segment list. |
996
-
997
- `getPreprUUID()` returning `null` is a useful check when headers seem to be missing — it means the middleware did not cover the route.
998
-
999
- ### GraphQL client
1000
-
1001
- `createPreprClient(options)` ships on `@preprio/toolkit/graphql` and on each framework's `/graphql` subpath (`@preprio/toolkit/nextjs/graphql`, `/nuxt/graphql`, `/sveltekit/graphql`, `/astro/graphql`). These subpaths need the `graphql` package (`>=16`); nothing else in the toolkit does. The core version takes explicit `headers`; the framework versions add `personalize`.
1002
-
1003
- | Option | Default | Effect |
1004
- | ---------------------- | --------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
1005
- | `url` | — | Full `https://graphql.prepr.io/<token>` URL. Throws `PreprError` when invalid. |
1006
- | `preview` | `false` | Every query is `no-store`; stega defaults to `'urls'`. |
1007
- | `stega` | `'urls'` in preview, else `'all'` | Which strings get stega markers stripped: URL-like keys only, all, or `'none'`. |
1008
- | `fetch` | global `fetch` | Custom fetch. Also accepted per query. |
1009
- | `fastlyQuery` | `false` | Send queries as a GET with a `Fastly-Query` header, served by Prepr's edge. Opt-in: undocumented Prepr behavior. |
1010
- | `headers` | — | Sent with every request. Fixed per client, so queries stay cacheable. |
1011
- | `cacheTags` (Next.js) | `['prepr']` | Tags on cacheable fetches. |
1012
- | `revalidate` (Next.js) | unset | `next.revalidate` on cacheable fetches. |
1013
-
1014
- `query(document, variables?, options?)` takes a query string, a `TypedDocumentString` or a `DocumentNode`, and resolves to `{ data, personalized }`. Per-query options: `headers`, `init`, `fetch`, plus `personalize` (framework versions), `tagItems` (Next.js 16, inside `'use cache'`) and `event` (Nuxt, SvelteKit, Astro). A request carrying per-query headers or `init.headers` is `no-store`; client-level `headers` are not.
1015
-
1016
- Import `PreprError` from the same subpath as the client when checking `instanceof`: CommonJS entry points do not share classes. `error.code` works from anywhere.
1017
-
1018
- `isPersonalizedResponse(response)`, exported from every entry point, reads the same verdict from a response fetched with your own client. It does not need `graphql`.
1019
-
1020
- For your own GraphQL client (see [Using your own GraphQL client](#using-your-own-graphql-client)), every `/graphql` subpath also exports:
1021
-
1022
- | Function | Returns |
1023
- | ---------------------------------------------------------- | -------------------------------------------------------------------------------------- |
1024
- | `loadPreprSchema(url, { fetch? })` | What the rewrites need from your schema, loaded once per URL. Failures are not cached. |
1025
- | `toVariantsQuery(query, schema)` | The variants query as a string: what `variants: true` sends. |
1026
- | `toDecisionQuery(query, schema, { from?, topLevelOnly? })` | The per-visitor decision query as a string, or `null` when there is nothing to decide. |
1027
- | `decisionsFrom(data)` | Decisions from a decision query's `data`, for `resolveVariants` or `PreprStack`. |
1028
- | `preprCacheTags(data)` | `prepr:<_id>` for every item in a result, or `['prepr:any']` past 128 items. |
1029
- | `preprModelTag(model)` | `prepr:model:<model>`, for list pages. |
1030
-
1031
- `@preprio/toolkit/graphql/codegen` is a graphql-codegen plugin that writes `<Name>VariantsQuery` and `<Name>DecisionQuery` for every named query with personalizable fields.
1032
-
1033
- ### Token helpers
1034
-
1035
- Exported from every entry point, including the core.
1036
-
1037
- - **`validatePreprToken(token)`** — asserts a Prepr GraphQL URL is well formed. Returns nothing; **throws** `PreprError` on a bad value (`MISSING_TOKEN` when empty, `INVALID_TOKEN` when not an HTTPS URL).
1038
- - **`extractAccessToken(url)`** — extracts the access token from a Prepr GraphQL URL — the value `PreprTrackingPixel` needs as its `id`. Always returns a `string`; a URL that is malformed, not on `graphql.prepr.io`, or missing a token segment throws `PreprError(INVALID_TOKEN)`.
1039
-
1040
- ```typescript
1041
- const token = extractAccessToken('https://graphql.prepr.io/abc123');
1042
- // 'abc123'
1043
- ```
1044
-
1045
- ### Components
1046
-
1047
- #### `PreprToolbar`
1048
-
1049
- The toolbar. Takes the props returned by `getToolbarProps`, and renders nothing itself — the UI is a shadow-DOM custom element mounted imperatively. There is no provider to wrap your tree in; state lives in the toolbar's own store.
1050
-
1051
- ```tsx
1052
- <PreprToolbar {...toolbarProps} />
1053
- ```
1054
-
1055
- #### `PreprPersonalizationSwitch`
1056
-
1057
- From `@preprio/toolkit/nextjs`. Gets each client-side navigation's decision in before the click: when the visitor hovers over a same-site link (or presses it, on touch devices), it asks `createPreprProxy` for the target page's decision. Clicks are never held (see [How each visitor gets their variant](#how-each-visitor-gets-their-variant)). Mount it once in the root layout, so links on pages without a `PreprStack` are covered too. Links to other sites and links that open a new tab or download are left alone. The decision requests are answered by `createPreprProxy` only. Takes no props and renders nothing.
1058
-
1059
- #### `PreprPreview`
1060
-
1061
- From `@preprio/toolkit/react`. The framework-free equivalent of `PreprToolbar`: same preview runtime, with the router binding left to you. Renders nothing.
1062
-
1063
- | Prop | Type | Description |
1064
- | ---------------------------------------------- | ------------------------ | ----------------------------------------------------------------------------------------------------------------------- |
1065
- | `activeSegment` / `activeVariant` / `segments` | — | Toolbar data, as returned by `getToolbarProps`. Optional for a headless preview. |
1066
- | `options` | `PreprPreviewOptions` | Feature flags, `ui`, locale, debug (see [Preview options](#preview-options)). |
1067
- | `navigation` | `PreprNavigationAdapter` | Optional router binding. Defaults to `window.location`, which is correct for any router that keeps the URL bar in sync. |
1068
-
1069
- Every prop is read once on mount; changing one afterwards has no effect, since a live update would have to tear down the editor bridge and re-announce the preview. Remount to change configuration.
1070
-
1071
- #### `PreprTrackingPixel`
1072
-
1073
- Loads Prepr's CDN tracking pixel on mount. Renders nothing. Exported from both `@preprio/toolkit/react` and `@preprio/toolkit/nextjs` — the same component, with nothing Next-specific about it.
1074
-
1075
- ```tsx
1076
- <PreprTrackingPixel
1077
- id={accessToken}
1078
- config={{ destinations: { googleTagManager: true } }}
1079
- />
1080
- ```
1081
-
1082
- | Prop | Type | Description |
1083
- | -------- | ------------------ | ------------------------------------------------------------------- |
1084
- | `id` | `string` | Prepr tracking/access token. Required. |
1085
- | `config` | `PreprPixelConfig` | Optional pixel configuration (see [Pixel options](#pixel-options)). |
1086
-
1087
- ### Core exports
1088
-
1089
- Available from `@preprio/toolkit` for apps outside the supported frameworks.
1090
-
1091
- #### `processPreprRequest(request, options?)`
1092
-
1093
- Computes the Prepr headers and cookies for a WHATWG `Request`.
1094
-
1095
- ```typescript
1096
- const { requestHeaders, responseCookies } = processPreprRequest(request, {
1097
- preview: true,
1098
- });
1099
- // requestHeaders: Headers — forward downstream and on to Prepr
1100
- // responseCookies: CookieSpec[] — { name, value, maxAge, path }
1101
- ```
1102
-
1103
- #### `createPreprPreview(options)`
1104
-
1105
- Starts the preview runtime — optionally mounting the toolbar — and returns a controller.
1106
-
1107
- ```typescript
1108
- const controller = createPreprPreview({
1109
- props: toolbarProps,
1110
- options: { debug: true, locale: 'nl' },
1111
- navigation: {
1112
- navigate: (url) => router.push(url),
1113
- currentPath: () => window.location.pathname + window.location.search,
1114
- reload: () => router.refresh(),
1115
- },
1116
- });
1117
-
1118
- controller.destroy();
1119
- ```
1120
-
1121
- | Option | Type | Description |
1122
- | ------------ | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1123
- | `props` | `PreprToolbarProps` | From `getToolbarProps`. Optional — a headless preview has no segment list to pass. |
1124
- | `options` | `PreprPreviewOptions` | `{ debug?, locale?, features?, ui?, allowedEditorOrigins?, autoClean? }`. See [Preview options](#preview-options). |
1125
- | `navigation` | `PreprNavigationAdapter` | How segment/variant switches navigate. Optional — omitted, the toolbar uses `window.location.assign` (a full page load). `reload` is optional too, runs after a preview-mode toggle, and defaults to `window.location.reload()`. The Next.js and SvelteKit wrappers wire all of this up for you. |
1126
-
1127
- `createPreprPreview` is a no-op outside a browser (no `window`/`document`) and returns a controller whose `destroy()` does nothing, so it is safe to call during SSR. Call it **once per page** — two calls start two bridges and announce the preview twice.
1128
-
1129
- #### Tracking
1130
-
1131
- - **`loadTrackingPixel(id, config?)`** — installs the CDN tracking pixel. Idempotent, and a no-op outside a browser. A typed facade over Prepr's existing CDN pixel (`https://cdn.tracking.prepr.io/js/prepr.min.js`), reproducing the legacy `<script>` snippet's queue-stub semantics: calls made before the CDN script loads are queued and flushed once it is ready.
1132
- - **`trackEvent(name, data?)`** — sends a custom tracking event: `trackEvent('add_to_cart', { productId: 'abc123' })`.
1133
- - **`setTrackingParam(key, value)`** — sets a persistent tracking parameter: `setTrackingParam('user_type', 'returning')`.
1134
-
1135
- `trackEvent` and `setTrackingParam` are independent of `loadTrackingPixel` — they work against `window.prepr` however it got installed, including a legacy HTML snippet already on the page. If no pixel is installed at all they warn once in the console and return without throwing.
1136
-
1137
- #### `stegaClean(value)`
1138
-
1139
- Strips stega-encoded characters from a string. Rarely needed, since cleaning is automatic (see [Visual editing](#visual-editing)), but available when you need a clean value for comparison, sorting, or a non-DOM API.
1140
-
1141
- #### Header-based server helpers
1142
-
1143
- The framework wrappers are thin renames of these. Use them directly when writing your own adapter.
1144
-
1145
- ```typescript
1146
- import {
1147
- getPreprUUIDFromHeaders,
1148
- getActiveSegmentFromHeaders,
1149
- getActiveVariantFromHeaders,
1150
- getPreprHeadersFromHeaders,
1151
- getToolbarPropsFromHeaders,
1152
- getPreprEnvironmentSegments,
1153
- } from '@preprio/toolkit';
1154
- ```
1155
-
1156
- Unlike `getToolbarProps`, `getPreprEnvironmentSegments(token)` throws on failure — see [Error handling](#error-handling).
1157
-
1158
- ## Configuration
1159
-
1160
- ### Middleware options
1161
-
1162
- ```typescript
1163
- // Simple usage (creates a new NextResponse)
1164
- createPreprMiddleware(request, { preview });
1165
-
1166
- // Chaining usage (folds onto an existing NextResponse)
1167
- createPreprMiddleware(request, response, { preview });
1168
- ```
1169
-
1170
- | Option | Type | Description |
1171
- | ---------- | --------------- | ---------------------------------------------------------------------------------- |
1172
- | `preview` | `boolean` | Enables preview mode. The only gate — resolve it from your own environment signal. |
1173
- | `features` | `PreprFeatures` | Disable features app-wide. See [Feature flags](#feature-flags). |
1174
- | `version` | `string` | Override the version reported in the `Prepr-Package` header. Mainly for tests. |
1175
-
1176
- ### Preview options
1177
-
1178
- ```typescript
1179
- createPreprPreview({ props, options: { debug: true, locale: 'nl' } });
1180
- ```
1181
-
1182
- | Option | Type | Default | Description |
1183
- | ---------------------- | --------------- | ------------- | -------------------------------------------------------------------------------------------------------- |
1184
- | `debug` | `boolean` | `false` | Enable debug logging. |
1185
- | `locale` | `'en' \| 'nl'` | auto-detected | UI language. Falls back to the first supported browser language, then `en`. |
1186
- | `features` | `PreprFeatures` | all enabled | Which features run. See [Feature flags](#feature-flags). |
1187
- | `ui` | `boolean` | `true` | Mount the visible toolbar. See [Headless preview](#headless-preview-no-toolbar-ui). |
1188
- | `allowedEditorOrigins` | `string[]` | `*.prepr.io` | Exact editor origins allowed to drive this preview, for self-hosted editors. Replaces the wildcard. |
1189
- | `autoClean` | `boolean` | `true` | Strip the invisible stega characters from visible text. See [Stega auto-cleaning](#stega-auto-cleaning). |
1190
-
1191
- `features` and `ui` are independent: `features` decides _what runs_, `ui` decides _whether the toolbar is visible_.
1192
-
1193
- ### Feature flags
1194
-
1195
- Preview mode is the master switch. Within it, each feature can be turned off with a `features` object. Everything is **on by default** — omit it and nothing changes.
1196
-
1197
- ```typescript
1198
- import type { PreprFeatures } from '@preprio/toolkit';
1199
-
1200
- export const preprFeatures: PreprFeatures = {
1201
- segments: false, // or { enabled: false }
1202
- abTesting: true,
1203
- editMode: { enabled: false },
1204
- };
1205
- ```
1206
-
1207
- | Feature | Off means |
1208
- | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1209
- | `segments` | No segment picker. No `Prepr-Segments` header, from cookie **or** `?prepr_preview_segment`. No segment cookie written. The `_Segments` API call is skipped, saving a round-trip per page. |
1210
- | `abTesting` | No A/B control or variant badge. No `Prepr-ABtesting` header, from cookie **or** `?prepr_preview_ab`. No variant cookie written. |
1211
- | `editMode` | No Edit mode control, no click-to-edit overlay, no close-edit pill. |
1212
-
1213
- Pass the **same object to both sides**. Each enforces its own half, so a feature disabled in only one place is still half-on — the UI would hide a control the middleware still honours:
1214
-
1215
- ```typescript
1216
- // server
1217
- createPreprMiddleware(request, { preview, features: preprFeatures });
1218
- const props = await getToolbarProps(graphqlUrl, preprFeatures);
1219
-
1220
- // client
1221
- <PreprToolbar {...props} options={{ features: preprFeatures }} />
1222
- ```
1223
-
1224
- Every framework's `getToolbarProps` takes `features` as its last argument, and every `<PreprToolbar>` accepts an `options` prop. Keeping the object in one module both sides import is the simplest way to stay in sync — the examples use `src/prepr-features.ts` (`shared/prepr-features.ts` in Nuxt).
1225
-
1226
- Disabling a feature also stops its `segment_changed` / `variant_changed` events, and the Reset button ignores it — state the user cannot see is never rewritten.
1227
-
1228
- **`editMode` does not disable the Prepr visual editor.** It governs your site's own click-to-edit affordance. When the Prepr editor frames your site it drives edit mode over its own `postMessage` handshake, which keeps working regardless — that is the CMS operating inside its own iframe, not an affordance offered to your visitors. Treat `editMode: false` as a UI choice, never as a security control.
1229
-
1230
- ### Headless preview (no toolbar UI)
1231
-
1232
- `ui: false` keeps every non-visual side effect wired — click-to-edit, the editor bridge, scroll restore, cookies and headers — while rendering no chrome of its own. That is how a site gets live editing, or editor scroll restore, alongside its own UI instead of the Prepr bar.
1233
-
1234
- ```typescript
1235
- // Live editing, no bar:
1236
- const preview = createPreprPreview({
1237
- options: { ui: false, features: { editMode: true } },
1238
- });
1239
-
1240
- // Later, on teardown (SPA route change, component unmount):
1241
- preview.destroy();
1242
- ```
1243
-
1244
- `props` is optional here — a headless preview that only wants click-to-edit or scroll restore has no segment list to pass. For scroll restore and nothing else:
1245
-
1246
- ```typescript
1247
- createPreprPreview({
1248
- options: {
1249
- ui: false,
1250
- features: { segments: false, abTesting: false, editMode: false },
1251
- },
1252
- });
1253
- ```
1254
-
1255
- Scroll restore comes free with any preview, headless or not: inside the live-preview iframe the editor saves and restores the reader's position over the `postMessage` bridge, with no extra call and no configuration.
1256
-
1257
- `?prepr_hide_bar=true` and the editor's own iframe both imply `ui: false`; the bridge stays connected in each case. Outside an iframe the bridge is a no-op, so mounting unconditionally is safe. The handshake is only ever accepted from `https://<tenant>.prepr.io`, or from `allowedEditorOrigins` when set.
1258
-
1259
- ### Pixel options
1260
-
1261
- ```typescript
1262
- loadTrackingPixel(id, {
1263
- destinations: { googleTagManager: true },
1264
- variantImpressionThreshold: 0.5,
1265
- });
1266
- ```
1267
-
1268
- | Option | Type | Description |
1269
- | ------------------------------- | --------- | ---------------------------------------------------------------------- |
1270
- | `destinations.googleTagManager` | `boolean` | Forward events to Google Tag Manager. |
1271
- | `variantImpressionThreshold` | `number` | Visibility ratio required before an A/B variant impression is counted. |
1272
-
1273
- ### Theming
1274
-
1275
- The toolbar's shadow DOM reads its look from CSS custom properties set on the `prepr-toolbar` host element, or any ancestor — custom properties inherit through the shadow boundary. All have fallbacks, so theming is entirely optional.
1276
-
1277
- | Custom property | Purpose | Default |
1278
- | ----------------- | ------------------------------------------ | ----------------------------------------- |
1279
- | `--prepr-primary` | Toggle button, badges, status pill color | `#4338ca` |
1280
- | `--prepr-bg` | Panel background | `#eef2ff` |
1281
- | `--prepr-text` | Reserved for future text theming | `#1f2937` |
1282
- | `--prepr-radius` | Corner radius (panel, radio group, inputs) | `8px` |
1283
- | `--prepr-shadow` | Panel drop shadow | `0px 0px 40px 0px rgba(31, 41, 55, 0.24)` |
1284
- | `--prepr-z-index` | Base stacking order (backdrop/panel/pills) | `10000` |
1285
-
1286
- ```css
1287
- prepr-toolbar {
1288
- --prepr-primary: #16a34a;
1289
- --prepr-radius: 4px;
1290
- }
1291
- ```
1292
-
1293
- Because the toolbar renders inside a shadow root, none of your own page CSS — Tailwind resets, global styles — can leak in or affect it. These custom properties are the only supported customization surface.
1294
-
1295
- ### Internationalization
1296
-
1297
- The toolbar UI ships with English and Dutch. Pass `locale` explicitly, or omit it to auto-detect from the browser and fall back to `en`:
1298
-
1299
- ```typescript
1300
- createPreprPreview({ props, options: { locale: 'nl' } });
1301
- ```
1302
-
1303
- ## Troubleshooting
1304
-
1305
- ### Toolbar not showing
1306
-
1307
- - **Check the preview flag**: `{ preview: true }` must reach the middleware, and `getToolbarProps` must actually be called. Log the boolean you are passing — an environment check that resolves to `false` is the most common cause.
1308
- - **Verify the GraphQL URL**: it must match `https://graphql.prepr.io/YOUR_ACCESS_TOKEN`.
1309
- - **Check the token permissions**: "Enable edit mode" must be checked on the token in Prepr.
1310
- - **Confirm the middleware matcher**: if `config.matcher` excludes the current path, no Prepr headers were set for it. `getPreprUUID()` returning `null` confirms this.
1311
- - **Check for `prepr_hide_bar=true`** in the URL, which suppresses the bar by design.
1312
-
1313
- ### Click-to-edit not working on some elements
1314
-
1315
- - **Check the token permissions**: "Enable edit mode" must be checked on the token in Prepr.
1316
- - **Check whether the encoded text sits in a hidden element.** The parent of the encoded text node is what becomes editable, and a parent that renders no box (`display: none`, `visibility: hidden`, the `hidden` attribute) is skipped — it cannot be hovered or clicked. Put `data-prepr-edit-target` on the visible ancestor that should be editable instead. See [Choosing the element that becomes editable](#choosing-the-element-that-becomes-editable).
1317
- - **Inspect the tagged elements**: `document.querySelectorAll('[data-prepr-encoded]')` in the console lists everything edit mode found. An element you expected to be in that list points at one of the two cases above.
1318
-
1319
- ### Every variant shows at once
1320
-
1321
- The list came from a `variants: true` query but was rendered directly. Pass it through `PreprStack` (or `resolveVariants`); see [Personalization with Cache Components](#personalization-with-cache-components).
1322
-
1323
- ### Headers not working
1324
-
1325
- - **Middleware setup**: confirm `middleware.ts` sits in the project root (or `src/`) and its matcher covers the route.
1326
- - **API calls**: personalization only works if you spread `getPreprHeaders()` into your GraphQL fetch. Missing headers is the most common reason segments appear to have no effect.
1327
- - **Chained middleware**: when chaining, pass the existing `NextResponse` as the second argument. Creating a fresh `NextResponse.next()` afterwards discards Prepr's request headers.
1328
-
1329
- ### Segments switch but content does not change
1330
-
1331
- The toolbar sets the segment; your data fetch decides what to do with it. Check that the fetch forwards `getPreprHeaders()` and is not being served from cache — use `cache: 'no-store'`, or Apollo's `fetchPolicy: 'no-cache'`, on personalized queries. `createPreprClient` with `personalize: true` does both.
1332
-
1333
- ### Build issues
1334
-
1335
- - **Server helpers in client components**: the Next.js helpers read `next/headers` and are server-only. Calling them from a `'use client'` component fails at build time.
1336
- - **Missing peer dependencies**: importing `/nextjs` without `next`, `react`, and `react-dom` installed will not resolve. The core and `/astro` entry points have no framework peers.
1337
-
1338
- ### Error handling
1339
-
1340
- Fetch and token failures throw `PreprError`, which carries a machine-readable code:
1341
-
1342
- ```typescript
1343
- import { PreprError, getPreprEnvironmentSegments } from '@preprio/toolkit';
1344
-
1345
- try {
1346
- const segments = await getPreprEnvironmentSegments(
1347
- process.env.PREPR_GRAPHQL_URL!,
1348
- );
1349
- } catch (error) {
1350
- if (error instanceof PreprError) {
1351
- console.log('Error code:', error.code);
1352
- console.log('Context:', error.context);
1353
- }
1354
- }
1355
- ```
1356
-
1357
- Codes: `INVALID_TOKEN`, `MISSING_TOKEN`, `HTTP_ERROR`, `FETCH_ERROR`, `INVALID_RESPONSE`, `CONTEXT_ERROR`, `GRAPHQL_ERROR`, `INVALID_DOCUMENT`.
1358
-
1359
- `getToolbarProps` is the exception — it swallows these and returns an empty segment list, so a bad token cannot crash your app.
1360
-
1361
- ### Debug mode
1362
-
1363
- ```typescript
1364
- createPreprPreview({ props, options: { debug: true } });
1365
- ```
1366
-
1367
- ## How It Works
1368
-
1369
- ### Middleware
1370
-
1371
- On each request the middleware:
1372
-
1373
- 1. **Generates customer IDs** — assigns a unique visitor identifier, persisted in the `__prepr_uid` cookie.
1374
- 2. **Tracks UTM parameters** — lifts `utm_*` query params into `Prepr-Context-*` headers.
1375
- 3. **Manages segments** — resolves the active segment from cookie or preview query param.
1376
- 4. **Processes A/B tests** — resolves the active variant the same way.
1377
- 5. **Sets headers** — makes all of the above visible to your server-side code.
1378
-
1379
- Cookie and query-parameter names are a frozen wire protocol shared with the Prepr editor.
1380
-
1381
- ### Toolbar
1382
-
1383
- - **Segment selection** — preview the site as any configured audience segment.
1384
- - **A/B testing** — toggle between variants A and B.
1385
- - **Edit mode** — click-to-edit, jumping straight to the field in Prepr.
1386
- - **Reset** — clear all personalization overrides.
1387
-
1388
- The toolbar renders with Preact into a shadow-DOM custom element (`<prepr-toolbar>`), which keeps its styles isolated from the host page in both directions. Segment/variant selection and edit mode are wired up for you; you only mount the toolbar and supply its props.
1389
-
1390
- ### Visual editing
1391
-
1392
- With edit mode enabled, the toolkit scans for stega-encoded content, strips the invisible Unicode characters after load so they cannot cause layout shifts, highlights editable elements by cursor proximity, and talks to the Prepr editor over a `postMessage` bridge when running inside the live-preview iframe.
1393
-
1394
- Stega cleaning is automatic. There is no need to call `vercelStegaSplit` or to strip the payload yourself before rendering — the data attributes the toolkit relies on survive the clean, so edit mode still activates instantly.
1395
-
1396
- #### Stega auto-cleaning
1397
-
1398
- Preview content carries its edit payload inside the text itself, as a run of invisible Unicode characters. The toolkit strips them from the DOM after load and keeps stripping them as your framework re-renders.
1399
-
1400
- Leaving them in place is not cosmetic. The characters are real string content: they inflate `String.length`, break text measurement and truncation, and are announced by screen readers.
1401
-
1402
- Turn the stripping off with `autoClean: false`:
1403
-
1404
- ```typescript
1405
- createPreprPreview({ props, options: { autoClean: false } });
1406
- ```
1407
-
1408
- Only do this when your app already strips the payload itself — for example by passing every field through `stegaClean` as it renders:
1409
-
1410
- ```typescript
1411
- import { stegaClean } from '@preprio/toolkit';
1412
-
1413
- <h1>{stegaClean(page.title)}</h1>;
1414
- ```
1415
-
1416
- Click-to-edit is unaffected by this option. Elements are still tagged from the payload, so the overlay, tooltip and edit bridge keep working either way.
1417
-
1418
- #### Choosing the element that becomes editable
1419
-
1420
- The element that gets the outline, the tooltip and the click handler is the **parent of the encoded text node**. Rendering `{title}` inside an `<h2>` makes the `<h2>` editable, which is what you want almost every time.
1421
-
1422
- Two rules govern the choice:
1423
-
1424
- - A parent that renders no box is skipped. An element hidden with `display: none`, `visibility: hidden`, or the `hidden` attribute cannot be hovered or outlined, so tagging it would produce an element that looks editable to the code and is unreachable to the visitor. Nothing is tagged for it.
1425
- - `data-prepr-edit-target` overrides the parent. The closest ancestor carrying it becomes the editable element instead.
1426
-
1427
- That attribute is the supported way to separate _where the payload lives_ from _what the visitor clicks_. It is what makes the hidden-payload pattern work:
1428
-
1429
- ```html
1430
- <!-- The payload rides in a visually hidden span; the <article> is what
1431
- gets outlined and clicked. -->
1432
- <article data-prepr-edit-target>
1433
- <h2>Product title</h2>
1434
- <span hidden>{encodedPayload}</span>
1435
- </article>
1436
- ```
1437
-
1438
- Without the attribute that span is skipped entirely — it renders no box, so there is nothing to click.
1439
-
1440
- It is equally useful when the encoded text sits deep inside markup you do not control, and the natural click target is an ancestor:
1441
-
1442
- ```html
1443
- <figure data-prepr-edit-target>
1444
- <img src="..." alt="..." />
1445
- <figcaption><em>{encodedCaption}</em></figcaption>
1446
- </figure>
1447
- ```
195
+ **6. Verify it works.** Open a content item and its preview in Prepr, and type in a text field. The page shows the text before you save.
1448
196
 
1449
- Without it the `<em>` would be the editable element; with it the whole figure is.
197
+ Not updating? Check, in this order: `enabled` is true, the page is served over HTTPS, the browser console shows no `Refused to frame` error, and the query selects `_id`. More in [Troubleshooting](https://github.com/preprio/prepr-toolkit/blob/main/packages/toolkit/docs/troubleshooting.md#live-preview-does-not-update).
1450
198
 
1451
- ## Examples
199
+ The [live preview guide](https://github.com/preprio/prepr-toolkit/blob/main/packages/toolkit/docs/live-preview.md) covers how it works, every option, the cookies involved and the security model.
1452
200
 
1453
- Runnable examples live in the repository root:
201
+ ## Documentation
1454
202
 
1455
- | Example | What it shows |
1456
- | ---------------------------------- | ------------------------------------------------------------------ |
1457
- | `examples/nextjs` | App Router, middleware, `createPreprClient`, custom image loader |
1458
- | `examples/nextjs-cache-components` | Cache Components: cached page shell, personalized `<Suspense>` |
1459
- | `examples/astro` | Astro middleware and `.astro` components |
1460
- | `examples/sveltekit` | `hooks.server.ts`, `+layout.server.ts`, `.svelte` components |
1461
- | `examples/nuxt` | `server/middleware`, `useAsyncData`, `.vue` components |
1462
- | `examples/express` | Vanilla core — a hand-written adapter for an unsupported framework |
203
+ | Topic | |
204
+ | -------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
205
+ | Framework guides | [Next.js](https://github.com/preprio/prepr-toolkit/blob/main/packages/toolkit/docs/nextjs.md) · [Astro](https://github.com/preprio/prepr-toolkit/blob/main/packages/toolkit/docs/astro.md) · [SvelteKit](https://github.com/preprio/prepr-toolkit/blob/main/packages/toolkit/docs/sveltekit.md) · [Nuxt](https://github.com/preprio/prepr-toolkit/blob/main/packages/toolkit/docs/nuxt.md) · [React](https://github.com/preprio/prepr-toolkit/blob/main/packages/toolkit/docs/react.md) · [Other](https://github.com/preprio/prepr-toolkit/blob/main/packages/toolkit/docs/other-frameworks.md) |
206
+ | [Live preview](https://github.com/preprio/prepr-toolkit/blob/main/packages/toolkit/docs/live-preview.md) | Checklist, preparing queries, options, security, cookies |
207
+ | [Visual editing](https://github.com/preprio/prepr-toolkit/blob/main/packages/toolkit/docs/visual-editing.md) | How click-to-edit picks elements, and marking content by hand |
208
+ | [Configuration](https://github.com/preprio/prepr-toolkit/blob/main/packages/toolkit/docs/configuration.md) | Middleware and preview options, feature flags, headless preview, theming, languages |
209
+ | [API reference](https://github.com/preprio/prepr-toolkit/blob/main/packages/toolkit/docs/api-reference.md) | Every entry point, helper and component |
210
+ | [Troubleshooting](https://github.com/preprio/prepr-toolkit/blob/main/packages/toolkit/docs/troubleshooting.md) | Toolbar, click-to-edit, headers, live preview, cookies |
211
+ | [Examples](https://github.com/preprio/prepr-toolkit/tree/main/examples) | Runnable Next.js, Astro, SvelteKit, Nuxt and Express apps |
1463
212
 
1464
- ## Migrating from `@preprio/prepr-nextjs`
213
+ ## Versioning
1465
214
 
1466
- `@preprio/toolkit` replaces the Next.js-only `@preprio/prepr-nextjs` package. Most of
1467
- the change is import paths — the middleware signature is unchanged and the server
1468
- helpers keep their names — but the toolbar's provider and the stylesheet are gone.
215
+ The package follows semver. Minor and patch releases never break the public API; a breaking change ships as a major version with a migration entry. An API on its way out is marked `@deprecated` and keeps working until the next major. See the [changelog](https://github.com/preprio/prepr-toolkit/blob/main/CHANGELOG.md).
1469
216
 
1470
- The [migration guide](https://github.com/preprio/prepr-toolkit/blob/main/MIGRATION.md) has the diffs.
217
+ Cookie names, header names, `data-prepr-*` attributes and the editor's message format are part of that contract.
1471
218
 
1472
219
  ## Support
1473
220
 
1474
- - **Documentation**: [Prepr Documentation](https://docs.prepr.io)
1475
- - **Support**: [Prepr Support](https://prepr.io/support)
221
+ - [Prepr documentation](https://docs.prepr.io)
222
+ - [Open an issue](https://github.com/preprio/prepr-toolkit/issues)
223
+ - [Prepr support](https://prepr.io/support)