Add Uniform to a SvelteKit app

Developer preview

This feature is in developer preview. Use with caution as it may change unexpectedly. For more information, contact us.

Follow this guide to add the SDK to an existing SvelteKit app, or use the Quick start to begin with a working app.

  • SvelteKit 3 (@sveltejs/kit 3.0.0 or later) and Svelte 5.57 or later
  • Node.js 22.17 or later
  • A Uniform project with compositions on the project map
npm install @uniformdev/canvas @uniformdev/canvas-svelte @uniformdev/canvas-sveltekit @uniformdev/context @uniformdev/context-svelte immer

Install the Uniform CLI as a dev dependency for syncing content and downloading manifests:

npm install -D @uniformdev/cli
PackagePurpose
@uniformdev/canvasCore Canvas API client, types, and utilities
@uniformdev/canvas-svelteSvelte components: UniformComposition, UniformSlot, UniformText, UniformRichText
@uniformdev/canvas-sveltekitSvelteKit integrations: route loading, server hooks, preview handler, ISR
@uniformdev/contextCore Context personalization engine
@uniformdev/context-svelteUniformContext provider and reactive helpers (getScores, getQuirks)
immerPeer dependency of @uniformdev/canvas-svelte. Version 10 or later
@uniformdev/cliCLI for pulling manifests and syncing content

Create a .env file in your project root:

UNIFORM_API_KEY=your-api-key UNIFORM_PROJECT_ID=your-project-id UNIFORM_PREVIEW_SECRET=your-preview-secret

note

You can find these values in your Uniform project under Security > Service Accounts. See the API access guide for more information.

SvelteKit 3 reads private variables from src/env.ts. Declare them there:

// src/env.ts import { defineEnvVars } from '@sveltejs/kit/env'; function optionalString(value: string | undefined) { return value; } export const variables = defineEnvVars({ UNIFORM_API_KEY: {}, UNIFORM_PROJECT_ID: {}, UNIFORM_PROJECT_MAP_ID: { schema: optionalString }, UNIFORM_PREVIEW_SECRET: { schema: optionalString }, });

UNIFORM_API_KEY and UNIFORM_PROJECT_ID are required. The app does not start when either value is missing. Set UNIFORM_PROJECT_MAP_ID when the project has more than one project map. UNIFORM_PREVIEW_SECRET has to match the preview secret in Canvas. Published pages still render when it is empty.

Import the values from $app/env/private in server files:

import { UNIFORM_API_KEY, UNIFORM_PROJECT_ID, UNIFORM_PROJECT_MAP_ID, UNIFORM_PREVIEW_SECRET, } from '$app/env/private';

The Uniform SDK requires a specific set of files to wire up routing, rendering, and preview. Here is the minimal file structure:

your-sveltekit-app/ ├── src/ │ ├── env.ts # Declares Uniform environment variables │ ├── app.html # HTML template │ ├── hooks.server.ts # Preview cookie, and the NESI hook when you use edge │ ├── routes/ │ │ ├── +layout.svelte # Root layout with UniformContext │ │ ├── [...path]/ │ │ │ ├── +page.server.ts # Fetches compositions from the Route API │ │ │ ├── +page.svelte # Renders compositions │ │ │ └── +error.svelte # Error boundary │ │ ├── playground/ │ │ │ └── +page.svelte # Component preview for the Canvas editor │ │ └── api/ │ │ └── preview/ │ │ └── +server.ts # Preview endpoint │ └── lib/ │ ├── index.ts # Target of the `#lib` import │ ├── components/ # Svelte components mapped to Uniform types │ │ ├── Hero.svelte │ │ ├── Page.svelte │ │ └── index.ts │ └── uniform/ │ ├── componentMap.ts # Maps Uniform types to Svelte components │ └── contextManifest.json # Downloaded personalization manifest ├── uniform.config.ts # CLI configuration ├── vite.config.ts # SvelteKit config, including the adapter └── .env

SvelteKit 3 reads its config from vite.config.ts.

Add this imports map to package.json. sv create writes it for you. Import library files from #lib/....

{ "imports": { "#lib": "./src/lib/index.js", "#lib/*": "./src/lib/*" } }

Create src/lib/index.ts so the #lib entry has a file to resolve:

// src/lib/index.ts // Files in this folder are imported through the `#lib` alias.

The following sections walk through each file.

Create src/routes/+layout.svelte to initialize the Uniform Context provider:

<!-- src/routes/+layout.svelte --> <script lang="ts"> import { Context, CookieTransitionDataStore, enableContextDevTools, enableDebugConsoleLogDrain, } from '@uniformdev/context'; import { UniformContext } from '@uniformdev/context-svelte'; import type { ManifestV2 } from '@uniformdev/context'; import manifestJson from '#lib/uniform/contextManifest.json'; let { children } = $props(); const context = new Context({ defaultConsent: true, transitionStore: new CookieTransitionDataStore({ serverCookieValue: undefined, }), plugins: [enableContextDevTools(), enableDebugConsoleLogDrain('debug')], manifest: manifestJson as ManifestV2, }); </script> <UniformContext {context} outputType="standard"> {@render children()} </UniformContext>

Importing @uniformdev/canvas-sveltekit adds uniformPreview to App.Locals. Leave src/app.d.ts as SvelteKit created it.

PropTypeDefaultDescription
contextContextRequired. A configured Uniform Context instance
outputType'standard' | 'edge''standard'How personalization variants are rendered
trackRouteOnRenderbooleantrueWhether to track route changes on render
includeTransferState'always' | 'never' | 'server-only''server-only'When to include transfer state for SSR hydration

note

The outputType setting controls how personalization and A/B test variants are rendered:

  • standard. The page render selects the variant and writes only that variant into the HTML. Use this without the NESI hook.
  • edge. The page writes every variant as a NESI placeholder. The hook in Edge personalization keeps the visitor's variant. Set this only together with that hook.

Create src/hooks.server.ts to handle Uniform preview mode detection:

// src/hooks.server.ts import { sequence } from '@sveltejs/kit/hooks'; import { createUniformHandle } from '@uniformdev/canvas-sveltekit'; import { UNIFORM_PREVIEW_SECRET } from '$app/env/private'; const uniformHandle = createUniformHandle({ secret: () => UNIFORM_PREVIEW_SECRET, onPreview: (event, previewData) => { if (previewData.isUniformContextualEditing) { console.log( '[Uniform] Contextual editing mode active for:', previewData.compositionPath ); } }, }); export const handle = sequence(uniformHandle);

secret has to return the same value you pass to createPreviewHandler. When it returns an empty value, the hook ignores the preview cookie and the load function fetches published content.

The hook:

  • Verifies the signed preview cookie
  • Sets event.locals.uniformPreview when the cookie is valid
  • Calls onPreview when preview mode is active

Create the route structure to serve Uniform compositions.

Server-side data loading in src/routes/[...path]/+page.server.ts:

// src/routes/[...path]/+page.server.ts import { RouteClient } from '@uniformdev/canvas'; import { createUniformLoad } from '@uniformdev/canvas-sveltekit/route'; import { UNIFORM_API_KEY, UNIFORM_PROJECT_ID, UNIFORM_PROJECT_MAP_ID, } from '$app/env/private'; import type { PageServerLoad } from './$types'; export const load: PageServerLoad = async (event) => { const client = new RouteClient({ apiKey: UNIFORM_API_KEY, projectId: UNIFORM_PROJECT_ID, }); const uniformLoad = createUniformLoad({ client, projectMapId: UNIFORM_PROJECT_MAP_ID, param: 'path', }); return uniformLoad(event); };

Composition rendering in src/routes/[...path]/+page.svelte:

<!-- src/routes/[...path]/+page.svelte --> <script lang="ts"> import { UniformComposition, UniformSlot } from '@uniformdev/canvas-svelte'; import { componentMap } from '#lib/uniform/componentMap.js'; let { data } = $props(); </script> <UniformComposition data={data.data} {componentMap} matchedRoute={data.matchedRoute} dynamicInputs={data.dynamicInputs} > <UniformSlot name="content" /> </UniformComposition>
OptionTypeDefaultDescription
clientRouteClientfrom process.envPass a client built from $app/env/private. The default reads process.env.UNIFORM_API_KEY and process.env.UNIFORM_PROJECT_ID.
paramstring'path'The route parameter name (matches [...path])
projectMapIdstringundefinedOptional project map ID (uses default if not set)
silentbooleanfalseSuppress console logging
requestOptionsobjectundefinedCustomize API request options
handleCompositionfunctionbuilt-inCustom handler for composition responses
handleRedirectfunctionbuilt-inCustom handler for redirect responses
handleNotFoundfunctionbuilt-inCustom handler for 404 responses

UniformComposition is the entry point for rendering a composition tree. It takes these props:

PropTypeRequiredDescription
dataRootComponentInstanceYesThe composition data from the Uniform API
componentMapComponentMapYes*Object mapping component types to Svelte components
resolveRendererRenderComponentResolverNoCustom resolver function (alternative to componentMap)
matchedRoutestringNoThe matched route path
dynamicInputsRecord<string, string>NoDynamic input values from route parameters
behaviorTracking'onLoad' | 'onView'NoWhen to track enrichment behavior
contextualEditingEnhancerfunctionNoCustom enhancer for contextual editing updates

note

Either componentMap or resolveRenderer must be provided. componentMap is the recommended approach for most projects.

Create src/lib/uniform/componentMap.ts to map Uniform component types to Svelte components:

// src/lib/uniform/componentMap.ts import type { ComponentMap } from '@uniformdev/canvas-svelte'; import Hero from '#lib/components/Hero.svelte'; import Page from '#lib/components/Page.svelte'; export const componentMap: ComponentMap = { page: Page, hero: Hero, // Variant mapping: use `type__variant` format // hero__dark: HeroDark, };

The componentMap is a simple object where keys are Uniform component type strings and values are Svelte components. For variant-specific mappings, use the type__variant format (double underscore).

note

Svelte uses componentMap instead of resolveRenderer. Unlike the React and Nuxt SDKs which use a resolveRenderer function, the Svelte SDK uses a declarative componentMap object. This is more idiomatic for Svelte and simpler to maintain.

You can also use a custom resolveRenderer function if your own code has to pick the component. Pass it as a prop to UniformComposition instead of componentMap.

Create src/routes/api/preview/+server.ts. In Canvas, set the preview URL to this route. Locally that is http://localhost:5173/api/preview.

// src/routes/api/preview/+server.ts import { createPreviewHandler } from '@uniformdev/canvas-sveltekit/preview'; import { UNIFORM_PREVIEW_SECRET } from '$app/env/private'; const handlers = createPreviewHandler({ secret: () => UNIFORM_PREVIEW_SECRET, playgroundPath: '/playground', resolveFullPath: ({ path, slug }) => { return path || slug || '/'; }, }); export const GET = handlers.GET; export const POST = handlers.POST; export const OPTIONS = handlers.OPTIONS;

secret signs the preview cookie. createUniformHandle has to use the same secret or the load function stays on published content.

Create src/routes/playground/+page.svelte for previewing individual components and patterns:

<!-- src/routes/playground/+page.svelte --> <script lang="ts"> import { UniformComposition, UniformSlot } from '@uniformdev/canvas-svelte'; import { componentMap } from '#lib/uniform/componentMap.js'; import { EMPTY_COMPOSITION } from '@uniformdev/canvas'; </script> <div class="playground"> <UniformComposition data={EMPTY_COMPOSITION} {componentMap}> <UniformSlot name="content" /> </UniformComposition> </div>

The playground page renders an empty composition shell that the Canvas editor populates during contextual editing sessions.