> ## 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 Gatsby

> Install the supplied Voiceflow chat widget in Gatsby, handle browser navigation and cleanup, and test a visitor conversation.

## Overview

Install the supplied embedded text-chat widget in Gatsby’s root wrapper. Gatsby generates page HTML at build time; a React Effect initializes the widget after browser hydration. This recipe installs an embedded panel for public support using an existing Voiceflow agent.

**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 framework access.

| Requirement | What to prepare |
| --- | --- |
| Framework scope | Gatsby 5.16.1 / React 19.3.1. The supplied starter targets the rendering model described above. |
| 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; a Published release in that Environment. Disable file uploads in its published widget settings for this text-only recipe. |
| Site developer | Node.js 22.23.4 and npm; permission to edit and deploy the site and a staging origin. |
| Visitor test | A known question and expected answer, plus access to the resulting [Transcript](/docs/documentation/measure/transcripts). |

Obtain the project ID, alias and expected answer from the agent owner before editing the files. This starter uses the **public `verify.projectID` contract**; client-key, private/prototype and Private Cloud configurations require their own compatible installation. Keep framework application secrets, website login tokens and personal/service API keys on the server. See [Gatsby browser APIs](https://www.gatsbyjs.com/docs/reference/config-files/gatsby-browser/#wrapRootElement) for the platform behavior.

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

## Install the widget

Configure and activate one browser-owned chat panel.

### 1. Download the complete starter

Download the [Gatsby starter](/docs/examples/web-frameworks/gatsby.zip) and extract it. It includes the entry files, dependency locks and `src/widget/widget.js`, `widget-config.js` and `widget.d.ts`. The helper loads the supplied widget from its CDN; no Voiceflow npm package is needed.

For an existing site, copy only the widget integration and merge the placement below into your existing layout. Keep its other configuration. Remove any earlier Voiceflow snippet: this global widget API supports one active widget per document.

### 2. Choose the public project and Published release

Edit `src/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,
  },
};
```

Replace both `YOUR_` values with the supplied project ID and Environment alias. `environmentID` and `versionVariant: 'published'` select that Environment’s Published release; [legacy `versionID` compatibility](/docs/documentation/deploy/widget/web-chat-api#choosing-which-environment-the-widget-loads) is separate. Raw HTML is disabled while ordinary Markdown remains available.

### 3. Add the browser integration

Copy the wrapper/helper files to `src/widget/`. Use the same `wrapRootElement` export in both `gatsby-browser.jsx` and `gatsby-ssr.jsx`; the download includes both files with identical contents. This keeps generated HTML and the browser tree aligned, with one widget outside changing page elements.

`src/widget/VoiceflowChat.jsx`:

```jsx
import React, { useEffect, useRef } from "react";
import { mountWidget } from "./widget.js";

export default function VoiceflowChat() {
  const host = useRef(null);
  useEffect(() => mountWidget(host.current), []);
  return <div ref={host} aria-label="Support chat" />;
}
```

`gatsby-browser.jsx`:

```jsx
import React from "react";
import VoiceflowChat from "./src/widget/VoiceflowChat.jsx";
export const wrapRootElement = ({ element }) => (
  <>
    {element}
    <VoiceflowChat />
  </>
);
```

Copy the same root-wrapper export into `gatsby-ssr.jsx`; both files are included in the starter.

### 4. Run the local installation

From the extracted folder, install the pinned dependencies and start the app:

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

Open `http://localhost:5173`. One embedded chat panel should replace the loading message. The installed panel proves browser startup; complete the [visitor test](#test-conversation) to verify answers from your actual agent.

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

## Handle widget lifetime and identity

Keep navigation, removal and guest conversations predictable.

The root wrapper persists across Gatsby client navigation. Avoid initializing the widget in `onRouteUpdate` or in every page component. React owns the empty outer container, while the helper owns its inner target. Full reloads and real wrapper removal start a fresh guest conversation.

The helper serializes `load()` and disposal, reuses its own downloaded loader, and creates a fresh inner HTMLElement for each mount. It calls `destroy()` only for the widget it owns, then removes that target. Keep the outer container’s children under widget ownership.

| Event | Required behavior |
| --- | --- |
| Owner remains through navigation | Retain the mounted conversation; do not load or launch again. |
| Owner is removed while loading | Cancel startup where possible; finish an already-started load before cleanup and another mount. |
| Refresh or real remount | `persistence: 'memory'` starts a fresh guest conversation. |
| Logout/account switch | Remove the previous owner before support returns for the next account. Revoke your application/backend session separately. |

Browser `userID`, page context and launch values do not authenticate a customer. This public widget supplies no private-record authorization. Protected operations require a trusted backend boundary on every read/write, turn and resume; use the [canonical trusted-customer guidance](/docs/guides/integrations/crms/recognize-returning-customers#recognize-the-customer) before adding them. Widget `destroy()` does not delete transcripts or undo an in-flight business action.

### Limit support to selected pages

Keep the adaptation separate from the supplied starter.

If you move the wrapper into individual pages, navigation may destroy and recreate it. Retain the Effect cleanup and accept the fresh-conversation behavior. Do not install it both in a page and in `wrapRootElement`. For a site-wide widget, the root wrapper is the complete path supplied here.

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

## Test a visitor conversation

Verify the installed widget, replies and framework navigation.

Use a staging deployment with the final project/release configuration. If approved-domain restrictions are enabled, have the agent owner allow that origin. Check that the site’s content security policy permits the widget’s script, styles, fonts and runtime connections.

### 1. Open as a visitor

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

### 2. Check a question and follow-up

Send the prepared support question and a related follow-up. Both replies must match the intended agent/release and preserve the expected conversation context. Locate this exchange in the intended project’s [Transcripts](/docs/documentation/measure/transcripts).

### 3. Navigate and return

Use the starter’s **About** link and Back. Compare the result with [widget lifetime](#widget-lifecycle): the persistent owner should keep the same conversation. Open the nested route directly too. Check that navigation never leaves two active panels or a blank cached copy.

### 4. Check slow startup and recovery

Leave while the CDN/setup is pending, then return. There must be no overlapping load or detached-target error. Interrupt and restore the network. If a business action’s result is uncertain, check its outcome before retrying. Reload to confirm the fresh-start policy. If the site has sign-in, remove the widget during logout/account change and confirm that old messages do not return for another account.

### The panel stays blank

Trace the browser entry and configuration before changing the agent.

Confirm both placeholders were replaced and that the documented module/component actually executes in the browser. Check missing static files, blocked CDN/style/font/runtime requests, project public access, the Environment alias, its Published release and approved origins. The helper gives the target a visible height. After repairing a failed or partial load, reload the document; it does not automatically retry the SDK.

### Navigation duplicates or restarts support

Check layout placement, caching and cleanup ownership.

Remove other snippets and keep one owner. Compare your installation with the local [lifecycle instructions](#widget-lifecycle), including any framework cache or DOM-replacement behavior. A real unmount intentionally starts fresh with memory persistence. Preserve the helper’s cleanup rather than calling `load()` after every route event.

### The wrong agent answers

Check the published route with a fresh conversation.

Compare the installed project ID and Environment alias with the agent owner’s values. Confirm the known answer exists in that Published release; editing Draft does not change it. Use [Environment 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 application

Have the agent owner [publish the reviewed Environment](/docs/documentation/deploy/environments/publishing), including widget-setting changes. Run `npm run build` and deploy the generated `public/` directory to your Gatsby/static host. Use `npm run start -- --port 5173` to serve the production output locally. The starter generates Home and About; confirm direct requests to deployed nested paths work.

### 2. Accept the production route

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

### Update, roll back or remove

Change the responsible release and repeat the visitor test.

Keep the last working application build and public widget configuration. The CDN URL moves independently of the framework lockfile, so test after widget updates. App rollback does not roll back the agent or delete transcripts. To remove support, remove its entry/component and deploy, retaining cleanup during removal. After any change, use the same visitor test.

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

## Custom interface guides

Planned framework guides for your own chat or voice UI.

Custom-interface walkthroughs for Gatsby are **planned**, 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) |
