Skip to main content

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:
// 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 for a detailed setup walkthrough.

Type Definition

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.
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:
// 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 for more details.

loadThemeSettings

Loads the global theme settings for the current Weaverse project.
loadThemeSettings(strategy?: AllCacheOptions): Promise<HydrogenThemeSettings>
Parameters:
  • strategy?: AllCacheOptions - Optional caching strategy for the theme settings request
Returns:
  • Promise<HydrogenThemeSettings> - The theme settings object
Example:
// 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.
loadPage(params?: {
  type?: PageType,
  locale?: string,
  handle?: string,
  projectId?: string,
  strategy?: AllCacheOptions
}): Promise<WeaverseLoaderData | null>
Parameters:

type?: PageType

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.
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 for complete details.
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)
Weaverse project ID for multi-project architectures.Default: Value from WEAVERSE_PROJECT_ID environment variableWhen 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
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 for comprehensive implementation details, including A/B testing, multi-brand setups, and step-by-step migration guides.
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:
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
}
Returns:
  • Promise<WeaverseLoaderData | null> - Page data object or null if not found
Examples:
// 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 };
}
Related:

execComponentLoader

Executes a component’s loader function to fetch its data.
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.
generateFallbackPage(message: string): HydrogenPageData
Parameters:
  • message: string - Message to display on the fallback page
Returns:
  • HydrogenPageData - A basic page data object with the message