Skip to Content
Prepr ToolkitSetup guide

Prepr Toolkit setup

From this guide, you’ll learn how to set up the Prepr Toolkit in your front end. To control when it runs, set up live preview, turn individual features on or off, choose which element becomes editable in Edit mode, and style the preview toolbar.

The code snippets below are available in Next.js, Astro, Nuxt, and SvelteKit. Check out the detailed examples in the GitHub repo  for your framework.

Prerequisites

You need to have the following setup before you install the Prepr Toolkit.

Don’t have a front-end project yet? Follow the Next.js, Astro, or Nuxt complete guide to build one with personalization and A/B testing.

Setting up the Prepr preview toolbar

Follow the steps below to install the Prepr Toolkit and show the Prepr preview toolbar in your front end.

Install the Prepr Toolkit

Open a terminal in your front-end project and run the following command:

npm install @preprio/toolkit

Each framework needs its own peer dependencies, such as next, react, and react-dom for Next.js. Check the package README on GitHub  for the full list.

Add your GraphQL Preview URL

Get the GraphQL Preview access token URL by logging into your Prepr account.

  1. Click the icon and choose the Access tokens option to view all the access tokens.
  2. Click to open the GraphQL Preview access token, and copy the API URL to only retrieve all content items.

The GraphQL Preview token allows editors to preview unpublished content items.

Preview access token - enable edit mode

  1. Add the URL to your .env file. The toolkit doesn’t read environment variables itself, so you choose the name and pass the value in your code. The examples in this guide use PREPR_GRAPHQL_URL.
./.env
PREPR_GRAPHQL_URL=https://graphql.prepr.io/YOUR_ACCESS_TOKEN

Enable preview mode and add the toolbar

The preview toolbar allows content editors to preview content on a test or staging website. The example code below makes sure the toolbar is not enabled on a production site. It does this by creating a preview setting that is only true when your website is not running in production.

When the preview setting is true, the following logic applies in your test or staging website:

  • The middleware turns on the preview features, such as switching segments and A/B variants.
  • The layout loads the toolbar.

Checking for production

The Next.js example, below, turns on preview in every environment except production, using VERCEL_ENV, so it also works on a staging deployment. The Astro, SvelteKit, and Nuxt examples use the development flag of the framework (import.meta.env.DEV, dev, import.meta.dev). That flag is only true while you run the dev server and is false in every production build, including a test or staging deployment.

To show the toolbar on a staging website with these frameworks, replace the flag with a variable that tells your environments apart, for example PREPR_ENV=preview in the .env file of your staging environment, and set preview to process.env.PREPR_ENV === 'preview'. If you host somewhere else, use the variable your host provides for the same purpose.

./proxy.ts
import type { NextRequest } from 'next/server' import { createPreprMiddleware } from '@preprio/toolkit/nextjs' export function proxy(request: NextRequest) { const preview = process.env.VERCEL_ENV !== 'production' return createPreprMiddleware(request, { preview }) }

On Next.js 15 and older, name the file middleware.ts and the function middleware. The code inside stays the same.

./app/layout.tsx
import type { ReactNode } from 'react' import { getToolbarProps, PreprToolbar } from '@preprio/toolkit/nextjs' export default async function RootLayout({ children }: { children: ReactNode }) { const preview = process.env.VERCEL_ENV !== 'production' const toolbarProps = preview ? await getToolbarProps(process.env.PREPR_GRAPHQL_URL!) : null return ( <html lang="en"> <body> {children} {toolbarProps && <PreprToolbar {...toolbarProps} />} </body> </html> ) }

Let the environment decide the preview value like in the examples above to prevent the preview toolbar showing on your live website.

Add the Prepr headers

Segments and A/B tests only change your content when you add the Prepr headers to every Prepr GraphQL request. For more details on how Prepr identifies visitors, check out the personalization guide or the A/B testing guide.

import { getPreprHeaders } from '@preprio/toolkit/nextjs' const response = await fetch(process.env.PREPR_GRAPHQL_URL!, { method: 'POST', headers: { 'Content-Type': 'application/json', ...(await getPreprHeaders()), }, body: JSON.stringify({ query, variables }), cache: 'no-store', })

Test the preview toolbar

To test the preview toolbar is set up correctly, follow the steps below.

  1. Restart your development server.
  2. Open your website in the browser. You’ll see the Prepr icon on the page.
  3. Click the icon to open the toolbar and click the Reset button.
  4. Choose a segment, or switch between the A and B variants of an A/B test for a content page with personalization or A/B testing. If your content changes, the toolbar and the headers are set up correctly.
  5. Turn on Edit mode and click a text element to open the corresponding field in the content item in Prepr.

If something doesn’t work, check the troubleshooting section.

Setting up live preview

Live preview shows what an editor enters in Prepr on the page before they save. It works inside the Visual Editing side-by-side preview in Prepr. Outside this preview, it does nothing and loads nothing.

Live preview builds on the preview toolbar setup above, so complete the steps above first.

Supported frameworks

Live preview is available in Next.js, Astro, SvelteKit, and Nuxt. In Next.js it requires version 16 or later. On Next.js 15 and earlier, the preview page updates after you save.

Check the access token and preview URL

  1. Open the GraphQL Preview access token you added earlier and check that Enable edit mode is ticked.
  2. Check that the preview URL of your content model points to a deployment that uses this token and runs with preview set to true.

Make the preview frameable

Inside the Prepr editor, your website opens in an iframe. Check the following for your preview website:

  • Serve it over HTTPS. In the iframe, browsers only keep the preview cookies when they are SameSite=None; Secure, which the toolkit sets on HTTPS.
  • If you send a Content-Security-Policy header, allow your Prepr environment in frame-ancestors.
  • Don’t send an X-Frame-Options header on your preview website.
Content-Security-Policy: frame-ancestors 'self' https://YOUR_ENVIRONMENT.prepr.io

Select _id in your queries

Live preview matches the changes of an editor to the content items on your page by _id. A content item, component, or dynamic content entry whose query doesn’t select _id stays static.

If you use GraphQL Codegen, add the preprIds document transform. It adds _id wherever your schema has one, and your .graphql files stay as they are. Run Codegen again afterwards.

./codegen.ts
import { preprIds } from '@preprio/toolkit/codegen' const config = { schema: process.env.PREPR_GRAPHQL_URL, documents: ['src/queries/**/*.graphql'], generates: { 'src/gql/': { preset: 'client', documentTransforms: [preprIds], }, }, } export default config

Without Codegen, select _id by hand on every model and component in your queries, or check the other methods on GitHub .

Run your query results through the live preview helper

Pass the result of each query through the helper of your framework. Use the same preview setting as in the middleware for enabled. When enabled is false, the data is returned unchanged.

Run each query result through normalizeQuery, with the client you use to fetch the data:

./app/page.tsx
import { normalizeQuery } from '@preprio/toolkit/nextjs' const preview = process.env.VERCEL_ENV !== 'production' const data = await fetchFromPrepr(GetPageDocument, { slug }) const page = await normalizeQuery(GetPageDocument, data, { enabled: preview })

Then add PreprRefresh once in the root layout. It sends the unsaved changes to the server while an editor types, and shows the stored content after a save.

./app/layout.tsx
import { PreprRefresh } from '@preprio/toolkit/nextjs/live' // In your layout's JSX {preview && <PreprRefresh enabled />}

Optional: skip the Prepr request while an editor types

Each change an editor makes renders the page again, and each render fetches your queries from Prepr again, even though the saved content hasn’t changed. To reuse the last response for these renders, wrap your fetch in livePreviewFetch:

./app/page.tsx
import { livePreviewFetch, normalizeQuery } from '@preprio/toolkit/nextjs' const preview = process.env.VERCEL_ENV !== 'production' const data = await livePreviewFetch( { query: GetPageDocument, variables: { slug } }, () => fetchFromPrepr(GetPageDocument, { slug }), { enabled: preview }, ) const page = await normalizeQuery(GetPageDocument, data, { enabled: preview })

The first argument identifies the response, so include every variable your fetch uses. A page load and a save always fetch from Prepr. Only the renders for unsaved changes reuse the last response, and normalizeQuery adds the changes on top.

This is most useful on pages with large or slow queries. Keep the following in mind:

  • Responses are stored in the memory of the server for 5 minutes. When a render runs on another server instance, it fetches from Prepr as usual.
  • Responses are stored per query, variables, and Prepr headers, so each segment and A/B variant gets its own response.
  • Don’t change the returned data in your code. Renders share it.

Don’t set enabled to true directly in your code. Always let your environment decide the value, the same as for the preview setting of the toolbar.

Test live preview

  1. Open a content item in Prepr and open its preview next to it.
  2. Type in a text field. The page shows the text before you save.
  3. Save the content item. The page shows the stored content.

Live preview example

If the page doesn’t update, check the troubleshooting section.

Additional features

Other than the standard preview toolbar setup, you can enable or disable some additional features.

Turn toolkit features on or off

With the standard setup above, personalized segments, A/B test variants and the edit mode options are available by default. To disable and hide one or more of these options, create a features object like in the example code below.

./src/prepr-features.ts
import type { PreprFeatures } from '@preprio/toolkit' export const preprFeatures: PreprFeatures = { segments: false, abTesting: true, editMode: { enabled: false }, }

Pass the same object to both the server and the client like in the example code snippets below.

// Server: middleware and toolbar props createPreprMiddleware(request, { preview, features: preprFeatures }) const props = await getToolbarProps(process.env.PREPR_GRAPHQL_URL!, preprFeatures) // Client: toolbar component <PreprToolbar {...props} options={{ features: preprFeatures }} />

Only activate edit mode

To keep click-to-edit and scroll restore in the Prepr editor but never show the toolbar, set ui to false. The toolkit still manages the cookies and headers, and keeps the connection with the Prepr editor. Outside the Prepr editor, Edit mode can’t be turned on without the toolbar.

<PreprToolbar {...toolbarProps} options={{ ui: false, features: { editMode: true } }} />

The toolbar is also hidden when the URL contains ?prepr_hide_bar=true or when your website opens inside the Prepr editor.

Choose editable elements

In Edit mode, the element that gets the outline, tooltip, and click handler is the parent of the text that comes from Prepr. For example, if you render {title} inside an <h2>, the <h2> becomes editable. This is what you want in most cases.

Text inside an element that isn’t visible, such as one with display: none, visibility: hidden, or the hidden attribute, becomes editable once it’s shown, for example when a visitor opens an accordion. Text that stays hidden, such as a payload you render only for Edit mode, never gets an outline. Add the data-prepr-edit-target attribute to the visible parent element to make that element clickable instead.

<article data-prepr-edit-target> <h2>Product title</h2> <span hidden>{encodedPayload}</span> </article>

You can also use the data-prepr-edit-target attribute when the text sits deep inside markup you don’t control, and the parent element is the natural click target:

<figure data-prepr-edit-target> <img src="..." alt="..." /> <figcaption><em>{encodedCaption}</em></figcaption> </figure>

The data-prepr-edit-target attribute also takes a value, and there are more attributes for list entries and linked items. Check the visual editing guide on GitHub  for the full list.

Handle invisible characters

In preview, your content contains invisible Unicode characters (Stega encoding) that tell Edit mode which field each text comes from. The toolkit removes these characters from the page after it loads, so they don’t affect layout, text length, or screen readers.

If your app already removes them, for example with stegaClean, turn off the automatic cleaning with autoClean: false.

Pass the option to the toolbar component in your framework, and clean each value as you render it. Cleaning a value also removes the information Edit mode needs, so add previewAttrs to the element that shows the value. stegaTarget reads the field from the value before it’s cleaned. Without these attributes, the element isn’t editable in Edit mode.

import { previewAttrs, stegaClean, stegaTarget } from '@preprio/toolkit' <PreprToolbar {...toolbarProps} options={{ autoClean: false }} /> <h1 {...previewAttrs(stegaTarget(page.title), { enabled: preview })}> {stegaClean(page.title)} </h1>

If you use live preview, clean the values after you pass the query result through the live preview helper, not before. Live preview finds content by _id, but click-to-edit reads the invisible characters, so cleaning the values earlier turns off click-to-edit.

Use strict mode

If your GraphQL Preview access token uses strict mode, set strictMode to true in the toolbar options. In strict mode, required fields are never null. While an editor types in live preview, the toolkit then:

  • Holds back new entries until their required fields are filled in.
  • Never sends a cleared required field as null.

Without this option, preview can show null errors in projects that use strict mode.

Pass the option to the toolbar component in your framework:

<PreprToolbar {...toolbarProps} options={{ strictMode: true }} />

You only need to set it on the toolbar. It applies to live preview in every framework.

Style the preview toolbar

The toolbar renders in its own isolated container, so your global CSS can’t change it. To change its look, set the following CSS custom properties on the prepr-toolbar element:

PropertyWhat it changesDefault
--prepr-primaryToggle button, badges, and status pill color#4338ca
--prepr-bgPanel background#eef2ff
--prepr-radiusCorner radius of the panel and inputs8px
--prepr-shadowPanel drop shadow0px 0px 40px 0px rgba(31, 41, 55, 0.24)
--prepr-z-indexBase stacking order10000
prepr-toolbar { --prepr-primary: #16a34a; --prepr-radius: 4px; }

The toolbar is available in English (en), Dutch (nl), French (fr), and German (de). To set the language, pass the locale option, for example options: { locale: 'nl' }. Without it, the toolkit uses the browser language and falls back to English.

Inside the Prepr editor, the labels of the visual editor, such as the outlines and tooltips, follow the language the editor user has set in Prepr. If that language isn’t supported, the toolkit uses the locale option instead.

Troubleshooting

The toolbar doesn’t show

  • Check that the preview value you pass to the middleware is true and that you call getToolbarProps. A failing environment check is the most common cause.
  • Check that your GraphQL URL looks like https://graphql.prepr.io/YOUR_ACCESS_TOKEN.
  • Open the GraphQL Preview access token in Prepr and check that Enable edit mode is ticked.
  • Check that the URL doesn’t contain prepr_hide_bar=true.

Click-to-edit doesn’t work on some elements

  • Check that Enable edit mode is ticked in the access token.
  • Check whether the text sits in an element that stays hidden. If so, add data-prepr-edit-target to a visible parent like in the examples above.
  • Check whether you clean the value with stegaClean. A cleaned value needs previewAttrs on its element, like in Handle invisible characters. With live preview, clean values after the live preview helper.
  • Run document.querySelectorAll('[data-prepr-encoded]') in the browser console to list the elements Edit mode found.

Content doesn’t change when switching segments or A/B variants

The toolbar sets the segment or variant, but your data fetching decides what to do with it.

  • Check that you add the Prepr headers to every Prepr GraphQL request, like in Add the Prepr headers.
  • Check that the response isn’t cached. Use cache: 'no-store' with fetch, or fetchPolicy: 'no-cache' with Apollo Client.
  • On Next.js, when you chain middleware, pass the existing NextResponse as the second argument to createPreprMiddleware. Creating a new response afterward removes the Prepr headers.

The segment or variant resets inside the Prepr editor

Inside the Prepr editor, your website opens in a cross-site iframe. Browsers only keep the preview cookies there when they are SameSite=None; Secure, which requires HTTPS.

  • Serve your preview website over HTTPS.
  • If your website runs behind a proxy, forward the x-forwarded-proto header so the toolkit knows the request was HTTPS.

Live preview doesn’t update

Check the following in this order:

  • On Next.js, check that you use version 16 or later, and that PreprRefresh is in the root layout. On older versions the page only updates after you save.
  • On Astro, check that the page renders on demand, with output: 'server' or export const prerender = false.
  • Check that enabled is true in every live preview helper. On Next.js and Astro, the middleware must also run with preview set to true for that page.
  • Check that the preview URL in Prepr points to a deployment that uses the GraphQL Preview token. A production build with preview turned off only shows saved content.
  • Check that the page is served over HTTPS.
  • Check that the browser console doesn’t show a Refused to frame error. If it does, add your Prepr environment to frame-ancestors in your Content-Security-Policy header and remove the X-Frame-Options header.
  • Check that your query selects _id for the content item or component that doesn’t update.
  • If preview shows null errors and your token uses strict mode, set strictMode to true in the toolbar options, like in Use strict mode.

The build fails

  • The Next.js helpers are server-only. Don’t call them from a 'use client' component.
  • In a 'use client' component, import PreprToolbar and PreprTrackingPixel from @preprio/toolkit/nextjs/components. Importing them from @preprio/toolkit/nextjs also pulls in the server helpers and fails the build.
  • Install the peer dependencies for the entry point you import, such as next, react, and react-dom for @preprio/toolkit/nextjs.

To see what the toolkit does in the browser, turn on debug logging by passing options={{ debug: true }} to the toolbar component, the same way as the features option.

What’s next?

Last updated on