> ## Documentation Index
> Fetch the complete documentation index at: https://www.voiceflow.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Add the Voiceflow widget to SvelteKit

> Install the supplied Voiceflow chat widget in Svelte / SvelteKit, handle its browser lifecycle and test a visitor conversation.

## Overview

Install the supplied embedded text-chat widget in SvelteKit’s root layout. `onMount` starts the widget after hydration and returns its cleanup function. This recipe answers public support questions using an existing Voiceflow agent; it installs an embedded chat panel rather than a floating launcher.

**Note:** 

**Building your own interface?** Framework-specific custom chat and voice guides are [planned](#custom-interface). Use [Chat agents](/docs/api-reference/agent-runtime/chat) and [Voice agents](/docs/api-reference/agent-runtime/voice) for their separate API contracts.

<a id="before-you-begin"></a>

## Before you begin

Prepare the published public agent and application access.

| Requirement | What to prepare |
| --- | --- |
| Framework | Svelte 5.58.0 with SvelteKit 3.4.0; the starter prerenders using adapter-static 4.0.1. |
| Agent owner | A [published support agent](/docs/guides/usecases/customer-service/build-faq-agent), its public widget project ID and the intended [Environment alias](/docs/documentation/deploy/environments/overview#aliases). |
| Widget configuration | Public API access already enabled for this project; the Environment has a Published release. Disable file uploads in the published widget settings for this text-only setup. |
| Site developer | Permission to edit, build and deploy the application, plus a staging origin. The starter requires Node.js 22.23.4 and npm. |
| Acceptance | A known support question, its expected answer and permission to inspect the resulting [Transcript](/docs/documentation/measure/transcripts). |

The agent owner supplies the project ID, alias and expected answer before you configure the files. This example uses **public `verify.projectID`**; it does not convert generated client keys, private/prototype credentials or Private Cloud settings. For a different authorization format, use its supported [installation contract](/docs/documentation/deploy/widget/embedding-the-chat-widget). Keep personal/service API keys and website login tokens on your server. See [Svelte mount/cleanup hooks](https://svelte.dev/docs/svelte/lifecycle-hooks) and [SvelteKit layouts](https://svelte.dev/docs/kit/routing) for the framework lifecycle.

<a id="install-widget"></a>

## Install the widget

Configure the example and mount one browser-owned chat panel.

<a id="planned-coverage" />

### 1. Download the complete starter

Download [Svelte / SvelteKit starter](/docs/examples/web-frameworks/svelte.zip) and extract it. It includes the required dependencies, entry files, `src/lib/widget/widget.js`, `widget-config.js` and `widget.d.ts`. No Voiceflow npm package is required: the helper loads the hosted widget once.

For an existing application, copy the widget folder and adapt only the entry placement below. Remove any previous Voiceflow snippet before using this helper; the global widget API supports one active widget per document.

### 2. Set the public project and release

Edit `src/lib/widget/widget-config.js`:

```javascript
// Public identifiers for an existing public widget project, not API credentials.
export const widgetOptions = {
  verify: { projectID: "YOUR_PROJECT_ID" },
  url: "https://general-runtime.voiceflow.com",
  environmentID: "YOUR_ENVIRONMENT_ALIAS",
  versionVariant: "published",
  autostart: true,
  allowDangerousHTML: false,
  assistant: {
    type: "chat",
    persistence: "memory",
    enableVoiceInput: false,
    enableVoiceOutput: false,
    enableVoiceMode: false,
  },
};
```

The example renders standard Markdown with raw HTML disabled. Replace both `YOUR_` values. Use the Environment **alias**, not its display name. `environmentID` plus `versionVariant: 'published'` selects that Environment’s Published release. The legacy `versionID` option has [separate compatibility behavior](/docs/documentation/deploy/widget/web-chat-api#choosing-which-environment-the-widget-loads); do not substitute it here.

### 3. Place the widget in the application

Copy the wrapper and helper files to `src/lib/widget/`, then import the wrapper in `src/routes/+layout.svelte` outside the rendered page content. The starter uses a relative import, compatible with SvelteKit 3’s removal of the automatic `$lib` alias.

`src/lib/widget/VoiceflowChat.svelte`:

```svelte
<script>
  import { onMount } from 'svelte';
  import { mountWidget } from './widget.js';
  let host;
  // Keep this callback synchronous so Svelte receives the cleanup function.
  onMount(() => mountWidget(host));
</script>

<div bind:this={host} aria-label="Support chat"></div>
```

`src/routes/+layout.svelte`:

```svelte
<script>
  import VoiceflowChat from '../lib/widget/VoiceflowChat.svelte';
  let { children } = $props();
</script>
<nav><a href="/">Home</a> <a href="/about">About</a></nav>
{@render children()}
<VoiceflowChat />
```

### 4. Run the installed page

From the extracted starter folder, install its pinned dependencies and start the development server:

```bash
npm ci
npm run dev -- --port 5173
```

Open `http://localhost:5173`. The loading message should be replaced by one chat panel. If support cannot load, inspect the console and the [troubleshooting below](#test-conversation). A rendered panel is the installation check; complete the visitor test to verify replies.

<a id="widget-lifecycle"></a>

## Handle widget lifetime and identity

Keep navigation, removal and guest conversations predictable.

Keep the `onMount` callback synchronous: an `async` callback returns a Promise rather than the cleanup function Svelte needs. Root-layout reuse retains the chat across page navigation. A keyed or conditional wrapper remount starts fresh.

The downloaded helper serializes `load()` and cleanup. It retains the loaded script, calls `destroy()` only for its own started widget, and removes that mount’s target. A new target avoids attaching a second shadow root to the same element. Keep the outer container empty so the framework and widget do not render the same children.

| Event | Example behavior |
| --- | --- |
| Navigation with the owner still mounted | Retain the same conversation; do not call `load()` or send another launch. |
| Owner removed during loading | Cancel startup when possible; if load already started, finish it before cleanup and any next mount. |
| Owner removed, refreshed or remounted | `persistence: 'memory'` starts a fresh guest conversation on the next mount. |
| Logout or account switch | Remove the old widget owner; finish cleanup before showing support for the next account. Revoke application/backend sessions separately. |

`destroy()` clears the rendered UI; it does not delete Voiceflow transcripts or undo an in-flight business action. Do not automatically replay an uncertain send after navigation or network loss.

Browser `userID`, page context and launch values do not authenticate a customer. This public widget installation supplies no access control for private records. Protected operations require authorization on every backend read/write and trusted identity on later turns and resumes; follow the [canonical trusted-customer guidance](/docs/guides/integrations/crms/recognize-returning-customers#recognize-the-customer) before adding them.

### Use Svelte without SvelteKit

Adapt the placement while keeping one widget owner.

Use the same `VoiceflowChat.svelte` component in your browser app’s root component. Import it beside the page/router content and keep the helper files together. Svelte itself needs no SvelteKit layout or adapter. The downloadable starter and route checks target SvelteKit 3; a Vite-only Svelte application is not included.

<a id="test-conversation"></a>

## Test a visitor conversation

Verify the installed widget, replies and framework lifecycle.

Use a staging deployment with the final project and Environment configuration. If approved-domain restrictions are enabled, have the agent owner allow the staging and production origins. Your content security policy must allow the widget script, styles, fonts and runtime connections; use the blocked request URL to diagnose a refusal.

### 1. Open as a visitor

Open the staging URL in a fresh browser session. Accept any configured notice. Confirm that one embedded chat panel appears and that input, keyboard and scrolling work at desktop and phone widths.

### 2. Ask the prepared question

Send the known support question and a related follow-up. Confirm both visible replies match the intended agent and retain the context needed for the follow-up. Locate this exchange in [Transcripts](/docs/documentation/measure/transcripts) for the expected project.

### 3. Check navigation and removal

Use **About** and Back. The root layout should retain the chat. Refresh either route and confirm the prerendered shell hydrates before the widget appears. Repeat with a slow connection, and leave while the loader is pending. Return to support: there must be no duplicate panel, detached-target error or second load overlapping the first. Check the network/console rather than counting the SDK’s unused overlay host as another chat panel.

### 4. Check recovery and account boundaries

Interrupt the network and restore it. Confirm the widget can continue or offers a clear recovery route; check an uncertain operation before retrying. Reload to verify the fresh-start policy. If your site has sign-in, remove the widget during logout/account change and confirm old messages are absent when support returns.

### The support panel stays blank

Check the browser entry, configuration and blocked requests.

Confirm both placeholders were replaced, the module/asset paths resolve, and the component has a mounted browser container. The helper gives the embedded target a visible height. Inspect failed CDN, stylesheet, font and runtime requests, project public access, the Environment alias, its Published release and approved origins. Repair the cause, then reload the document; the helper does not retry a partially failed SDK load automatically.

### Navigation duplicates or restarts chat

Find a second owner or an unexpected component replacement.

Remove other snippets and mount the wrapper only once. Review keys, conditional rendering and page-versus-layout placement against [widget lifetime](#widget-lifecycle). Keep the helper’s returned cleanup wired to the framework hook. Memory-only retention intentionally restarts after a real unmount or document reload.

### The wrong agent or answer appears

Separate release selection from agent content.

Check the installed project ID and alias against the agent owner’s values, then test a fresh conversation. Confirm the expected answer exists in that Published release. Changing a draft does not update the selected release; use [publishing](/docs/documentation/deploy/environments/publishing) before retesting.

<a id="release"></a>

## Release and maintain the installation

Publish the agent and website independently, then test production.

### 1. Publish the agent and deploy the site

Have the agent owner [publish the reviewed Environment](/docs/documentation/deploy/environments/publishing), including widget-setting changes. Deploy `build/` after `npm run build`. The starter uses adapter-static and prerenders Home and About; use the appropriate SvelteKit adapter if your application needs server routes. Keep the public configuration in the browser bundle; store backend credentials separately.

### 2. Accept the production route

Open the actual HTTPS production URL and repeat the [visitor conversation test](#test-conversation), including a direct request to a nested route. Agent publication and website deployment are separate releases. Record the application commit, Environment release and observed widget version for rollback.

### Update, roll back or remove

Change the responsible layer and verify the deployed route.

Keep the last working application build and configuration. The hosted widget URL is a moving release, so a framework lockfile does not pin its served bundle; regression-test after widget updates. An app rollback does not roll back the agent or delete transcripts. To remove support, remove the wrapper/HTML entry and deploy; keep its cleanup in place during removal. After any change, repeat the same visitor test.

<a id="custom-interface"></a>

## Custom interface guides

Planned framework guides for your own chat or voice UI.

<a id="existing-documentation" />

Custom-interface walkthroughs for Svelte / SvelteKit are **planned**. They are separate from the completed supplied-widget procedure.

| Planned guide | Available API reference |
| --- | --- |
| Build a custom chat interface | [Chat agents](/docs/api-reference/agent-runtime/chat) |
| Build a custom voice interface | [Voice agents](/docs/api-reference/agent-runtime/voice) |
