Skip to content

@snizu/storefront

The typed Storefront API client for headless storefronts. No dependencies, built on fetch, so it runs in browsers, Node, Deno, Bun and edge workers.

npmTypeScript7 min read

Install it

Terminal
npm i @snizu/storefront
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

  • publishableKeypk_…required
    The store's publishable key.
  • localestring
    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().
  • countrystring
    The country the shopper buys from (EG): new carts price in its market. Change it with shop.setCountry().
  • apiUrlurl
    Where the API answers. https://api.snizu.com unless you put a proxy of your own in front of it.
  • storage{ get, set, remove }
    Where cart and customer tokens are kept. localStorage in browsers, under snizu:, and memory elsewhere.
  • fetchtypeof fetch
    Another fetch, such as one with caching on a server.
  • publicReadsFetchOptions
    Added to reads that are the same for everyone: the catalog, the store's content and its forms.
  • privateReadsFetchOptions
    Added to reads about one shopper: their cart, account and orders.
  • timeoutMsnumber
    How long one try may take: 15 seconds by default, 0 for no limit.
  • retriesnumber
    How many more tries a call gets when it failed for a passing reason: 2 by default. See Retries.
  • hooks{ onRequest, onResponse }
    Called for every request, for logs, metrics and tracing. onRequest may add headers, such as a traceparent.
  • cancelCheckoutOnEditboolean
    A change to a cart whose payment started cancels that payment first. true by default.
  • secretKey, buyerIpstring
    On a server only: see Many shoppers, one server.

What it covers

  • 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.
  • 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.
  • 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.
  • 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.
  • store
    profile, brand, policies, policy, blogs, blog, articles, article, metaobjects, metaobject, cities for address forms, Saudi National Addresses (addressAt, addressByCode), redirect, loyaltyProgram and contact.
  • stockAlerts
    request an email when a sold-out variant is back.
  • signupForms
    list and submit the store's sign-up forms.
  • analytics
    track views, adds to cart and checkouts. See Analytics.

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

@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.

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

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:

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

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.

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

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.

  • statusnumber
    The HTTP status, or 0 when the API wasn't reached.
  • codestring
    Stable, for your code: cart_completed, validation_failed… When the API wasn't reached: network_error, timeout or aborted. See Errors.
  • messagestring
    A sentence for people.
  • fieldError(name)string | undefined
    What's wrong with one field, for forms.
  • requestIdstring | undefined
    The request's ID, to quote to support.
  • retryAfternumber | undefined
    Seconds the API asked to wait, after a 429 or 503.
  • isTemporary, isAbort, isMissingCartboolean
    Trying again later may work; the request was stopped by its signal; the cart is over.
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

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

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

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

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

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.

Was this page helpful?

Updated 30 Nov 2026