# Personalization and testing with the Svelte SDK

> Render personalization and A/B test variants in SvelteKit, in the page render or with the NESI hook.

Source: https://docs.uniform.app/docs/sdk/svelte/personalization-and-testing

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

Personalization and A/B testing are configured in the Uniform dashboard and evaluated automatically by the SDK. When `UniformSlot` encounters a personalization or test container in the composition tree, it renders the appropriate `Personalize` or `Test` component from `@uniformdev/context-svelte`.

## How personalization works

```mermaid
flowchart TD
    A["Manifest downloaded<br/>(signals, enrichments, quirks)"] --> B["UniformContext initialized<br/>in +layout.svelte"]
    B --> C["Visitor browses site"]
    C --> D["Track / TrackFragment<br/>updates enrichment scores"]
    D --> E["UniformSlot encounters<br/>personalization container"]
    E --> F["Context evaluates visitor scores<br/>against variant criteria"]
    F --> G["Winning variant rendered"]
    
    style A fill:#e0e7ff,stroke:#4f46e5
    style F fill:#f0fdf4,stroke:#16a34a
    style G fill:#fef3c7,stroke:#d97706
```

1. The personalization manifest is downloaded locally (see [Manifest management](https://docs.uniform.app/docs/sdk/svelte/manifest-management)) and passed to the Context in the root layout.
2. The `UniformContext` provider creates a `Context` instance and makes it available to the entire component tree.
3. When `UniformSlot` encounters a personalization container, it evaluates the visitor's scores against the variant criteria and renders the winning variant(s).
4. Score updates happen through enrichment tracking (`Track` component) and route-based signals.

## Output types

The `outputType` prop on `UniformContext` controls how variants are rendered:

- **`standard`** (default): Evaluates personalization during SSR or on the client. Only the winning variant HTML is included. Best for development and most deployments.
- **`edge`**: Outputs all variants as NESI placeholders. An edge middleware selects the winning variant before the response reaches the browser. Best for production with edge personalization (see [Edge personalization](#edge-personalization)).

```svelte
<UniformContext {context} outputType="standard">
  {@render children()}
</UniformContext>
```

Change `outputType` to `edge` only when the [NESI hook](#edge-personalization) is in place.

## Edge personalization

`outputType="edge"` writes every personalization and test variant into the HTML as NESI placeholders. A hook in `src/hooks.server.ts` reads that HTML and keeps the visitor's variant. The hook runs in `vite dev` and in production.

```mermaid
sequenceDiagram
    participant V as Visitor
    participant S as SvelteKit server
    V->>S: Request /about
    Note over S: Page renders with NESI placeholders
    Note over S: Hook keeps the visitor's variant
    S-->>V: HTML for that variant
```

`@uniformdev/context-edge` and `@uniformdev/context-edge-sveltekit` are private packages. To install them, you need an npm access token from Uniform. If you don't have an access token, request one from [Uniform Support](mailto:support@uniform.dev?subject=Access+token+for+edge+personalization).

Add an `.npmrc` file to the project root that reads the token from `NPM_TOKEN`:

```shell
//registry.npmjs.org/:_authToken=${NPM_TOKEN}
```

Set `NPM_TOKEN` to your token and install the edge packages:

```bash
export NPM_TOKEN=<your-npm-token>
npm install @uniformdev/context-edge @uniformdev/context-edge-sveltekit
```

Set the output type on `UniformContext`:

```svelte
<UniformContext {context} outputType="edge">
  {@render children()}
</UniformContext>
```

Add the NESI hook after `createUniformHandle`. Skip responses that are not HTML. `__data.json`, API routes, and assets do not contain placeholders.

```ts
// src/hooks.server.ts
import { type Handle, sequence } from '@sveltejs/kit/hooks';
import { createUniformHandle } from '@uniformdev/canvas-sveltekit';
import { type ManifestV2 } from '@uniformdev/context';
import { createEdgeContext } from '@uniformdev/context-edge';
import { createUniformNesiResponseHandler } from '@uniformdev/context-edge-sveltekit';
import manifest from '#lib/uniform/contextManifest.json';
import { UNIFORM_PREVIEW_SECRET } from '$app/env/private';

const uniformHandle = createUniformHandle({
  secret: () => UNIFORM_PREVIEW_SECRET,
});

const uniformNesiHandler: Handle = async ({ event, resolve }) => {
  const response = await resolve(event);

  if (!response.headers.get('content-type')?.startsWith('text/html')) {
    return response;
  }

  const context = createEdgeContext({
    manifest: manifest as ManifestV2,
    request: event.request,
  });

  await context.update({
    cookies: event.cookies.getAll().reduce<Record<string, string>>((acc, cookie) => {
      acc[cookie.name] = cookie.value;
      return acc;
    }, {}),
    url: event.url,
  });

  const handler = createUniformNesiResponseHandler();
  return handler({ response, context });
};

export const handle = sequence(uniformHandle, uniformNesiHandler);
```
