Preview Drafts

On this page, you'll learn how to create a preview version of your SvelteKit app to view drafts from Prismic live on your website.

Do you need to do this?

If you used a Prismic starter that has a [[preview=preview]] directory, then previews are already configured for you. When you create new +page.server.js files, handle the cookies param and specify the entries() option as described below. Here's a truncated example:

import { createClient } from '$lib/prismicio';

export async function load({ fetch, cookies }) {
  const client = createClient({ fetch, cookies });

  // Your data fetching...
}

export async function entries() {
  // Return one or more params objects
}

You will also need to configure previews in your repository, as described in the final step below.

For optimal speed, we recommend prerendering your website. However, when you prerender your website, all of the data for your website is fetched only once at build time. In order to fetch new data to preview drafts live on your website, we recommend creating a conditional preview route in your application. Here's how it works.

  • On the root layout, you will set prerender to "auto". This will prerender some URLs and server-render other URLs.
  • You will nest your entire app inside a directory with the name [[preview=preview]]. This creates an optional /preview/ route segment at the root of your website.
  • In each +page.server.js file, export an entries() function that tells SvelteKit to prerender each page without the /preview/ segment (e.g. example.com/about-us).
  • Create an API route, /api/preview, which will launch a preview session with the /preview/ segment (e.g. example.com/preview/about-us). Because SvelteKit has only prererendered the version without the /preview/ segment, your /preview/ version will be server-rendered with fresh data. The server-rendered version will automatically display your draft content.

Prismic will automatically preprend /preview/ to internal links using the <PrismicPreview> component, creating a complete preview version of your website.

Put all of your routes in a [[preview=preview]] directory

In order to serve routes with an optional /preview prefix (e.g. example.com/about and example.com/preview/about), routes must be nested under an optional route parameter.

Create a src/routes/[[preview=preview]] directory.

Put all of your routes inside that directory, like this:

Copy
src/
└── routes/
    └── [[preview=preview]]/
        ├── [uid]/
        │   ├── +page.server.js
        │   └── +page.svelte
        ├── +page.server.js
        └── +page.svelte

Create a preview route matcher

The [[preview=preview]] route parameter uses a route matcher stored in the src/params/ directory. The matcher ensures the parameter only matches routes that start with /preview.

Create a file at src/params/preview.js with the following contents:

src/params/preview.js
Copy
export function match(param) {
	return param === 'preview'
}

Prerender published pages

The prerender = "auto" page option tells SvelteKit to prerender all pages returned in the page’s entries() option. All other pages are server-rendered, which is necessary to preview unpublished content.

Configure all pages with prerender = "auto" in src/routes/+layout.server.js:

src/routes/+layout.server.js
Copy
export const prerender = 'auto'

Define pages with entries()

Ensure published pages are prerendered by including an entries() page option.

+page.server.js files should include an entries() function like the following example. Adjust the parameters and Prismic query to fit your page.

src/routes/[[preview=preview]]/[uid]/+page.server.js
Copy
import { createClient } from '$lib/prismicio'

export async function entries() {
  const client = createClient()

  const pages = await client.getAllByType('page')

  // Do not include the `preview` parameter to ensure `/preview`
  // routes are not prerendered.
  return pages.map((page) => {
    return { uid: page.uid }
  })
}

Add <PrismicPreview> to the root layout

<PrismicPreview> adds the Prismic toolbar to all pages. It updates the page’s data as content is saved in Prismic.

Add the following lines to your root layout at src/routes/+layout.svelte:

src/routes/+layout.svelte
Copy
  <script>
   import { PrismicPreview } from '@prismicio/svelte/kit';
   import { repositoryName } from '$lib/prismicio';
  </script>

  <main>
    <slot />
  </main>
 <PrismicPreview {repositoryName} />

Enable previews in createClient()

The Prismic client needs SvelteKit-specific configuration to support previews. @prismicio/svelte/kit’s enableAutoPreviews() will configure your Prismic client to fetch preview data automatically.

Update your createClient() function with the following version:

src/lib/prismicio.js
Copy
/**
 * Creates a Prismic client for the project's repository. The client is
 * used to query content from the Prismic API.
 *
 * @param {import('@prismicio/svelte/kit').CreateClientConfig} config
 */
export const createClient = ({ cookies, ...config } = {}) => {
  const client = prismic.createClient(repositoryName, {
    routes,
    ...config
  });

  enableAutoPreviews({ client, cookies });

  return client;
};

Pass cookies to createClient()

createClient() needs access to a page request’s cookies to detect a preview session.

When calling createClient() from a page’s load() function, pass the request’s cookies object like this:

src/routes/[[preview=preview]]/+page.server.js
Copy
// src/routes/[[preview=preview]]/+page.server.js

import { createClient } from '$lib/prismicio';

export async function load({ fetch, cookies }) {
  const client = createClient({ fetch, cookies });

  // Your data fetching...
}

Create an /api/preview endpoint

An /api/preview endpoint is needed to direct content writers from Prismic to the previewed document’s page.

Create a file at src/routes/api/preview/+server.js with the following contents:

src/routes/api/preview/+server.js
Copy
import { redirectToPreviewURL } from '@prismicio/svelte/kit';
import { createClient } from '$lib/prismicio.js';

export async function GET({ fetch, request, cookies }) {
	const client = createClient({ fetch });

	return await redirectToPreviewURL({ client, request, cookies });
}

Configure previews in your Prismic repository

Finish setting up previews by configuring your Prismic repository:

  1. In your Prismic repository, go to Settings > Previews
  2. Ignore the step about including the Prismic Toolbar (<PrismicPreview> adds the toolbar for you)
  3. Click Create Preview
  4. You’ll be prompted to input a site name, a domain for your application, and an optional preview route. Fill out the fields with the following information:
    Domain: http://localhost:5173
    Preview Route: /api/preview

Your project is now set up to handle previews.


Can't find what you're looking for?

Need technical Support? Spot an error in the documentation? Get in touch with us on our Community Forum.