# Add Uniform to a SvelteKit app

> Install the Uniform Svelte SDK and add the layout, hooks, routes, component map, and preview handler to a SvelteKit app.

Source: https://docs.uniform.app/docs/sdk/svelte/manual-setup

> **Developer preview:**
>
> This feature is in developer preview and may change unexpectedly. For more information, contact support@uniform.dev.

Follow this guide to add the SDK to an existing SvelteKit app, or use the [Quick start](https://docs.uniform.app/docs/sdk/svelte#quick-start) to begin with a working app.

## Prerequisites

- 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

## Install packages

```bash
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:

```bash
npm install -D @uniformdev/cli
```

| Package | Purpose |
| --- | --- |
| `@uniformdev/canvas` | Core Canvas API client, types, and utilities |
| `@uniformdev/canvas-svelte` | Svelte components: `UniformComposition`, `UniformSlot`, `UniformText`, `UniformRichText` |
| `@uniformdev/canvas-sveltekit` | SvelteKit integrations: route loading, server hooks, preview handler, ISR |
| `@uniformdev/context` | Core Context personalization engine |
| `@uniformdev/context-svelte` | `UniformContext` provider and reactive helpers (`getScores`, `getQuirks`) |
| `immer` | Peer dependency of `@uniformdev/canvas-svelte`. Version 10 or later |
| `@uniformdev/cli` | CLI for pulling manifests and syncing content |

## Environment variables

Create a `.env` file in your project root:

```bash
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](https://docs.uniform.app/docs/guides/api-access) for more information.

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

```ts
// 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:

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

## Project setup

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/...`.

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

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

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

The following sections walk through each file.

### Step 1: Root layout with UniformContext

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

```svelte
<!-- 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.

#### UniformContext props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `context` | `Context` |  | **Required.** A configured Uniform Context instance |
| `outputType` | `'standard' \| 'edge'` | `'standard'` | How personalization variants are rendered |
| `trackRouteOnRender` | `boolean` | `true` | Whether 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](https://docs.uniform.app/docs/sdk/svelte/personalization-and-testing#edge-personalization) keeps the visitor's variant. Set this only together with that hook.

### Step 2: Server hooks

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

```ts
// 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

### Step 3: Catch-all route

Create the route structure to serve Uniform compositions.

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

```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`**:

```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>
```

#### createUniformLoad options

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `client` | `RouteClient` | from `process.env` | Pass a client built from `$app/env/private`. The default reads `process.env.UNIFORM_API_KEY` and `process.env.UNIFORM_PROJECT_ID`. |
| `param` | `string` | `'path'` | The route parameter name (matches `[...path]`) |
| `projectMapId` | `string` | `undefined` | Optional project map ID (uses default if not set) |
| `silent` | `boolean` | `false` | Suppress console logging |
| `requestOptions` | `object` | `undefined` | Customize API request options |
| `handleComposition` | `function` | built-in | Custom handler for composition responses |
| `handleRedirect` | `function` | built-in | Custom handler for redirect responses |
| `handleNotFound` | `function` | built-in | Custom handler for 404 responses |

#### UniformComposition props

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

| Prop | Type | Required | Description |
| --- | --- | --- | --- |
| `data` | `RootComponentInstance` | Yes | The composition data from the Uniform API |
| `componentMap` | `ComponentMap` | Yes* | Object mapping component types to Svelte components |
| `resolveRenderer` | `RenderComponentResolver` | No | Custom resolver function (alternative to `componentMap`) |
| `matchedRoute` | `string` | No | The matched route path |
| `dynamicInputs` | `Record<string, string>` | No | Dynamic input values from route parameters |
| `behaviorTracking` | `'onLoad' \| 'onView'` | No | When to track enrichment behavior |
| `contextualEditingEnhancer` | `function` | No | Custom enhancer for contextual editing updates |

> **Note:**
>
> Either `componentMap` or `resolveRenderer` must be provided. `componentMap` is the recommended approach for most projects.

### Step 4: Component mapping

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

```ts
// 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`.

### Step 5: Preview handler

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

```ts
// 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.

### Step 6: Playground page

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

```svelte
<!-- 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.
