# @snizu/storefront

Source: https://snizu.dev/docs/storefronts/storefront-client

## Install it [#install-it]

```sh title="Terminal"
npm i @snizu/storefront
```

```ts title="shop.ts"
import { createStorefront, formatMoney } from "@snizu/storefront";

const shop = createStorefront({
  publishableKey: "pk_…", // Admin → Settings → API keys
  locale: "ar",
  country: "EG",
});

const { data: products } = await shop.catalog.products({ limit: 12 });
const product = await shop.catalog.product(products[0].handle);

// The first add starts a cart, remembered in localStorage (in memory on a server).
const cart = await shop.cart.add({ productId: product.id, variantId: product.variants[0].id });
formatMoney(cart.total, "ar");

// Pay on the store's hosted checkout.
location.href = shop.cart.checkoutUrl()!;
```

A publishable key is safe in a browser: that's what it's for. Never put a secret key in one; the client refuses it there.

## Options [#options]

<Fields>
<Field name="publishableKey" type="pk_…" required>
The store's publishable key.
</Field>

<Field name="locale" type="string">
The shopper's language (`ar`, `en`): content in it where the store publishes it, and the language of new carts and accounts. The store's default when absent. Change it with `shop.setLocale()`.
</Field>

<Field name="country" type="string">
The country the shopper buys from (`EG`): new carts price in its market. Change it with `shop.setCountry()`.
</Field>

<Field name="apiUrl" type="url">
Where the API answers. `https://api.snizu.com` unless you put a proxy of your own in front of it.
</Field>

<Field name="storage" type="{ get, set, remove }">
Where cart and customer tokens are kept. `localStorage` in browsers, under `snizu:`, and memory elsewhere.
</Field>

<Field name="fetch" type="typeof fetch">
Another `fetch`, such as one with caching on a server.
</Field>

<Field name="publicReads" type="FetchOptions">
Added to reads that are the same for everyone: the catalog, the store's content and its forms.
</Field>

<Field name="privateReads" type="FetchOptions">
Added to reads about one shopper: their cart, account and orders.
</Field>

<Field name="timeoutMs" type="number">
How long one try may take: 15 seconds by default, `0` for no limit.
</Field>

<Field name="retries" type="number">
How many more tries a call gets when it failed for a passing reason: 2 by default. See [Retries](#retries).
</Field>

<Field name="hooks" type="{ onRequest, onResponse }">
Called for every request, for logs, metrics and tracing. `onRequest` may add headers, such as a `traceparent`.
</Field>

<Field name="cancelCheckoutOnEdit" type="boolean">
A change to a cart whose payment started cancels that payment first. `true` by default.
</Field>

<Field name="secretKey, buyerIp" type="string">
On a server only: see [Many shoppers, one server](#many-shoppers-one-server).
</Field>
</Fields>

## What it covers [#what-it-covers]

<Fields>
<Field name="catalog">
`products`, `product`, `collections`, `collection`, `collectionProducts`, `search` with filters and facets, `suggestions` as someone types, `recommendations` (related or add-ons), `availability` of variants, `sellingPlans` for subscribe and save, and `bookableTimes` of a service.
</Field>

<Field name="cart">
`get`, `add`, `update`, `remove`, discount codes, gift cards, store credit, note, checkout fields, referral, country, buyer, addresses, delivery option and day, payment method, business details, gift card details, `requestQuote`, `recover`, `checkoutUrl`, `order`, `cancelCheckout`, `detachCustomer` and `forget`, and for a checkout of your own `startCheckout`, `confirmCheckout`, `sendCodCode` and `verifyCodCode`. See [Carts and checkout](/docs/storefronts/carts-and-checkout).
</Field>

<Field name="customer">
Sign-up, sign-in with a password or a code by email, SMS or WhatsApp, the account, addresses, orders and tracking, downloads, buying again, subscriptions, bookings, the wishlist and sharing it, loyalty points and the shopper's own fields. See [Customer accounts](/docs/storefronts/customer-accounts).
</Field>

<Field name="orderStatus">
An order by the token in its link, no account needed: `get`, `confirm`, `cancel`, `sendReceipt` for a transfer, and `find` a token by order number and email or phone.
</Field>

<Field name="store">
`profile`, `brand`, `policies`, `policy`, `blogs`, `blog`, `articles`, `article`, `metaobjects`, `metaobject`, `cities` for address forms, Saudi National Addresses (`addressAt`, `addressByCode`), `redirect`, `loyaltyProgram` and `contact`.
</Field>

<Field name="stockAlerts">
`request` an email when a sold-out variant is back.
</Field>

<Field name="signupForms">
`list` and `submit` the store's sign-up forms.
</Field>

<Field name="analytics">
`track` views, adds to cart and checkouts. See [Analytics](/docs/storefronts/analytics).
</Field>
</Fields>

Lists that page answer `{ data, page }`: pass `page.next_cursor` back as `cursor` for the next page. Search pages by number (`page`, 1–50), since its results are ranked as a whole. Every read takes an `AbortSignal`.

`findVariant(product, { Size: "M", Colour: "Sand" })` finds a variant by option name, and `variantOptions(product, variant)` names its values, so nothing depends on the order of `option_values`. Images carry `sizes` for a `srcset`.

## On a server [#on-a-server]

`@snizu/storefront/server` is the same client for anything with a request and cookies: Next.js, Remix, Hono, Astro. A cart and a customer session live in cookies (HTTP-only by default) instead of `localStorage`, so they belong to the request.

```ts title="server.ts"
import { createServerStorefront } from "@snizu/storefront/server";
import { cookies } from "next/headers";

// A shopper's cart and account: never cached, whatever you pass.
const shop = createServerStorefront({ publishableKey, locale, cookies: await cookies() });
const cart = await shop.cart.get();

// What's the same for everyone, cached under tags you can refresh.
const catalog = createServerStorefront({ publishableKey, locale, next: { revalidate: 3600, tags: ["products"] } });
const products = await catalog.catalog.products({ limit: 12 });

// Or for one read:
await shop.with({ next: { tags: [`product:${handle}`] } }).catalog.product(handle);
```

Make a new client for each request. Where cookies can't change, as in a server component, a change lasts for that request: make it in a server action or a route handler to keep it.

### One cart for the server and the browser [#one-cart-for-the-server-and-the-browser]

A server-rendered shop that also changes the cart in the browser, such as a cart drawer with `@snizu/react`, needs both to read the same tokens. Keep them in cookies the page can read, on both sides:

```ts title="shop.ts"
// On the server: server components, actions and route handlers.
createServerStorefront({ publishableKey, cookies: await cookies(), cookieOptions: { httpOnly: false } });

// In the browser.
import { browserCookieStorage } from "@snizu/storefront";
createStorefront({ publishableKey, storage: browserCookieStorage() });
```

Both write the same cookies in the same format, whatever the framework's cookie jar does to values. The tokens are then as readable by the page's scripts as `localStorage` would make them.

### Many shoppers, one server [#many-shoppers-one-server]

Every shopper's calls leave from your server, so to the API they all come from one address and share its allowance. Give the server client one of the store's secret keys, made with no permissions, and the shopper's address: calls about that shopper then carry it, and each shopper gets their own allowance. Reads that are the same for everyone don't carry it, so they stay cached.

```ts title="server.ts"
createServerStorefront({ publishableKey, secretKey: process.env.SNIZU_SECRET_KEY, buyerIp, cookies });
```

## Errors [#errors]

Everything that goes wrong throws a `StorefrontError` with the API's problem details. Messages are in the shopper's language: the client sends `Accept-Language` from `locale`, and the API answers in Arabic for `ar`.

<Fields>
<Field name="status" type="number">
The HTTP status, or 0 when the API wasn't reached.
</Field>

<Field name="code" type="string">
Stable, for your code: `cart_completed`, `validation_failed`… When the API wasn't reached: `network_error`, `timeout` or `aborted`. See [Errors](/reference/errors).
</Field>

<Field name="message" type="string">
A sentence for people.
</Field>

<Field name="fieldError(name)" type="string | undefined">
What's wrong with one field, for forms.
</Field>

<Field name="requestId" type="string | undefined">
The request's ID, to quote to support.
</Field>

<Field name="retryAfter" type="number | undefined">
Seconds the API asked to wait, after a 429 or 503.
</Field>

<Field name="isTemporary, isAbort, isMissingCart" type="boolean">
Trying again later may work; the request was stopped by its signal; the cart is over.
</Field>
</Fields>

```ts title="sign-up.ts"
import { isStorefrontError } from "@snizu/storefront";

try {
  await shop.customer.signUp({ email, password });
} catch (error) {
  if (isStorefrontError(error)) showError(error.fieldError("email") ?? error.message);
}
```

### Retries [#retries]

A call that failed for a passing reason is tried again, twice by default: a read after a network failure, a timeout, a 429 or a 502–504; a `POST` likewise, since each carries an `Idempotency-Key` and the API answers a repeat with the first answer; any other write only after a 429, which the API refuses before doing anything. A `Retry-After` longer than five seconds isn't waited out: the error carries it.

## Testing your storefront [#testing-your-storefront]

`@snizu/storefront/testing` has a `fetch` that answers like the API from a script, and shapes to answer with:

```ts title="cart.test.ts"
import { cart, cartCreated, fakeApi, problem } from "@snizu/storefront/testing";

const api = fakeApi([{ status: 201, body: cartCreated(cart()) }, problem(409, "cart_completed")]);
const shop = createStorefront({ publishableKey: "pk_test", fetch: api.fetch, storage: memoryStorage() });
await shop.cart.add({ productId: "prod_1", variantId: "var_1" });
```

## Money [#money]

Amounts are in minor units with their currency: `{ amount: 1500, currency: "EGP" }` is 15 EGP. `formatMoney(money, locale)` writes one for people, in the currency's own decimals, and `moneyValue(money)` gives it as a plain decimal for structured data. `formatMoney(null)` is an empty string: a line the store no longer sells has no price.

## API versions [#api-versions]

The client sends the API version it was built for as `shop-api-version` (`API_VERSION`, `2026-10`), and its types are from that version, so upgrading the package is what moves your storefront to a newer one.