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

# WeaverseClient

> The WeaverseClient class provides server-side methods to interact with Weaverse content and services in a Hydrogen storefront.

# WeaverseClient

The `WeaverseClient` class is a server-side utility that provides methods to interact with Weaverse services, fetch content, manage caching strategies, and load theme settings and page data for your Hydrogen storefront.

## Initialization

The `WeaverseClient` is typically initialized in your `server.ts` file and injected into your app's load context:

```tsx theme={null}
// Example from templates/pilot/server.ts
export async function createAppLoadContext(
  request: Request,
  env: Env,
  executionContext: ExecutionContext,
) {
  // ... other context setup

  let hydrogenContext = createHydrogenContext({
    env,
    request,
    cache,
    waitUntil,
    session,
    i18n: getLocaleFromRequest(request),
    cart: { queryFragment: CART_QUERY_FRAGMENT },
  });

  return {
    ...hydrogenContext,
    weaverse: new WeaverseClient({
      ...hydrogenContext,
      request,
      cache,
      themeSchema,
      components,
    }),
  };
}
```

Refer to the [Project Structure guide](core-concepts/project-structure#base-files-explained) for a detailed setup walkthrough.

## Type Definition

```typescript theme={null}
class WeaverseClient {
  constructor(args: WeaverseClientArgs);
  
  // Properties
  public API: string;  // API endpoint path
  public basePageConfigs: Omit<WeaverseProjectConfigs, 'requestInfo'>
  public basePageRequestBody: Omit<FetchProjectRequestBody, 'url'>
  public configs: WeaverseProjectConfigs
  public storefront: HydrogenContext['storefront'];
  public env: HydrogenEnv;
  public cache: Cache;
  public waitUntil: ExecutionContext['waitUntil'];
  public request: Request;
  public components: HydrogenComponent[];
  public themeSchema: HydrogenThemeSchema;
  
  // Methods
  fetchWithCache<T>(url: string, options?: RequestInit & { strategy?: AllCacheOptions }): Promise<T>;
  loadThemeSettings(strategy?: AllCacheOptions): Promise<HydrogenThemeSettings>;
  loadPage(params?: { type?: PageType, locale?: string, handle?: string, projectId?: string, strategy?: AllCacheOptions }): Promise<WeaverseLoaderData | null>;
  execComponentLoader(item: HydrogenComponentData): Promise<HydrogenComponentData>;
  generateFallbackPage(message: string): HydrogenPageData;
}

type WeaverseClientArgs = HydrogenContext & {
  components: HydrogenComponent[];
  themeSchema: HydrogenThemeSchema;
  request: Request;
  cache: Cache;
};
```

## Methods

### fetchWithCache

Fetches data from an external API with configurable caching strategies.

```typescript theme={null}
fetchWithCache<T>(url: string, options?: RequestInit & { strategy?: AllCacheOptions }): Promise<T>
```

**Parameters:**

* `url: string` - The endpoint URL
* `options?: RequestInit & { strategy?: AllCacheOptions }` - Cache and fetch configuration
  * `strategy` - Caching strategy with options like `maxAge`, `staleWhileRevalidate`, etc.
  * Other standard `fetch` options (`headers`, `method`, etc.)

**Returns:**

* `Promise<T>` - A promise that resolves with the fetched data

**Example:**

```typescript theme={null}
// In a component loader
export async function loader({ data, weaverse }: ComponentLoaderArgs) {
  const apiUrl = 'https://api.example.com/products';
  
  const products = await weaverse.fetchWithCache(apiUrl, {
    headers: {
      'Authorization': `Bearer ${process.env.API_KEY}`
    },
    cache: {
      maxAge: 60, // Cache for 60 seconds
      staleWhileRevalidate: 600 // Allow stale content for 10 minutes while revalidating
    }
  });
  
  return { products };
}
```

Refer to the [Data Fetching and Caching guide](/development-guide/data-fetching#fetching-data-from-external-apis) for more details.

### loadThemeSettings

Loads the global theme settings for the current Weaverse project.

```typescript theme={null}
loadThemeSettings(strategy?: AllCacheOptions): Promise<HydrogenThemeSettings>
```

**Parameters:**

* `strategy?: AllCacheOptions` - Optional caching strategy for the theme settings request

**Returns:**

* `Promise<HydrogenThemeSettings>` - The theme settings object

**Example:**

```typescript theme={null}
// In a route loader
export async function loader({ context }: LoaderFunctionArgs) {
  const { weaverse } = context;
  const themeSettings = await weaverse.loadThemeSettings();
  
  return json({
    themeSettings,
    // other data
  });
}
```

### loadPage

Loads a page's data from Weaverse, including running component loaders and handling localization.

```typescript theme={null}
loadPage(params?: {
  type?: PageType,
  locale?: string,
  handle?: string,
  projectId?: string,
  strategy?: AllCacheOptions
}): Promise<WeaverseLoaderData | null>
```

**Parameters:**

<AccordionGroup>
  <Accordion title="type?: PageType" icon="file" defaultOpen>
    Page type identifier determining the kind of content to load.

    **Supported types:**

    * `'INDEX'` - Homepage
    * `'PRODUCT'` - Product detail pages
    * `'COLLECTION'` - Collection/category pages
    * `'PAGE'` - Custom pages created in Weaverse Studio
    * `'BLOG'` - Blog listing pages
    * `'ARTICLE'` - Individual blog post pages
    * `'CUSTOM'` - Dynamic custom pages

    **Default:** Inferred from route context if not specified.

    **Required:** For most page types except INDEX and CUSTOM.
  </Accordion>

  <Accordion title="locale?: string" icon="globe">
    Locale identifier for loading localized content.

    **Format:** `language-country` (lowercase, hyphen-separated)

    * Language: ISO 639-1 code (2 letters, e.g., `sv`, `en`, `fr`)
    * Country: ISO 3166-1 alpha-2 code (2 letters, e.g., `se`, `us`, `ca`)

    **Examples:**

    * `"en-us"` - English in United States
    * `"sv-se"` - Swedish (sv) in Sweden (se)
    * `"fr-ca"` - French (fr) in Canada (ca)
    * `"de-de"` - German (de) in Germany (de)

    **Detection priority when not provided:**

    1. Path prefix from URL (deprecated)
    2. Auto-detection from `context.storefront.i18n.pathPrefix`

    **Fallback:** If the specified locale doesn't exist, falls back to `en-us` (smart fallback coming in future release).

    **When to use explicit locale:**

    * Custom routing logic determines locale
    * Loading content for different locale than current page
    * Background jobs without request context
    * Cross-locale content comparison

    See [Advanced Localization Guide](/guides/localization-advanced) for complete details.
  </Accordion>

  <Accordion title="handle?: string" icon="tag">
    Page handle/slug identifier for specific content.

    **Required for:**

    * `PRODUCT` - Product handle (e.g., `"classic-varsity-jacket"`)
    * `COLLECTION` - Collection handle (e.g., `"summer-collection"`)
    * `PAGE` - Custom page handle from Studio
    * `BLOG` - Blog handle
    * `ARTICLE` - Article handle

    **Not used for:**

    * `INDEX` - Homepage (no handle needed)
    * `CUSTOM` - Dynamic custom pages (URL determines content)

    **Format:** URL-friendly slug (lowercase, hyphens, no spaces)
  </Accordion>

  <Accordion title="projectId?: string" icon="folder-tree">
    Weaverse project ID for multi-project architectures.

    **Default:** Value from `WEAVERSE_PROJECT_ID` environment variable

    **When to use:**

    * Multi-brand storefronts sharing infrastructure
    * Different projects per market or locale
    * A/B testing different project configurations
    * Staging vs production project separation

    **Example use case:** Domain-based project selection

    ```typescript theme={null}
    let projectId = origin === "https://store.se"
      ? "project-sweden-123"
      : "project-default-456";

    let data = await weaverse.loadPage({ type: "INDEX", projectId });
    ```

    **Important:** Set up `projectId` in WeaverseClient initialization for automatic domain-based routing. Route-level override is available for special cases.

    See [Multi-Project Architecture Guide](/guides/multi-project-architecture) for comprehensive implementation details, including A/B testing, multi-brand setups, and step-by-step migration guides.
  </Accordion>

  <Accordion title="strategy?: AllCacheOptions" icon="database">
    Caching strategy configuration for the page data request.

    **Options:**

    * `mode?` - Cache control mode: `'public'`, `'private'`, `'no-cache'`, `'no-store'`, `'must-revalidate'`
    * `maxAge?` - Cache duration in seconds
    * `staleWhileRevalidate?` - Serve stale content while revalidating in seconds
    * `sMaxAge?` - Shared cache (CDN) duration in seconds
    * `staleIfError?` - Serve stale content if error occurs in seconds

    **Example:**

    ```typescript theme={null}
    strategy: {
      mode: "public",
      maxAge: 3600, // Cache for 1 hour
      staleWhileRevalidate: 86400, // Serve stale for 24h while updating
      sMaxAge: 7200, // CDN cache for 2 hours
      staleIfError: 604800, // Serve stale for 7 days if error
    }
    ```
  </Accordion>
</AccordionGroup>

**Returns:**

* `Promise<WeaverseLoaderData | null>` - Page data object or `null` if not found

**Examples:**

<CodeGroup>
  ```typescript Basic Usage theme={null}
  // Auto-detects locale from context.storefront.i18n
  export async function loader({ context, params }: LoaderFunctionArgs) {
    let { weaverse } = context;

    let weaverseData = await weaverse.loadPage({
      type: "PRODUCT",
      handle: params.productHandle,
    });

    return { weaverseData };
  }
  ```

  ```typescript With Explicit Locale theme={null}
  // Load Swedish content explicitly
  export async function loader({ context, params }: LoaderFunctionArgs) {
    let { weaverse } = context;

    let weaverseData = await weaverse.loadPage({
      type: "PRODUCT",
      handle: params.productHandle,
      locale: "sv-se", // Swedish (sv) in Sweden (se)
    });

    return { weaverseData };
  }
  ```

  ```typescript Cross-Locale Loading theme={null}
  // Load content in multiple locales
  export async function loader({ context, params }: LoaderFunctionArgs) {
    let { weaverse } = context;
    let { productHandle } = params;

    let [englishData, frenchData, swedishData] = await Promise.all([
      weaverse.loadPage({ type: "PRODUCT", handle: productHandle, locale: "en-us" }),
      weaverse.loadPage({ type: "PRODUCT", handle: productHandle, locale: "fr-ca" }),
      weaverse.loadPage({ type: "PRODUCT", handle: productHandle, locale: "sv-se" }),
    ]);

    return { englishData, frenchData, swedishData };
  }
  ```

  ```typescript Multi-Project Setup theme={null}
  // Load from different project based on domain
  export async function loader({ context, request, params }: LoaderFunctionArgs) {
    let { weaverse } = context;
    let origin = new URL(request.url).origin;

    // Determine project by domain
    let projectId = origin === "https://mystore.se"
      ? "project-sweden-123"
      : "project-default-456";

    let weaverseData = await weaverse.loadPage({
      type: "PRODUCT",
      handle: params.productHandle,
      projectId, // Override default project
    });

    return { weaverseData };
  }
  ```

  ```typescript Complete Example theme={null}
  // All parameters with error handling
  export async function loader({ context, request, params }: LoaderFunctionArgs) {
    let { weaverse } = context;

    // Determine locale from custom logic
    let locale = params.locale?.toLowerCase() || "en-us";

    let weaverseData = await weaverse.loadPage({
      type: "PRODUCT",
      handle: params.productHandle,
      locale,
      strategy: {
        maxAge: 3600,              // Cache for 1 hour
        staleWhileRevalidate: 86400 // Stale-while-revalidate for 24h
      }
    });

    if (!weaverseData) {
      throw new Response("Page not found", { status: 404 });
    }

    return { weaverseData, locale };
  }
  ```
</CodeGroup>

**Related:**

* [Rendering Weaverse Pages](/guides/rendering-page) - Complete guide to page rendering
* [Advanced Localization](/guides/localization-advanced) - Locale detection and multi-project setup
* [Multi-Project Architecture](/guides/multi-project-architecture) - A/B testing, multi-brand, and advanced routing
* [Markets & Localization](/features/markets-localization) - Studio workflow for localized content

### execComponentLoader

Executes a component's loader function to fetch its data.

```typescript theme={null}
execComponentLoader(item: HydrogenComponentData): Promise<HydrogenComponentData>
```

**Parameters:**

* `item: HydrogenComponentData` - Component data object

**Returns:**

* `Promise<HydrogenComponentData>` - Component data with loader data added

**Note:** This method is primarily used internally by `loadPage` to process component loaders.

### generateFallbackPage

Generates a fallback page when the requested page data isn't available.

```typescript theme={null}
generateFallbackPage(message: string): HydrogenPageData
```

**Parameters:**

* `message: string` - Message to display on the fallback page

**Returns:**

* `HydrogenPageData` - A basic page data object with the message

## Related

* [useWeaverse](/api-reference/use-weaverse) - Hook for accessing Weaverse instance client-side
* [Data Fetching and Caching](/development-guide/data-fetching) - Advanced guide on data fetching
