> ## 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/*`.
> Define component schemas with `createSchema()` from `@weaverse/hydrogen` (React Router themes) or `@weaverse/next` (Next.js themes).
> These docs cover @weaverse/hydrogen, @weaverse/react and @weaverse/core 5.x, and @weaverse/next 1.x. Do not use APIs from other major versions.
> For live project data (pages, theme settings, translations), use the Weaverse MCP server: https://docs.weaverse.io/developer-tools/weaverse-mcp

# Integrate Trustpilot Product Reviews with Shopify Hydrogen

> Add Trustpilot product-review widgets and server-rendered rating summaries to Shopify Hydrogen with SKU mapping, caching, CSP, and structured data.

# Integrate Trustpilot Product Reviews with Shopify Hydrogen

> [!NOTE]
>
> This guide is for Shopify Hydrogen storefronts. Building on Next.js? See the [Next.js overview](https://weaverse.io/docs/nextjs/overview.md).

Trustpilot Product Reviews can display product-level star ratings and review widgets on a Shopify Hydrogen storefront. The integration has two useful layers:

* A browser TrustBox widget for Trustpilot-managed rendering and interactions.
* An optional server-side API request for aggregate ratings used in initial HTML, product cards, or structured data.

This guide is based on maintained Weaverse Hydrogen implementations. Replace the example identifiers and file paths with your own project conventions.

## What you will build

```text theme={null}
Shopify product SKU
    ├──────────────► TrustBox widget in the browser
    │
    └──► Hydrogen server ──► Trustpilot Product Reviews API
                              └── aggregate rating + review count
```

Both paths depend on consistent product identifiers. Decide which Shopify SKU represents a Trustpilot product before writing UI code.

## Prerequisites

* Trustpilot Product Reviews enabled for the business account.
* A TrustBox template configured for product reviews.
* The Trustpilot business unit ID.
* A stable Shopify SKU mapping.
* A Trustpilot API key if server-side Product Reviews API access is required.

Example environment configuration:

```bash theme={null}
PUBLIC_TRUSTPILOT_BUSINESS_UNIT_ID=your-business-unit-id
PUBLIC_TRUSTPILOT_TEMPLATE_ID=your-trustbox-template-id
TRUSTPILOT_API_KEY=your-api-key
```

The widget's business unit and template IDs are visible in browser markup. Keep API credentials server-only.

## Load the TrustBox script once

Add the bootstrap script to the document head using Hydrogen's CSP nonce:

```tsx theme={null}
<script
  src="https://widget.trustpilot.com/bootstrap/v5/tp.widget.bootstrap.min.js"
  async
  nonce={nonce}
/>
```

If the root can render more than once in your environment, deduplicate the script by URL or a stable element ID.

## Render a product-rating widget

```tsx theme={null}
import { useEffect, useRef } from "react";

declare global {
  interface Window {
    Trustpilot?: {
      loadFromElement: (element: Element) => void;
    };
  }
}

type TrustpilotProductRatingProps = {
  businessUnitId: string;
  templateId: string;
  sku: string;
  locale?: string;
};

export function TrustpilotProductRating({
  businessUnitId,
  templateId,
  sku,
  locale = "en-US",
}: TrustpilotProductRatingProps) {
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const element = ref.current;
    if (!element) return;

    if (window.Trustpilot) {
      window.Trustpilot.loadFromElement(element);
      return;
    }

    const script = document.querySelector<HTMLScriptElement>(
      'script[src*="tp.widget.bootstrap"]',
    );
    if (!script) return;

    const initialize = () => window.Trustpilot?.loadFromElement(element);
    script.addEventListener("load", initialize, { once: true });
    return () => script.removeEventListener("load", initialize);
  }, [sku, templateId]);

  if (!(businessUnitId && templateId && sku)) return null;

  return (
    <div
      key={`${templateId}-${sku}`}
      ref={ref}
      className="trustpilot-widget"
      data-locale={locale}
      data-template-id={templateId}
      data-businessunit-id={businessUnitId}
      data-style-height="24px"
      data-style-width="100%"
      data-theme="light"
      data-sku={sku}
      data-no-reviews="show"
    >
      <a
        href="https://www.trustpilot.com"
        target="_blank"
        rel="noopener noreferrer"
      >
        Trustpilot
      </a>
    </div>
  );
}
```

Use the exact data attributes generated by the TrustBox configuration in Trustpilot Business. Different templates support different settings.

## Map Shopify products to Trustpilot SKUs

Trustpilot matches product reviews by SKU. A Hydrogen product can expose several candidate values:

* Product-level custom metafield.
* Selected variant SKU.
* A normalized group SKU shared by variants.
* Multiple SKUs for an aggregate widget, when supported by the selected template or API.

Define one function that implements the store's product identity rule and reuse it in product pages, cards, quick views, API requests, and structured data.

```ts theme={null}
export function getTrustpilotSku(product: {
  selectedOrFirstAvailableVariant?: { sku?: string | null } | null;
}) {
  return product.selectedOrFirstAvailableVariant?.sku?.trim() ?? "";
}
```

Do not silently fall back to a product handle unless the Trustpilot catalog also uses handles as SKUs.

## Reinitialize after client-side navigation

Hydrogen can replace the product without reloading the TrustBox bootstrap script. The component above calls `loadFromElement()` when the SKU changes and gives the widget a SKU-specific React key.

Test product A → product B → product A repeatedly. Also test quick-shop dialogs that mount after the initial document load.

## Optional: fetch aggregate ratings on the server

Use the Product Reviews API when the initial HTML needs a rating summary or when the same data feeds JSON-LD.

```ts theme={null}
const TRUSTPILOT_API = "https://api.trustpilot.com/v1";

type TrustpilotEnv = {
  TRUSTPILOT_API_KEY: string;
  TRUSTPILOT_BUSINESS_UNIT_ID: string;
};

export async function getTrustpilotSummary(
  skus: string[],
  env: TrustpilotEnv,
) {
  const uniqueSkus = [...new Set(skus.map((sku) => sku.trim()).filter(Boolean))];
  if (!uniqueSkus.length) return null;

  const url = new URL(
    `${TRUSTPILOT_API}/product-reviews/business-units/` +
      encodeURIComponent(env.TRUSTPILOT_BUSINESS_UNIT_ID),
  );
  url.searchParams.set("sku", uniqueSkus.join(","));
  url.searchParams.set("apikey", env.TRUSTPILOT_API_KEY);

  const response = await fetch(url);
  if (!response.ok) {
    console.error("Trustpilot Product Reviews request failed", response.status);
    return null;
  }

  const result = await response.json() as {
    starsAverage?: number;
    numberOfReviews?: { total?: number };
  };

  return {
    averageRating: result.starsAverage ?? 0,
    reviewCount: result.numberOfReviews?.total ?? 0,
  };
}
```

> [!WARNING]
>
> This request belongs on the server. Do not expose `TRUSTPILOT_API_KEY` through a public environment variable, Weaverse setting, browser request, or rendered HTML.

## Cache read-only summaries

Product-review summaries change less often than product inventory. Cache successful API responses with a stable key derived from the business unit and sorted SKUs. Do not cache upstream failures as valid zero-review results.

A useful Hydrogen policy is:

* Long cache for product-card summaries.
* Shorter cache when a just-submitted review must appear quickly.
* Stale-while-revalidate to avoid blocking the storefront during Trustpilot latency.
* `null` fallback when the API is unavailable.

The widget can continue rendering even when the optional server summary fails.

## Configure CSP

Allow the TrustBox bootstrap host in `script-src`:

```ts theme={null}
const csp = {
  scriptSrc: ["https://widget.trustpilot.com"],
};
```

The selected TrustBox can load additional Trustpilot frames, images, fonts, or API hosts. Inspect CSP violations on the deployed storefront and add only the required Trustpilot origins.

## Use Trustpilot with Weaverse

A Weaverse product section can expose public presentation settings:

* Business unit ID.
* TrustBox template ID.
* Locale and theme.
* Height, width, and alignment.
* Empty-review behavior.

Keep the SKU mapping in code or a controlled Shopify metafield. Keep the private API key exclusively in deployment configuration.

## Add structured data safely

When server-side summary data is available, it can feed the product's `AggregateRating` JSON-LD. Emit it only when:

* The summary belongs to the current product's mapped SKU.
* `reviewCount` is greater than zero.
* The rating scale matches the schema output.
* Another app or widget is not already emitting duplicate rating markup.

If the Trustpilot request fails, omit aggregate-rating JSON-LD rather than emitting zero or stale data.

## Test the integration

1. Verify SKU mapping against products in Trustpilot Business.
2. Test products with reviews, no reviews, and missing SKUs.
3. Navigate repeatedly between products and open quick-shop views.
4. Confirm the TrustBox uses the expected template and locale.
5. Verify server summaries match the visible widget.
6. Simulate API failure and confirm product pages still render.
7. Check CSP and script errors on mobile and desktop.
8. Validate structured data with the rendered page source.

## Production checklist

* Shopify-to-Trustpilot SKU mapping is documented and reused everywhere.
* Public widget IDs are separated from the private API key.
* The TrustBox script loads once.
* Widgets reinitialize after SPA navigation.
* Server summaries are cached and fail closed to `null`.
* Structured data is current and not duplicated.
* CSP allows only required Trustpilot hosts.

## Official resources

* [Trustpilot Product Reviews API](https://developers.trustpilot.com/product-reviews-api)
* [Trustpilot API authentication](https://developers.trustpilot.com/authentication)
* [Hydrogen caching](https://weaverse.io/docs/development-guide/data-fetching.md)
* [Hydrogen Content Security Policy](https://weaverse.io/docs/features/content-security.md)


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