Use SvelteKit with Prismic
Last updated
Overview
Prismic has a first-party SvelteKit integration that supports all of Prismic’s features:
- Model content with page types and slices using the Type Builder or the Prismic CLI.
- Fetch and display content using SDKs with generated TypeScript types.
- Preview draft content with live previews and full-website previews.
Here’s what a Prismic page looks like in SvelteKit:
<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 a Prismic repository
From the Prismic dashboard, create a Prismic repository. Select SvelteKit.

Set up your project
Follow the setup instructions shown in your Prismic repository. The instructions walk you through creating a SvelteKit project, connecting it to Prismic, and modeling content with the Type Builder.
Add
<PrismicPreview>to your root layout<PrismicPreview>adds support for content draft previews. The$lib/prismicioimport comes from a file thatprismic initcreates for you during setup.src/routes/+layout.svelte<script lang="ts"> import type { Snippet } from "svelte"; import { PrismicPreview } from "@prismicio/svelte/kit"; import { repositoryName } from "$lib/prismicio"; type Props = { children: Snippet; }; let { children }: Props = $props(); </script> <main>{@render children()}</main> <PrismicPreview {repositoryName} />Your SvelteKit website is now ready for Prismic. Continue to create pages and slices.
Create a SvelteKit project
npx sv create my-website cd my-websiteYou can also use an existing SvelteKit project.
Add Prismic to your project
The
initcommand creates a Prismic repository, installs packages, and configures your project.npx prismic initIf you already have a Prismic repository, provide its domain with
--repo:npx prismic init --repo your-domainAdd
<PrismicPreview>to your root layout<PrismicPreview>adds support for content draft previews. The$lib/prismicioimport comes from a file thatprismic initcreates for you.src/routes/+layout.svelte<script lang="ts"> import type { Snippet } from "svelte"; import { PrismicPreview } from "@prismicio/svelte/kit"; import { repositoryName } from "$lib/prismicio"; type Props = { children: Snippet; }; let { children }: Props = $props(); </script> <main>{@render children()}</main> <PrismicPreview {repositoryName} />Your SvelteKit website is now ready for Prismic. Continue to create pages and slices.
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.
import type { PageServerLoad, EntryGenerator } 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 };
};
export const entries: EntryGenerator = async () => {
const client = createClient();
const pages = await client.getAllByType("page");
return pages.map((page) => ({ uid: page.uid }));
};<script lang="ts">
import { isFilled, asImageSrc } from "@prismicio/client";
import { SliceZone } from "@prismicio/svelte";
import { components } from "$lib/slices";
import type { PageProps } from "./$types";
const { data }: PageProps = $props();
</script>
<svelte:head>
<title>{data.page.data.meta_title}</title>
{#if isFilled.keyText(data.page.data.meta_description)}
<meta name="description" content={data.page.data.meta_description} />
{/if}
{#if isFilled.image(data.page.data.meta_image)}
<meta property="og:image" content={asImageSrc(data.page.data.meta_image)} />
{/if}
</svelte:head>
<SliceZone slices={data.page.data.slices} {components} />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).
{
"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 route | SvelteKit file-system route |
|---|---|
/ | src/routes/[[preview=preview]]/+page.svelte |
/:uid | src/routes/[[preview=preview]]/[uid]/+page.svelte |
/blog/:uid | src/routes/[[preview=preview]]/blog/[uid]/+page.svelte |
/:grandparent/:parent/:uid | src/routes/[[preview=preview]]/[...path]/+page.svelte |
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.
<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.
import {
createClient as baseCreateClient,
type Route,
} from "@prismicio/client";
import {
enableAutoPreviews,
type CreateClientConfig,
} from "@prismicio/svelte/kit";
import prismicConfig from "../../prismic.config.json";
export const repositoryName = prismicConfig.repositoryName;
export function createClient({ cookies, ...config }: CreateClientConfig = {}) {
const client = baseCreateClient(repositoryName, {
routes: prismicConfig.routes as Route[],
...config,
});
enableAutoPreviews({ client, cookies });
return client;
}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.
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 createSave the new access token as an environment variable in a
.envfile..envPRISMIC_ACCESS_TOKEN=my-access-tokenAccess tokens can also be managed in your repository at Settings → API & Security.
Pass the access token to your client
Provide the token via the
accessTokenoption in$lib/prismicio.ts:src/lib/prismicio.tsimport { 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 privateAPI visibility can also be managed in your repository at Settings → API & Security.
Display content
Display content using @prismicio/svelte. Here are the most commonly used components:
<PrismicLink>- Display links.<PrismicImage>- Display images.<PrismicRichText>- Display rich text.<PrismicText>- Display plain text.<SliceZone>- Display slices.
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 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:5173The 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 usingredirectToPreviewURL().src/params/preview.ts— a route matcher that dynamically renders pages prefixed with/preview(e.g./preview/about).src/routes/[[preview=preview]]/— an optionalpreviewroute segment that wraps your pages.src/routes/+layout.server.ts— setsprerendertoautoso pages prefixed with/previewskip 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 DevelopmentOnce deployed, add your production URL as a second preview. Previews can also be managed at Settings → Previews.
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 documentsUnpublishedWebhooks can also be managed at Settings → Webhooks.
SEO
Page types automatically include fields in an SEO & Metadata tab:
meta_title: The page’s title.meta_description: The page’s description.meta_image: A preview image when your page is shared on social platforms.
Use the metadata fields in a +page.svelte’s <svelte:head>.
<svelte:head>
<title>{data.page.data.meta_title}</title>
{#if isFilled.keyText(data.page.data.meta_description)}
<meta name="description" content={data.page.data.meta_description} />
{/if}
{#if isFilled.image(data.page.data.meta_image)}
<meta property="og:image" content={asImageSrc(data.page.data.meta_image)} />
{/if}
</svelte:head>Internationalization
Prismic supports multi-lingual websites. See Locales for details on locale management.
Add locales to your repository
Use the Prismic CLI to add locales.
npx prismic locale add fr-frLocales can also be managed in your repository at Settings → Translations & Locales.
Install the necessary packages
Install the packages needed for locale detection:
npm install negotiator @formatjs/intl-localematcherCreate a
$lib/i18n.tsfileThe
$lib/i18n.tsfile provides a set of internationalization helpers. The helpers will be used in your website’shandlehook.Create a
$lib/i18n.tsfile with the following contents.src/lib/i18n.tsimport { redirect, type RequestEvent } from "@sveltejs/kit"; import { match } from "@formatjs/intl-localematcher"; import Negotiator from "negotiator"; /** * A record of locales mapped to a version displayed in URLs. The first entry is * used as the default locale. */ // TODO: Update this object with your website's supported locales. Keys // should be the locale IDs registered in your Prismic repository, and values // should be the string that appears in the URL. const LOCALES: Record<string, string> = { "en-us": "en-us", "fr-fr": "fr-fr", }; /** Redirects with an auto-detected locale prepended to the URL. */ export function redirectToLocale(event: RequestEvent) { const headers = { "accept-language": event.request.headers.get("accept-language") ?? undefined, }; const languages = new Negotiator({ headers }).languages(); const locales = Object.keys(LOCALES); const locale = match(languages, locales, locales[0]); const destination = new URL(event.url); destination.pathname = `/${LOCALES[locale]}${event.url.pathname}`; redirect(302, destination); } /** Determines if a pathname has a locale as its first segment. */ export function pathnameHasLocale(event: RequestEvent): boolean { const regexp = new RegExp(`^/(${Object.values(LOCALES).join("|")})(/|$)`); return regexp.test(event.url.pathname); } /** * Returns the full locale of a given locale. It returns `undefined` if the * locale is not in the master list. */ export function reverseLocaleLookup(locale: string): string | undefined { for (const key in LOCALES) { if (LOCALES[key] === locale) { return key; } } }Define locales in
$lib/i18n.ts$lib/i18n.tscontains a list of locales supported by your website.Update the
LOCALESconstant to match your Prismic repository’s locales. The first locale is used when a visitor’s locale is not supported.src/lib/i18n.tsconst LOCALES = { "en-us": "en-us", "fr-fr": "fr-fr", };You can define how the locale appears in the URL by changing the object’s values. In the following example, the
en-uslocale will appear asenin the URL (e.g./en/about).src/lib/i18n.tsconst LOCALES = { "en-us": "en", "fr-fr": "fr", };Create or modify
hooks.server.tsWebsite visitors will be directed to the correct locale using
handleinsrc/hooks.server.ts.Create a
src/hooks.server.tsfile with the following contents, or modify your existingsrc/hooks.server.tsto include the highlighted lines.src/hooks.server.tsimport { type Handle } from "@sveltejs/kit"; import { pathnameHasLocale, redirectToLocale } from "$lib/i18n"; export const handle: Handle = async ({ event, resolve }) => { if (!pathnameHasLocale(event)) { redirectToLocale(event); } return resolve(event); };Learn about SvelteKit hooks
Nest routes under a
[lang]dynamic route segmentCreate a directory at
src/routes/[[preview=preview]]/[lang]and nest all other routes under this directory.The
langroute parameter will contain the visitor’s locale. For example,/en-us/aboutsetslangto"en-us".Learn about SvelteKit routing
Fetch content from the visitor’s locale
In your
+page.server.tsfiles, forward thelangparameter to your Prismic query.src/routes/[[preview=preview]]/[lang]/[uid]/+page.server.tsimport type { PageServerLoad } from "./$types"; import { createClient } from "$lib/prismicio"; import { reverseLocaleLookup } from "$lib/i18n"; export const load: PageServerLoad = async ({ params, fetch, cookies }) => { const client = createClient({ fetch, cookies }); const page = await client.getByUID("page", params.uid, { lang: reverseLocaleLookup(params.lang), }); return { page }; };The
reverseLocaleLookuphelper from$lib/i18n.tsconverts a shortened locale (e.g.en) to its full version (e.g.en-us).Fetch all locales in
entriesFetch pages from all locales using the Prismic client’s
lang: "*"option. Include thelangroute parameter.src/routes/[[preview=preview]]/[lang]/[uid]/+page.server.tsimport type { EntryGenerator } from "./$types"; import { createClient } from "$lib/prismicio"; export const entries: EntryGenerator = async () => { const client = createClient(); const pages = await client.getAllByType("page", { lang: "*", }); return pages.map((page) => ({ lang: page.lang, uid: page.uid })); };