# Headless storefronts

On a headless storefront, such as Hydrogen or a Next.js site, the app's theme blocks don't load. There are two ways to add the wishlist:

- **The storefront script (recommended).** Add one script tag and the same buttons, header count, drawer and wishlist page as on the Online Store work on your site, with your settings, translations and hide rules. You place the elements; the script does the rest.
- **The REST API.** Build every button and page yourself and call the [REST API](https://wishlist.themivo.com/docs/rest-api) from your server. Use it when you want full control of the markup.

Both keep everything else working: analytics, emails for signed-in customers, outgoing webhooks and Shopify Flow.

## The storefront script

### What you need

| For | You need | Where it lives |
|---|---|---|
| Guests | Only the script tag | Every page |
| Product titles, images and prices | Your **public Storefront API access token**, from Shopify | `data-storefront-token` on the script tag. It's made for browsers, so it's safe in the page. |
| Signed-in customers | An **API key** of this app, used by your server to mint a **customer token** | The API key stays on your server. Only the customer token goes on the script tag, as `data-customer-token`. |

Start with guests: steps 1 to 4 below. Add [signed-in customers](#signed-in-customers) once that works.

### 1. Allow your site

In the app, open **Developers → Headless storefront** and add the origin of each site that will load the script, such as `https://shop.example.com`. `https://*.example.com` allows every subdomain, for preview deployments, and `http://localhost:3000` works for local development. Other sites get `403`. Changes apply within a minute.

### 2. Add the script

Add this tag to every page, for example in the root layout. Replace the shop with your `myshopify.com` domain; the **Developers** page shows the tag ready to copy.

```html
<script
  type="module"
  src="https://wishlist-edge.themivo.com/storefront/v1/wishlist.js"
  data-wishlist-shop="your-store.myshopify.com"
  data-storefront-token="your-public-storefront-token"
  data-locale="en"
  data-wishlist-url="/wishlist"
></script>
```

The script loads in the background and never blocks rendering. It always serves the latest version; you don't need to update the URL.

| Attribute | Required | Description |
|---|---|---|
| `data-wishlist-shop` | Yes | Your `myshopify.com` domain. |
| `data-customer-token` | For customers | Who the signed-in customer is. See [Signed-in customers](#signed-in-customers). Leave it out for guests. |
| `data-locale` | No | Language of the wishlist's texts, such as `fr` or `pt-BR`. Defaults to the `lang` of the page. Uses your translations under **Settings → Translations**. |
| `data-country` | No | Country code of the market, such as `FR`, for prices in the wishlist. |
| `data-currency` | No | Currency shown, such as `EUR`. Defaults to the shop's currency. |
| `data-wishlist-url` | No | Path of your wishlist page, such as `/wishlist`. Used by links to the wishlist when **List view** is set to a page. |
| `data-product-url` | No | Path of a product page with `{handle}`, such as `/shop/{handle}`. Defaults to `/products/{handle}`. |
| `data-login-url` | No | Your sign-in page, linked when a guest must sign in to save. |
| `data-storefront-token` | Recommended | Your public Storefront API access token, used to read product titles, images and prices. On Hydrogen, it's `PUBLIC_STOREFRONT_API_TOKEN` in your environment; otherwise, find it in Shopify admin under **Sales channels → Headless → your storefront → Storefront API**. Without it, the wishlist uses Shopify's tokenless access, which stops working while the Online Store is password-protected, as it often is on headless shops. |

### 3. Place the elements

The script doesn't know your markup, so nothing is inserted automatically, apart from the floating launcher when it's turned on under **Appearance**. Put these elements where you want them:

```html
<!-- On product cards and the product page -->
<wl-card-button product-id="7982301"></wl-card-button>
<wl-button product-id="7982301" variant-id="44012345"></wl-button>

<!-- In the header: opens the wishlist, shows the count -->
<wl-count></wl-count>

<!-- On your wishlist page, at data-wishlist-url -->
<wl-page></wl-page>
```

Ids are the numbers at the end of the GIDs (`gid://shopify/Product/7982301` → `7982301`). The elements are custom elements, so they work in React, Vue or plain HTML, including when your app renders them after navigation. To use your own buttons instead, add `data-wishlist-toggle="{productId}"` to any element; see [Customization](https://wishlist.themivo.com/docs/customization). The look follows **Appearance**; style the elements further with CSS parts.

### 4. Hand Add to cart to your cart

The wishlist's **Add to cart** buttons can't reach a headless cart by themselves. Take the add over with `beforeAddToCart` and add the lines with your cart, for example the Storefront API `cartLinesAdd` mutation:

```js
document.addEventListener("wishlist:ready", () => {
  window.Wishlist.on("beforeAddToCart", (event) => {
    event.respondWith(
      addLinesToMyCart(
        event.detail.items.map((line) => ({
          merchandiseId: `gid://shopify/ProductVariant/${line.variantId}`,
          quantity: line.quantity,
          // Counts the order line as wishlist revenue, guests included.
          attributes: [{ key: "_wl", value: "list" }],
        })),
      ),
    );
  });
});
```

The wishlist waits for the promise, then shows "Added to cart". Without a handler, the shopper goes to Shopify checkout with those items. See [JavaScript API](https://wishlist.themivo.com/docs/js-api#changing-add-to-cart).

### Signed-in customers

On the Online Store, Shopify tells the wishlist who is signed in. On a headless site, the browser can't prove it, so your server vouches for the customer with a short-lived customer token:

1. In the app, create an API key with the `write` scope under **Developers → API keys**. Keep it in a server-side secret, such as `WISHLIST_API_KEY`.
2. When a customer is signed in, call `POST /customers/{customerId}/customer-token` from your server. `customerId` is the number at the end of the customer's GID, which you get from the Customer Account API (`gid://shopify/Customer/7982301` → `7982301`).
3. Put the returned `token` on the script tag as `data-customer-token`.

```ts
// app/lib/wishlist.server.ts
export async function wishlistCustomerToken(env: Env, customerGid: string) {
  const customerId = customerGid.split("/").pop();
  const response = await fetch(
    `https://wishlist-edge.themivo.com/api/v1/customers/${customerId}/customer-token`,
    { method: "POST", headers: { Authorization: `Bearer ${env.WISHLIST_API_KEY}` } },
  );
  if (!response.ok) return null; // The script then runs as a guest.
  const { token, expiresAt } = await response.json();
  return { token, expiresAt };
}
```

```tsx
<script
  type="module"
  src="https://wishlist-edge.themivo.com/storefront/v1/wishlist.js"
  data-wishlist-shop="your-store.myshopify.com"
  data-customer-token={customerToken ?? undefined}
/>
```

- The token is valid for 1 day by default; pass `{ "expiresIn": seconds }` (5 minutes to 7 days) to change that. Keep it in the session and mint a new one before `expiresAt`. Revoking the API key ends its tokens within 5 minutes.
- Never send the API key to the browser; only the token goes there.
- When a guest signs in, the items they saved on this device join the customer's wishlist on the next page load.
- If the token is expired or invalid, the script carries on as a guest. The `/config` request in the browser's network panel says why.
- The script reads the attributes once. After signing in or out, reload the page, which the Customer Account API sign-in does anyway.

### Sharing and emails

Share links open your wishlist page (`data-wishlist-url`) with `?wl_share=…`, and invite links with `?wl_invite=…`; a `<wl-page>` on that page shows them. Back in stock, price drop and reminder emails link to your shop's primary domain; if your storefront runs on another domain, redirect `/products/{handle}` there.

## The REST API

```text
Browser ──► your storefront server ──► Wishlist REST API
             (holds the API key,        /customers/{id}/…
              knows who the shopper is)  /guests/{uuid}/…
```

1. Create an API key with the `read` and `write` scopes under **Developers → API keys**. Keep it in a server-side secret, such as `WISHLIST_API_KEY`. Never ship it to the browser.
2. On each request, work out who the shopper is on your server, then call the shopper endpoints under `/customers/{customerId}` or `/guests/{guestId}`.
3. Get product titles, images and prices from the Storefront API. The wishlist stores only ids.

### Identify the shopper

The API trusts the shopper id in the path, so it must come from your server, never from a form field or a query string the browser sends. Otherwise anyone could read or change another customer's wishlist.

- **Signed-in customers:** read the customer id from your session, for example from the Customer Account API, and use the number at the end of the GID (`gid://shopify/Customer/7982301` → `7982301`).
- **Guests:** generate a UUID v4 the first time a guest saves, and keep it in an HTTP-only cookie or your session. Use it as `/guests/{guestId}`.
- **Sign-in:** when a guest signs in, call `POST /customers/{customerId}/merge` with `{ "guestId": "…" }`, then forget the guest id. Their items join the customer's lists.

Guest wishlists follow the **Guest wishlists** setting under **Settings → Features**. When it's off, guest writes answer `401 login_required`; ask the shopper to sign in.

### Hydrogen example

A small server module, `app/lib/wishlist.server.ts`:

```ts
const API = "https://wishlist-edge.themivo.com/api/v1";
const GUEST_KEY = "wishlistGuest";

export async function wishlistFetch(env: Env, path: string, init: RequestInit = {}) {
  const response = await fetch(`${API}${path}`, {
    ...init,
    headers: {
      Authorization: `Bearer ${env.WISHLIST_API_KEY}`,
      "Content-Type": "application/json",
      ...init.headers,
    },
  });
  if (!response.ok) {
    const { error } = await response.json();
    throw new Error(`${error.code}: ${error.message}`);
  }
  return response.json();
}

/** The path prefix for the current shopper: /customers/{id} or /guests/{uuid}. */
export async function wishlistShopper(context: AppLoadContext): Promise<string> {
  const { customerAccount, session, env } = context;
  const guestId: string | undefined = session.get(GUEST_KEY);

  if (await customerAccount.isLoggedIn()) {
    const { data } = await customerAccount.query(`#graphql
      query WishlistCustomer { customer { id } }
    `);
    const customerId = data.customer.id.split("/").pop();
    if (guestId) {
      await wishlistFetch(env, `/customers/${customerId}/merge`, {
        method: "POST",
        body: JSON.stringify({ guestId }),
      });
      session.unset(GUEST_KEY);
    }
    return `/customers/${customerId}`;
  }

  if (guestId) return `/guests/${guestId}`;
  const newGuestId = crypto.randomUUID();
  session.set(GUEST_KEY, newGuestId);
  return `/guests/${newGuestId}`;
}
```

The Hydrogen template commits the session when it changes, so the guest id is saved in the session cookie.

A route that shows the wishlist and handles the heart button, `app/routes/wishlist.tsx`:

```ts
export async function loader({ context }: LoaderFunctionArgs) {
  const shopper = await wishlistShopper(context);
  const wishlist = await wishlistFetch(context.env, `${shopper}/wishlist`);
  const ids = [...new Set(wishlist.items.map((i) => `gid://shopify/Product/${i.productId}`))];
  const { nodes } = await context.storefront.query(PRODUCTS_QUERY, { variables: { ids } });
  return { wishlist, products: nodes.filter(Boolean) };
}

export async function action({ request, context }: ActionFunctionArgs) {
  const form = await request.formData();
  const shopper = await wishlistShopper(context);
  const item = {
    productId: String(form.get("productId")),
    variantId: String(form.get("variantId") ?? ""),
  };
  const method = form.get("intent") === "remove" ? "DELETE" : "POST";
  return wishlistFetch(context.env, `${shopper}/items`, { method, body: JSON.stringify(item) });
}

const PRODUCTS_QUERY = `#graphql
  query WishlistProducts($ids: [ID!]!) {
    nodes(ids: $ids) {
      ... on Product { id title handle featuredImage { url altText } priceRange { minVariantPrice { amount currencyCode } } }
    }
  }
`;
```

Products that were deleted or unpublished come back as `null` from `nodes`; skip them.

### Showing the buttons

- **Saved state:** `GET {shopper}/wishlist` returns every saved item as `{ listId, productId, variantId }`. Load it once in your root loader and mark the heart as filled when the product is in `items`. For a single product page, `GET {shopper}/products/{productId}` is enough.
- **Counts:** the header count is the number of distinct `productId` values in `items`.
- **Caching:** the response has an `ETag`. Send it in `If-None-Match` and you get `304` while nothing changed.
- **Hide rules:** `GET /rules` lists the products where the wishlist button is hidden (`hideButton`) and where the price is hidden in the wishlist (`hidePrice`). It changes rarely, so cache it for a few minutes. Saving a `hideButton` product answers `403 forbidden`.

### Lists, sharing and collaborators

These follow the features turned on under **Settings → Features**. When one is off, its endpoints answer `403 feature_disabled`.

- **Multiple lists:** create, rename and delete lists, move items between them, and read each list with `GET {shopper}/lists/{listId}/items`.
- **Sharing:** `POST {shopper}/lists/{listId}/share` returns a `token`. Build a page on your storefront such as `/wishlist/shared/{token}` and load it on your server with `GET /shared/{token}`. The `url` in the response points to the Online Store and isn't useful on a headless site.
- **Collaborators:** `POST /customers/{id}/lists/{listId}/invites` returns a `token` that works for 7 days. Send a link such as `/wishlist/join/{token}`; when the invited customer opens it signed in, call `POST /customers/{theirId}/invites/{token}/accept`. Guests can't invite or join.

### Add to cart and orders

Add wishlist items to the cart with the Storefront API `cartLinesAdd` mutation. Orders from signed-in customers count as wishlist revenue automatically, as described in [Analytics](https://wishlist.themivo.com/docs/analytics). Guest orders aren't counted.

**Move to cart from Save for later.** Remove the item first and add it to the cart only when the remove answers `"changed": true`. Each shop's wishlist makes one change at a time, so when two requests remove the same item, only one gets `true`; the other gets `false` and adds nothing. Adding to the cart first lets two clicks, or two tabs, add the item twice. If the cart refuses the line, save the item again with `POST {shopper}/items`.

```ts
const query = new URLSearchParams({ productId, variantId, listId: savedForLaterListId });
const { changed } = await wishlistFetch(context.env, `${shopper}/items?${query}`, { method: "DELETE" });
if (!changed) return { ok: true }; // another request already moved it

const { userErrors } = await context.cart.addLines([
  { merchandiseId: `gid://shopify/ProductVariant/${variantId}`, quantity },
]);
if (userErrors?.length) {
  await wishlistFetch(context.env, `${shopper}/items`, {
    method: "POST",
    body: JSON.stringify({ productId, variantId, quantity, listId: savedForLaterListId }),
  });
}
```

Send the saved `variantId` exactly, `""` for a product-level item: without it, the remove takes every variant of the product. Read `quantity` from the item (`GET {shopper}/lists`) before removing it. An item saved again counts as newly saved, so its saved date and price reference start over.

### Emails and notifications

Back in stock, price drop, low stock and reminder emails go to signed-in customers, as on the Online Store. Product and buy links in the emails go to your shop's primary domain. If your headless storefront runs on another domain, redirect `/products/{handle}` from the primary domain to it.

## Limits

With the REST API, each shopper can make 60 requests every 10 seconds, and one key 2,000 requests every 10 seconds across all shoppers. Load the wishlist once per page, not once per product card. The storefront script allows 60 requests every 10 seconds for each shopper. See [REST API](https://wishlist.themivo.com/docs/rest-api#rate-limits) for all limits.

## Keeping other systems in sync

To push changes into a CRM or an email tool as they happen, use [outgoing webhooks](https://wishlist.themivo.com/docs/webhooks) rather than polling the API.
