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

> ## Agent Instructions
> Weaverse component configuration uses `settings`. `inspector` is deprecated; never generate it.
> Weaverse Hydrogen themes use React Router v7: import from `react-router`, never `react-router-dom` or `@remix-run/*`.
> Before using any code sample, read `@weaverse/hydrogen` in the project's `package.json`: 6.x and 5.x import from different entries and use different type names, so code for one does not build on the other.
> `@weaverse/hydrogen` 6 (Shopify Hydrogen 2026.10 and later, the version these docs show) imports from `@weaverse/hydrogen/react-router` and uses `Weaverse*` types such as `WeaverseComponentProps`, `WeaverseComponentLoaderArgs` and `WeaverseComponentSchema`; the root `@weaverse/hydrogen` entry only exports `createSchema()`, data helpers and types.
> `@weaverse/hydrogen` 5.x (Hydrogen 2026.4 and earlier) imports everything from `@weaverse/hydrogen` and uses `HydrogenComponentProps`, `ComponentLoaderArgs` and `HydrogenComponentSchema`. On a 5.x project, convert samples to these names. Upgrade to 6 only when asked (`npx @weaverse/cli@latest migrate v6`, plus the Hydrogen 2026.10 upgrade). Do not mix major versions.
> Next.js themes use `@weaverse/hydrogen` 6.2.0 or later: import client and shared code from `@weaverse/hydrogen/next` and server-only code from `@weaverse/hydrogen/next/server`. `@weaverse/next` is deprecated; never install or import it.
> For live project data (pages, theme settings, translations), use the Weaverse MCP server: https://weaverse.io/docs/developer-tools/weaverse-mcp

# Integrating Weaverse into an Existing Hydrogen Project

> Add @weaverse/hydrogen 6 to an existing Hydrogen 2026.10 storefront, from the server.ts request lifecycle to WeaverseClient, caching and CSP.

This guide adds Weaverse to an **existing** Shopify Hydrogen storefront on **Hydrogen 2026.10** with **`@weaverse/hydrogen` 6**. Once it's in, merchants build pages visually in Weaverse Studio, edit theme settings, and use the sections you register.

> **Agent note:** This page targets Hydrogen 2026.10 with `@weaverse/hydrogen` 6.1. Import Weaverse from `@weaverse/hydrogen/react-router`. Build `WeaverseClient` in the app context from the request's Storefront client (`storefront`, `env`, `cache`, `waitUntil`, `request`, `themeSchema`, `components`, optional `locale`), return it from `createAppContext()`, and let `server.ts` copy the context onto React Router's `RouterContextProvider`. The root loader must return `weaverseTheme: await context.weaverse.loadThemeSettings()`. Pass `cache` to every `storefront.graphql()` call. Build the CSP with the theme's own `app/utils/csp.ts`. Never use `createHydrogenContext`, `storefront.query()`, `hydrogenRoutes()`, `weaverse.withCache`, or CSP helpers from `@shopify/hydrogen`. Pilot `main` is the reference implementation.

> [!NOTE]
>
> Pick the guide that matches your project. Check `package.json` (or run `npm ls @shopify/hydrogen`):
>
> | Your project | Weaverse SDK | Guide |
> | - | - | - |
> | Hydrogen 2026.10 or later | `@weaverse/hydrogen` 6 | This page |
> | Classic Hydrogen on React Router 7 (2025.5 to 2026.4) | `@weaverse/hydrogen` 5 | Move to Hydrogen 2026.10 first with the [v6 migration guide](https://weaverse.io/docs/migration-advanced/v6-migration.md), which also covers Weaverse |
> | Hydrogen on Remix | `@weaverse/hydrogen` 4 (legacy) | [v5 migration guide](https://weaverse.io/docs/migration-advanced/v5-migration.md), then the v6 guide |
>
> A 2026.10 project has a `server.ts` that composes the request lifecycle with `handleShopifyRoutes()`, and queries Shopify with `storefront.graphql()`. If yours still calls `createHydrogenContext()` or `storefront.query()`, it is classic Hydrogen.

Every sample on this page is trimmed from [Pilot](https://github.com/Weaverse/pilot), Weaverse's reference theme on Hydrogen 2026.10 and `@weaverse/hydrogen` 6.1. `// ...` marks omitted code. When a sample and Pilot disagree, Pilot `main` wins.

## Prerequisites

* A Hydrogen 2026.10 storefront that runs locally (`@shopify/hydrogen` `^2026.10`, React Router 7.18 or later 7.x, Vite 8).
* Node.js `^22.18.0 || ^24.11.0`, the range Pilot's `engines` field allows.
* A Weaverse account and a Weaverse project for the storefront.
* `@shopify/cli` 4.4.0 or later as a dev dependency if you deploy to Oxygen ([Step 10](#step-10-run-connect-and-deploy)).

## Step 1: Install the SDK

```bash theme={null}
npm install @weaverse/hydrogen@^6.1.0
```

`@weaverse/hydrogen` 6 has `@shopify/hydrogen` `>=2026.10.0` as a peer dependency, and depends on exactly `@weaverse/react` 6.1.0 and `@weaverse/next` 1.1.1. You don't need to install those yourself. If your `package.json` already lists `@weaverse/react` or `@weaverse/next`, align them to those versions: two copies of `@weaverse/react` have separate React contexts, and components stop finding their data. From 6.2.0, `@weaverse/hydrogen` no longer depends on `@weaverse/next`, which is deprecated; remove it if your `package.json` lists it.

Hydrogen themes import everything from one entry point:

```typescript theme={null}
import { WeaverseClient, withWeaverse, useThemeSettings } from "@weaverse/hydrogen/react-router";
```

The bare `@weaverse/hydrogen` entry holds schemas, data helpers and types without React or a router; you don't need it in a Hydrogen theme.

## Step 2: Configure Environment Variables

Add your project ID to `.env`:

```env theme={null}
# .env

# Required
WEAVERSE_PROJECT_ID="your-project-id"

# Optional
# WEAVERSE_API_KEY="your-weaverse-api-key"
# WEAVERSE_HOST="https://studio.weaverse.io"
```

The Project ID is in your Weaverse project settings. On Oxygen, add the same variables to the storefront's environment.

Hydrogen 2026.10 no longer ships `HydrogenEnv`, so `env.d.ts` lists every variable your theme reads. Extend the SDK's `WeaverseEnv`, which declares the Weaverse variables:

```typescript theme={null}
// env.d.ts
/// <reference types="vite/client" />
/// <reference types="react-router" />
/// <reference types="@shopify/oxygen-workers-types" />
import type { WeaverseEnv } from "@weaverse/hydrogen/react-router";
import type { AppContext } from "./app/.server/context";

declare global {
  interface Env extends WeaverseEnv {
    SESSION_SECRET: string;
    PUBLIC_STORE_DOMAIN: string;
    PUBLIC_STOREFRONT_API_TOKEN?: string;
    PRIVATE_STOREFRONT_API_TOKEN?: string;
    PUBLIC_STOREFRONT_ID?: string;
    PUBLIC_CHECKOUT_DOMAIN: string;
    WEAVERSE_PROJECT_ID: string;
    WEAVERSE_API_KEY?: string;
    WEAVERSE_HOST?: string;
    // ... the rest of your variables
  }
}

declare module "react-router" {
  // `server.ts` copies the app context onto React Router's context (Step 5)
  interface AppLoadContext extends AppContext {}
  interface RouterContextProvider extends AppContext {}
}
```

## Step 3: Add the Weaverse Files

Create `app/weaverse/`. It holds the theme schema, the component registry, the global styles and the content renderer.

### Theme Schema ([`app/weaverse/schema.server.ts`](https://github.com/Weaverse/pilot/blob/main/app/weaverse/schema.server.ts))

The theme's metadata, the global settings shown under **Theme > Customize** in Studio, and the i18n configuration:

```typescript theme={null}
// app/weaverse/schema.server.ts
import type { WeaverseThemeSchema } from "@weaverse/hydrogen/react-router";
import packageJson from "../../package.json" with { type: "json" };
import { DEFAULT_LOCALE, SUPPORTED_LOCALES } from "~/utils/locale";

export const themeSchema: WeaverseThemeSchema = {
  info: {
    version: packageJson.version,
    author: "Your Store Name",
    name: "Your Theme Name",
    authorProfilePhoto: "",
    documentationUrl: "https://docs.weaverse.io",
    supportUrl: "https://help.weaverse.io/",
  },
  // Optional; required for markets and the Translation Manager
  i18n: {
    urlStructure: "url-path",
    defaultLocale: DEFAULT_LOCALE,
    shopLocales: SUPPORTED_LOCALES,
  },
  settings: [
    {
      group: "Layout",
      inputs: [
        {
          type: "range",
          label: "Page width",
          name: "pageWidth",
          configs: { min: 1000, max: 1600, step: 10, unit: "px" },
          defaultValue: 1280,
        },
      ],
    },
    // ... more groups: colors, typography, header, footer
  ],
};
```

`DEFAULT_LOCALE` and `SUPPORTED_LOCALES` are your market list (Pilot's lives in `app/utils/locale.ts`). Pilot also sets `translation: true` and `staticContent` in `i18n` to turn on the [Translation Manager](https://weaverse.io/docs/features/translation-feature-guide.md), and keeps one file per settings group under `app/weaverse/settings/`.

### Component Registry ([`app/weaverse/components.ts`](https://github.com/Weaverse/pilot/blob/main/app/weaverse/components.ts))

Every component Studio can place, each a module that exports a `default` component and a `schema` (and optionally a `loader`):

```typescript theme={null}
// app/weaverse/components.ts
import type { WeaverseComponent } from "@weaverse/hydrogen/react-router";
import * as Heading from "~/components/heading";
import * as FeaturedProducts from "~/sections/featured-products";
import * as HeroImage from "~/sections/hero-image";

export const components: WeaverseComponent[] = [Heading, HeroImage, FeaturedProducts];
```

See [Creating Components](https://weaverse.io/docs/development-guide/creating-components.md) to write them.

### Global Styles ([`app/weaverse/style.tsx`](https://github.com/Weaverse/pilot/blob/main/app/weaverse/style.tsx))

Turns theme settings into CSS variables:

```tsx theme={null}
// app/weaverse/style.tsx
import { useThemeSettings } from "@weaverse/hydrogen/react-router";

export function GlobalStyle() {
  const settings = useThemeSettings();
  if (!settings) return null;
  return (
    <style
      id="global-theme-style"
      suppressHydrationWarning
      dangerouslySetInnerHTML={{
        __html: `:root { --page-width: ${settings.pageWidth}px; }`,
      }}
    />
  );
}
```

### Content Renderer ([`app/weaverse/index.tsx`](https://github.com/Weaverse/pilot/blob/main/app/weaverse/index.tsx))

`WeaverseContent` renders the page a route loaded. `validateWeaverseData` turns a missing page into a 404, except in Studio's design mode, where the editor needs the fallback page to start from:

```tsx theme={null}
// app/weaverse/index.tsx
import { WeaverseHydrogenRoot, type WeaverseLoaderData } from "@weaverse/hydrogen/react-router";
import { GenericError } from "~/components/root/generic-error";
import { components } from "./components";

export function WeaverseContent() {
  return <WeaverseHydrogenRoot components={components} errorComponent={GenericError} />;
}

export function validateWeaverseData(weaverseData: WeaverseLoaderData) {
  if (
    !weaverseData?.page?.id ||
    (weaverseData?.page?.id?.includes("fallback") &&
      !weaverseData?.configs?.requestInfo?.queries?.isDesignMode)
  ) {
    throw new Response(null, { status: 404 });
  }
}
```

## Step 4: Create the `WeaverseClient` in the App Context

Hydrogen 2026.10 has no `createHydrogenContext()`. Your app builds the per-request values itself, usually in `app/.server/context.ts`, and `server.ts` puts them on React Router's context. Add a `WeaverseClient` built from the request's Storefront client:

```typescript theme={null}
// app/.server/context.ts
import { WeaverseClient } from "@weaverse/hydrogen/react-router";
import { AppSession } from "~/.server/session";
import { createRequestStorefront, resolveRequestLocale } from "~/.server/storefront";
import { components } from "~/weaverse/components";
import { themeSchema } from "~/weaverse/schema.server";

export async function createAppContext(
  request: Request,
  env: Env,
  executionContext: ExecutionContext,
) {
  const waitUntil = executionContext.waitUntil.bind(executionContext);
  const [cache, session] = await Promise.all([
    caches.open("hydrogen"),
    AppSession.init(request, [env.SESSION_SECRET]),
  ]);
  const storefront = createRequestStorefront({ request, env, cache, waitUntil });

  const weaverse = new WeaverseClient({
    storefront, // the request-scoped Hydrogen 2026.10 Storefront client
    locale: resolveRequestLocale(request), // optional, 6.1.0+
    env,
    cache,
    waitUntil,
    request,
    themeSchema,
    components,
  });

  return { env, cache, waitUntil, session, storefront, weaverse };
}

export type AppContext = Awaited<ReturnType<typeof createAppContext>>;
```

`createRequestStorefront`, `resolveRequestLocale` and `AppSession` are app code: Pilot's live in `app/.server/storefront.ts` and `app/.server/session.ts`, and [Step 4 of the v6 migration guide](https://weaverse.io/docs/migration-advanced/v6-migration.md#step-4-build-the-app-context-yourself) walks through them. If your project already creates its Storefront client with `createStorefrontClient()`, pass that client; `WeaverseClient` only needs it per request.

`WeaverseClient` arguments:

| Argument | Required | Notes |
| - | - | - |
| `storefront` | Yes | The request's Storefront API client. Section loaders reach it as `weaverse.storefront`. |
| `env` | Yes | The worker `env`. Weaverse reads `WEAVERSE_PROJECT_ID`, `WEAVERSE_API_KEY`, `WEAVERSE_HOST`, `PUBLIC_STORE_DOMAIN` and `PUBLIC_STOREFRONT_API_TOKEN`. |
| `cache` | Yes | The worker cache (`caches.open(...)`). Weaverse content is cached in it ([Step 6](#step-6-cache-explicitly)). |
| `request` | Yes | The incoming request. |
| `themeSchema`, `components` | Yes | From Step 3. |
| `waitUntil` | No | Lets background cache writes finish after the response. Pass it. |
| `locale` | No | The market, as Weaverse identifies it. Added in 6.1.0, see below. |
| `customerAccount` | No | Your Customer Account client, passed through to section loaders. |
| `projectId` | No | A string or a function returning one, to choose the project per request. Defaults to `WEAVERSE_PROJECT_ID`. |
| `fetchTimeoutMs` | No | Weaverse API timeout. Defaults to 10 seconds. |
| `throwPageLoadFailures` | No | `loadPage()` rejects with a `WeaverseLoadError` when the Weaverse API fails, instead of resolving to `null` like a missing page. Pilot sets it and answers outages with a 503. |

### The `locale` Option

Weaverse uses the request's market for the locale it sends with page requests, the Translation Manager overrides it loads (keyed by `${language}-${country}`, lowercased), and the `requestInfo.i18n` Studio reads. Without `locale`, it takes all three from `storefront.i18n`.

Pass `locale` when the Storefront client's `i18n.language` is a Shopify `LanguageCode` that differs from the market's public language. A Traditional Chinese Hong Kong market sends `ZH_TW` to Shopify; given to Weaverse, it asks for `zh_tw-hk` translations, which match nothing and silently fall back to the theme defaults. The value is a `WeaverseI18n` (`language`, `country`, and optional `pathPrefix`, `label` and other market fields); include `pathPrefix`, which Weaverse passes to Studio. Pilot passes `resolveRequestLocale(request)`, the request's entry from its market list. `weaverse.storefront` stays the request's own client, so Shopify keeps receiving `ZH_TW`.

If `storefront.i18n` already carries the public language and the `pathPrefix`, leave `locale` out.

## Step 5: Wire the Request Lifecycle in `server.ts`

In Hydrogen 2026.10, `server.ts` owns the request: it builds the context, lets Hydrogen's handlers answer the routes they own, renders the app with React Router, and finishes the response. Weaverse only needs the context it puts on React Router to include `weaverse`. If your `server.ts` already copies the app context onto `RouterContextProvider`, adding `weaverse` to `createAppContext()` is enough.

Pilot's `server.ts`, trimmed:

```typescript theme={null}
// server.ts
import { handleShopifyRedirects, handleShopifyRoutes } from "@shopify/hydrogen";
import { createRequestHandler, RouterContextProvider } from "react-router";
import * as serverBuild from "virtual:react-router/server-build";
import { cartHandlers } from "~/.server/cart";
import { createAppContext } from "~/.server/context";
import { routeTemplates } from "~/utils/route-templates";

const handleRequest = createRequestHandler(serverBuild, process.env.NODE_ENV);

export default {
  async fetch(request: Request, env: Env, executionContext: ExecutionContext): Promise<Response> {
    try {
      // 1. Build the request context: session, Storefront client, WeaverseClient
      const appContext = await createAppContext(request, env, executionContext);
      const { session, storefront } = appContext;
      const requestContext = storefront.requestContext;

      // 2. Let Hydrogen answer the routes it owns (/api/cart, /account/login, ...)
      const shopifyRoute = handleShopifyRoutes({
        request,
        requestContext,
        sessionManager: session,
        storefrontClient: storefront,
        routeTemplates,
        handlers: [cartHandlers /* , predictive search, Customer Account, ... */],
      });
      if (shopifyRoute) {
        const response = await shopifyRoute;
        await commitSession(response, appContext);
        return response;
      }

      // 3. Render the app. Loaders read context.storefront, context.weaverse, ...
      const routerContext = Object.assign(new RouterContextProvider(), appContext);
      const response = await handleRequest(request, routerContext);

      // 4. On a 404, look the path up in Shopify's URL redirects
      if (response.status === 404) {
        const redirect = await handleShopifyRedirects({
          request,
          storefrontClient: storefront,
          routeTemplates,
        });
        if (redirect) return redirect;
      }

      // 5. Commit the session, then apply Shopify's response headers
      await commitSession(response, appContext);
      requestContext.applyResponseHeaders(response.headers);
      return response;
    } catch (error) {
      console.error(error);
      return new Response("An unexpected error occurred", { status: 500 });
    }
  },
};

async function commitSession(
  response: Response,
  { session }: Awaited<ReturnType<typeof createAppContext>>,
) {
  const headers = new Headers((await session.commit()) ?? undefined);
  for (const [name, value] of headers) response.headers.append(name, value);
}
```

* `Object.assign(new RouterContextProvider(), appContext)` keeps React Router's context instance and adds your values to it. Don't spread it into a plain object.
* `handleShopifyRoutes` decides synchronously: it returns a `Promise<Response>` for a path one of its handlers owns, and `null` otherwise.
* `routeTemplates` comes from `createShopifyRouteTemplates()` (`app/utils/route-templates.ts` in Pilot). Both it and `applyResponseHeaders()` fail silently when missing.
* Pilot's full `server.ts` adds its own cart, predictive search and Customer Account handlers, market-aware redirects and an HTTPS fix for tunnels. See [Step 3 of the v6 migration guide](https://weaverse.io/docs/migration-advanced/v6-migration.md#step-3-own-the-request-lifecycle-in-the-server-entry).

## Step 6: Cache Explicitly

Hydrogen 2026.10 has no default cache: a `storefront.graphql()` call without `cache` hits the Storefront API on every request. Pilot keeps its strategies in [`app/utils/cache.ts`](https://github.com/Weaverse/pilot/blob/main/app/utils/cache.ts):

```typescript theme={null}
// app/utils/cache.ts
import { Cache } from "@shopify/hydrogen";

// Classic Hydrogen's implicit default: fresh for a second, stale for a day
export const CACHE_DEFAULT = Cache({ mode: "public", maxAge: 1, staleWhileRevalidate: 86_399 });
export const CACHE_SHORT = Cache.short();
export const CACHE_LONG = Cache.long();
export const CACHE_NONE = Cache.none();
```

Pass one on every query, in routes and in section loaders alike:

```typescript theme={null}
// app/sections/featured-collections/index.tsx
import { gql } from "@shopify/hydrogen";
import type { WeaverseComponentLoaderArgs } from "@weaverse/hydrogen/react-router";
import { CACHE_DEFAULT } from "~/utils/cache";
import { unwrapStorefront } from "~/utils/storefront";

const COLLECTIONS_QUERY = gql(`
  query collectionsByIds($country: CountryCode, $language: LanguageCode, $ids: [ID!]!)
  @inContext(country: $country, language: $language) {
    nodes(ids: $ids) { ... on Collection { id title handle } }
  }
`);

export const loader = async ({ data, weaverse }: WeaverseComponentLoaderArgs<FeaturedCollectionsData>) => {
  const ids = data.collections?.map(
    (collection) => `gid://shopify/Collection/${collection.id}`,
  );
  if (!ids?.length) return [];
  const { nodes } = unwrapStorefront(
    await weaverse.storefront.graphql(COLLECTIONS_QUERY, {
      variables: { ids }, // $country and $language come from the request context
      cache: CACHE_DEFAULT,
    }),
  );
  // `nodes(ids:)` returns any `Node`, or null: keep the collections
  return nodes.filter((node) => Boolean(node && "id" in node));
};
```

`graphql()` returns `{ data, errors }` and doesn't throw on GraphQL errors; Pilot's `unwrapStorefront()` (`app/utils/storefront.ts`) throws instead, so a failed query reaches the route's error boundary. See [Data Fetching](https://weaverse.io/docs/development-guide/data-fetching.md) for query patterns.

Weaverse caches its own content in the `cache` you gave `WeaverseClient`: fresh for 60 seconds, then served stale for up to a day while it revalidates or when the Weaverse API fails. Studio's design and preview modes skip the cache. To change it for one call, pass a strategy: `context.weaverse.loadPage({ type, handle, strategy: CACHE_LONG })` or `context.weaverse.loadThemeSettings(CACHE_LONG)`. For a third-party API in a section loader, `weaverse.fetchWithCache(url, { ...init, strategy })` goes through the same cache; it replaces v5's `weaverse.withCache`.

Pilot also sets `Cache-Control` per route with `export const headers = routeHeaders` from the same file, and keeps loaders free of per-shopper data so Oxygen can cache whole documents.

## Step 7: Own the Content Security Policy

Hydrogen 2026.10 removes `createContentSecurityPolicy`, `NonceProvider` and `useNonce`. The theme builds the header and the nonce itself, with two files from Pilot:

* [`app/utils/csp.ts`](https://github.com/Weaverse/pilot/blob/main/app/utils/csp.ts): `generateNonce`, `createContentSecurityPolicy(nonce, directives, shop)`, `NonceProvider` and `useNonce`, with the same header semantics as Hydrogen 2026.4's helper. Copy it as is.
* [`app/weaverse/csp.ts`](https://github.com/Weaverse/pilot/blob/main/app/weaverse/csp.ts): `getWeaverseCsp(request, env)`, the directives Weaverse Studio and your third-party services need. In design mode it allows Studio to frame the storefront (`frame-ancestors *`) and adds `'unsafe-eval'` for the Studio bridge. Copy it and add your own sources.

Build the header in `app/entry.server.tsx`, and pass the same nonce to the renderer, `ServerRouter` and `NonceProvider`:

```tsx theme={null}
// app/entry.server.tsx
import { isbot } from "isbot";
import { renderToReadableStream } from "react-dom/server";
import type { EntryContext, RouterContextProvider } from "react-router";
import { ServerRouter } from "react-router";
import { createContentSecurityPolicy, generateNonce, NonceProvider } from "~/utils/csp";
import { getWeaverseCsp } from "~/weaverse/csp";

export default async function handleRequest(
  request: Request,
  responseStatusCode: number,
  responseHeaders: Headers,
  reactRouterContext: EntryContext,
  context: RouterContextProvider,
) {
  const nonce = generateNonce();
  const header = createContentSecurityPolicy(nonce, getWeaverseCsp(request, context.env), {
    checkoutDomain: context.env?.PUBLIC_CHECKOUT_DOMAIN || context.env?.PUBLIC_STORE_DOMAIN,
    storeDomain: context.env?.PUBLIC_STORE_DOMAIN,
  });

  const body = await renderToReadableStream(
    <NonceProvider value={nonce}>
      <ServerRouter context={reactRouterContext} url={request.url} nonce={nonce} />
    </NonceProvider>,
    {
      nonce,
      signal: request.signal,
      onError(error) {
        console.error(error);
        responseStatusCode = 500;
      },
    },
  );

  if (isbot(request.headers.get("user-agent"))) {
    await Promise.race([body.allReady, new Promise((resolve) => setTimeout(resolve, 2000))]);
  }

  responseHeaders.set("Content-Type", "text/html");
  // Pilot ships report-only. Switch to "Content-Security-Policy" once your directives are complete.
  responseHeaders.set("Content-Security-Policy-Report-Only", header);

  return new Response(body, { headers: responseHeaders, status: responseStatusCode });
}
```

`context.env` is typed because `RouterContextProvider` extends `AppContext` (Step 2). In `app/entry.client.tsx`, wrap `<HydratedRouter />` in `<NonceProvider value={existingNonce}>`, reading the nonce from `document.querySelector<HTMLScriptElement>("script[nonce]")?.nonce`. Then pass `useNonce()` to `<Scripts>`, `<ScrollRestoration>` and `<ShopifyScripts>` in the root route. A dropped nonce leaves hydration silently dead. See [Content Security Policy](https://weaverse.io/docs/features/content-security.md) for each source and for rolling out an enforced policy.

## Step 8: Wrap the Root Layout and Load Theme Settings

Weaverse wraps the component that renders the HTML document, which is the `Layout` export. The root loader must return the theme settings as `weaverseTheme`: `withWeaverse` and `useThemeSettings()` read them from the root route's data.

```tsx theme={null}
// app/root.tsx
import { withWeaverse } from "@weaverse/hydrogen/react-router";
import type { LoaderFunctionArgs } from "react-router";
import { Links, Meta, Outlet, Scripts, ScrollRestoration, useRouteLoaderData } from "react-router";
import { useNonce } from "~/utils/csp";
import { GlobalStyle } from "~/weaverse/style";

export type RootLoader = typeof loader;

export async function loader({ context }: LoaderFunctionArgs) {
  const weaverseTheme = await context.weaverse.loadThemeSettings();
  return {
    weaverseTheme,
    selectedLocale: context.storefront.i18n,
    // ... layout data, ShopifyScripts config, consent
  };
}

function App() {
  return <Outlet />;
}

export const Layout = withWeaverse(function RootLayout({ children }: { children: React.ReactNode }) {
  const nonce = useNonce();
  const data = useRouteLoaderData<RootLoader>("root");

  return (
    // Pilot sets `lang` from its market list (`locale.hreflang`)
    <html lang="en">
      <head>
        {/* ... meta, <ShopifyScripts nonce={nonce} ... /> */}
        <Meta />
        <Links />
        <GlobalStyle />
      </head>
      <body>
        {/* ... CartProvider, header */}
        <main>{children}</main>
        {/* ... footer */}
        <ScrollRestoration nonce={nonce} />
        <Scripts nonce={nonce} />
      </body>
    </html>
  );
});

export default App;
```

* **Wrap `Layout`, not the default `App` export.** Wrapping `App` leaves the Weaverse providers below the document, so theme settings and Studio's design mode don't initialize.
* `withWeaverse` takes no component list; `WeaverseContent` renders the registered components.
* Pilot's root loader passes the theme through `localizedThemePayload()` and `neutralThemeWhenUnavailable()` before returning it, and answers `no-store` when the settings failed to load (`app/.server/root.ts` and `app/weaverse/load-failure.ts`). Start with the plain call and add those when you need them.

## Step 9: Load Weaverse Pages in Your Routes

Hydrogen 2026.10 has no `hydrogenRoutes()`; `app/routes.ts` exports the route array directly. Add a catch-all so pages created in Studio resolve at any handle:

```typescript theme={null}
// app/routes.ts
import { index, prefix, type RouteConfig, route } from "@react-router/dev/routes";

export default [
  ...prefix(":locale?", [
    index("routes/home.tsx"),
    route("products/:productHandle", "routes/products/product.tsx"),
    route("pages/:pageHandle", "routes/pages/regular-page.tsx"),
    // ... your other routes
    route("*", "routes/catch-all.tsx"), // Weaverse custom pages
  ]),
] satisfies RouteConfig;
```

Pilot also wraps these routes in layout routes that answer 404 for unsupported market prefixes; see [Markets in the v6 migration guide](https://weaverse.io/docs/migration-advanced/v6-migration.md#markets).

In each route Weaverse should drive, load the page with `context.weaverse.loadPage()` and render `<WeaverseContent />`. The homepage, from Pilot:

```tsx theme={null}
// app/routes/home.tsx
import { gql } from "@shopify/hydrogen";
import { getWeaverseSeoMeta, type PageType } from "@weaverse/hydrogen/react-router";
import type { LoaderFunctionArgs, MetaArgs } from "react-router";
import { CACHE_LONG, routeHeaders } from "~/utils/cache";
import { unwrapStorefront } from "~/utils/storefront";
import { validateWeaverseData, WeaverseContent } from "~/weaverse";

export const headers = routeHeaders;

export async function loader({ params, context }: LoaderFunctionArgs) {
  const { pathPrefix } = context.storefront.i18n;
  const locale = pathPrefix?.slice(1) || "";
  let type: PageType = "INDEX";

  if (params.locale && params.locale.toLowerCase() !== locale) {
    // Not a market prefix: a Weaverse custom page at the root
    type = "CUSTOM";
  }

  const [weaverseData, { shop }] = await Promise.all([
    context.weaverse.loadPage({ type }),
    context.storefront.graphql(SHOP_QUERY, { cache: CACHE_LONG }).then(unwrapStorefront),
  ]);
  validateWeaverseData(weaverseData);

  return { shop, weaverseData };
}

export const meta = ({ data }: MetaArgs<typeof loader>) => getWeaverseSeoMeta(data?.weaverseData);

export default function Homepage() {
  return <WeaverseContent />;
}

const SHOP_QUERY = gql(`
  query shop($country: CountryCode, $language: LanguageCode)
  @inContext(country: $country, language: $language) {
    shop { name description }
  }
`);
```

A product page loads the Weaverse page next to the product, in parallel:

```tsx theme={null}
// app/routes/products/product.tsx
import { getSelectedProductOptions } from "@weaverse/hydrogen/react-router";
import type { LoaderFunctionArgs } from "react-router";
import { PRODUCT_QUERY } from "~/graphql/queries";
import { CACHE_DEFAULT } from "~/utils/cache";
import { unwrapStorefront } from "~/utils/storefront";
import { WeaverseContent } from "~/weaverse";

export async function loader({ params, request, context }: LoaderFunctionArgs) {
  const { productHandle: handle } = params;
  const { storefront, weaverse } = context;
  // Hydrogen's selected options, without Weaverse's Studio query params
  const selectedOptions = getSelectedProductOptions(request);

  const [{ shop, product }, weaverseData] = await Promise.all([
    storefront
      .graphql(PRODUCT_QUERY, { variables: { handle, selectedOptions }, cache: CACHE_DEFAULT })
      .then(unwrapStorefront),
    weaverse.loadPage({ type: "PRODUCT", handle }),
  ]);

  if (!product?.id) {
    throw new Response("product", { status: 404 });
  }

  return { shop, product, weaverseData, selectedOptions };
}

export default function Product() {
  return <WeaverseContent />;
}
```

Pilot's product route also wraps `<WeaverseContent />` in Hydrogen's `ProductProvider`, so every section shares one variant selection; see [Step 9 of the v6 migration guide](https://weaverse.io/docs/migration-advanced/v6-migration.md#step-9-rebuild-product-forms-and-variant-selection). `WeaverseContent` renders the page you loaded with the components from `components.ts`.

## Step 10: Run, Connect and Deploy

1. **Start the dev server:** `npm run dev`. Pilot's script is `vite dev --port 3456`; use the URL your terminal prints.
2. **Open Weaverse Studio:** go to your project at [studio.weaverse.io](https://studio.weaverse.io/dashboard).
3. **Set the Preview URL** to your local dev server.

Your storefront now loads in the Weaverse editor. Check that sections render, theme settings apply, and the browser console shows no CSP violations.

To deploy to Oxygen, build, then point Shopify CLI at the build output:

```bash theme={null}
npm run build    # react-router build: writes dist/client and dist/server
npx shopify hydrogen deploy --assets-dir dist/client --worker-dir dist/server
```

Pilot keeps the second command as its `deploy` script, with `buildDirectory: "dist"` in `react-router.config.ts`. The flags need `@shopify/cli` 4.4.0 or later. See [Deploy to Oxygen](https://weaverse.io/docs/guides/deployment/oxygen.md).

## Next Steps

> [card] [Create Custom Components](https://weaverse.io/docs/development-guide/creating-components.md)
>
> Build React components that merchants can edit in Weaverse.

> [card] [Data Fetching](https://weaverse.io/docs/development-guide/data-fetching.md)
>
> Query Shopify from section loaders with `gql()` and an explicit cache.

> [card] [WeaverseClient Reference](https://weaverse.io/docs/api-reference/weaverse-client.md)
>
> Every argument and method of the server-side client.

> [card] [v6 Migration Guide](https://weaverse.io/docs/migration-advanced/v6-migration.md)
>
> Move a classic Hydrogen storefront to Hydrogen 2026.10 and Weaverse 6.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.