Frameworks

Use SvelteKit with Prismic

Last updated

Overview

Prismic has a first-party SvelteKit integration that supports all of Prismic’s features:

Here’s what a Prismic page looks like in SvelteKit:

src/routes/[[preview=preview]]/[uid]/+page.svelte
<script lang="ts">
  import { SliceZone } from "@prismicio/svelte";
  import { components } from "$lib/slices";
  import type { PageProps } from "./$types";

  // Page data is loaded in +page.server.ts
  const { data }: PageProps = $props();
</script>

<!-- Display the page's slices -->
<SliceZone slices={data.page.data.slices} {components} />

SvelteKit websites use @prismicio/client and @prismicio/svelte.

Set up a SvelteKit website

Prismic can be added to new or existing SvelteKit websites. Set up your project using the Type Builder, a tool for building by hand, or the Prismic CLI, a tool for AI agents.

Create pages

Content writers create pages from page types, like a homepage, blog post, or landing page. Model page types by hand in the Type Builder, or with the Prismic CLI for AI agents. TypeScript types are generated automatically.

Learn how to create page types

Write page components

Each page type needs a SvelteKit page component. With file-system-based routing, you create a page file at each page’s path.

The example below shows a page component for a Page page type.

src/routes/[[preview=preview]]/[uid]/+page.server.ts
src/routes/[[preview=preview]]/[uid]/+page.svelte

Define routes

The Prismic CLI keeps routes in prismic.config.json in sync with your page types, whether you model in the Type Builder or with CLI commands.

Page routes are inferred from each page type’s API ID:

  • A page type named Homepage maps to /.
  • A page type named Page maps to /:uid.
  • Any other page type, like Blog Post, maps to /<api-id>/:uid (e.g. /blog-post/:uid).
prismic.config.json
{
  "repositoryName": "example-prismic-repo",
  "routes": [
    { "type": "homepage", "path": "/" },
    { "type": "page", "path": "/:uid" },
    { "type": "blog_post", "path": "/blog/:uid" }
  ]
}

Edit prismic.config.json directly to customize routes. Make sure your routes match your SvelteKit file-system routes. Here are common examples:

Prismic routeSvelteKit file-system route
/src/routes/[[preview=preview]]/+page.svelte
/:uidsrc/routes/[[preview=preview]]/[uid]/+page.svelte
/blog/:uidsrc/routes/[[preview=preview]]/blog/[uid]/+page.svelte
/:grandparent/:parent/:uidsrc/routes/[[preview=preview]]/[...path]/+page.svelte
Learn more about routes

Create slices

Content writers build pages from reusable sections called slices, like a block of text, a hero, or a call to action. Model slices by hand in the Type Builder, or with the Prismic CLI for AI agents. TypeScript types are generated automatically.

Learn how to create slices

Write Svelte components

The Prismic CLI generates a starter component in src/lib/slices/<SliceName>/index.svelte. Edit the component to add your implementation.

The following example Call to Action component displays a rich text field and a link.

src/lib/slices/CallToAction/index.svelte
<script lang="ts">
  import type { Content } from "@prismicio/client";
  import {
    PrismicRichText,
    PrismicLink,
    type SliceComponentProps,
  } from "@prismicio/svelte";

  type Props = SliceComponentProps<Content.CallToActionSlice>;

  let { slice }: Props = $props();
</script>

<section class="flex flex-col gap-4 p-8">
  <PrismicRichText field={slice.primary.text} />
  <PrismicLink field={slice.primary.link} class="button" />
</section>

Learn how to display content

Fetch content

Use @prismicio/client and its methods to fetch page content.

The Prismic client

The Prismic CLI creates a $lib/prismicio.ts file when you run prismic init. It centralizes your client configuration, including routes read from prismic.config.json.

src/lib/prismicio.ts

Fetch content in pages and slices

Import createClient() from $lib/prismicio.ts and create a client. Use the client to fetch content. The following example fetches content for a /[uid] dynamic route.

src/routes/[[preview=preview]]/[uid]/+page.server.ts
import type { PageServerLoad } from "./$types";
import { createClient } from "$lib/prismicio";

export const load: PageServerLoad = async ({ params, fetch, cookies }) => {
  const client = createClient({ fetch, cookies });
  const page = await client.getByUID("page", params.uid);

  return { page };
};

We do not recommend fetching content in slices on the client. Instead, you can use a content relationship field to fetch linked content. You can also use <SliceZone>’s context prop to pass arbitrary data from a page to a slice.

Learn more about fetching content

Secure with an access token

Published content is public by default. You can require a private access token to secure the API.

Learn more about content visibility

  • Generate an access token

    npx prismic token create

    Save the new access token as an environment variable in a .env file.

    .env
    PRISMIC_ACCESS_TOKEN=my-access-token

    Access tokens can also be managed in your repository at SettingsAPI & Security.

  • Pass the access token to your client

    Provide the token via the accessToken option in $lib/prismicio.ts:

    src/lib/prismicio.ts
    import { PRISMIC_ACCESS_TOKEN } from "$env/static/private"; 
    
    export function createClient({ cookies, ...config }: CreateClientConfig = {}) {
      const client = baseCreateClient(repositoryName, {
        accessToken: PRISMIC_ACCESS_TOKEN, 
        routes: prismicConfig.routes as Route[],
        ...config,
      });
    
      enableAutoPreviews({ client, cookies });
    
      return client;
    }
  • Change your repository’s API access

    Set the API access to private. Content API requests will immediately require an access token.

    npx prismic repo set-api-access private

    API visibility can also be managed in your repository at SettingsAPI & Security.

Display content

Display content using @prismicio/svelte. Here are the most commonly used components:

Learn how to display content from a field

Live previews in the Page Builder

The Page Builder shows live-updating thumbnails for each slice as content writers edit.

A screenshot of a page with live previews in the Page Builder.

A page with live previews in the Page Builder.

Live previews are powered by the slice simulator, a special route that renders individual slices. The Prismic CLI creates the simulator page at src/routes/slice-simulator/+page.svelte when you run prismic init.

Tell Prismic where your simulator is running so the Page Builder can load it:

npx prismic preview set-simulator http://localhost:5173

The simulator URL can also be set from any document. Click the ”” button next to the Publish/Unpublish button in the top-right corner and select Live preview settings.

Once your website is deployed, update the simulator URL to your production domain.

Preview draft content

Full-website previews let content writers see draft content on your website before publishing. The prismic init command creates the routes and configuration needed for previews:

  • src/routes/api/preview/+server.ts — starts a draft preview session using redirectToPreviewURL().
  • src/params/preview.ts — a route matcher that dynamically renders pages prefixed with /preview (e.g. /preview/about).
  • src/routes/[[preview=preview]]/ — an optional preview route segment that wraps your pages.
  • src/routes/+layout.server.ts — sets prerender to auto so pages prefixed with /preview skip prerendering and fetch draft content.

Add a development preview URL so you can preview drafts locally:

npx prismic preview add http://localhost:5173/api/preview --name Development

Once deployed, add your production URL as a second preview. Previews can also be managed at SettingsPreviews.

Deploy

Deploy your SvelteKit website with your hosting provider:

Handle content changes

Your website needs to rebuild when content changes in Prismic. Follow the instructions in our webhooks documentation for your hosting provider.

Register the rebuild endpoint as a webhook so Prismic calls it when content is published or unpublished:

npx prismic webhook create https://example.com/your-rebuild-endpoint \
  --trigger documentsPublished \
  --trigger documentsUnpublished

Webhooks can also be managed at SettingsWebhooks.

SEO

Internationalization

Prismic supports multi-lingual websites. See Locales for details on locale management.

Was this page helpful?