@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.
Install it
npm i @snizu/storefrontimport { 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_…requiredThe store's publishable key.localestringThe 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 withshop.setLocale().countrystringThe country the shopper buys from (EG): new carts price in its market. Change it withshop.setCountry().apiUrlurlWhere the API answers.https://api.snizu.comunless you put a proxy of your own in front of it.storage{ get, set, remove }Where cart and customer tokens are kept.localStoragein browsers, undersnizu:, and memory elsewhere.fetchtypeof fetchAnotherfetch, such as one with caching on a server.publicReadsFetchOptionsAdded to reads that are the same for everyone: the catalog, the store's content and its forms.privateReadsFetchOptionsAdded to reads about one shopper: their cart, account and orders.timeoutMsnumberHow long one try may take: 15 seconds by default,0for no limit.retriesnumberHow 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.onRequestmay add headers, such as atraceparent.cancelCheckoutOnEditbooleanA change to a cart whose payment started cancels that payment first.trueby default.secretKey, buyerIpstringOn a server only: see Many shoppers, one server.
What it covers
catalogproducts,product,collections,collection,collectionProducts,searchwith filters and facets,suggestionsas someone types,recommendations(related or add-ons),availabilityof variants,sellingPlansfor subscribe and save, andbookableTimesof a service.cartget,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,detachCustomerandforget, and for a checkout of your ownstartCheckout,confirmCheckout,sendCodCodeandverifyCodCode. See Carts and checkout.customerSign-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.orderStatusAn order by the token in its link, no account needed:get,confirm,cancel,sendReceiptfor a transfer, andfinda token by order number and email or phone.storeprofile,brand,policies,policy,blogs,blog,articles,article,metaobjects,metaobject,citiesfor address forms, Saudi National Addresses (addressAt,addressByCode),redirect,loyaltyProgramandcontact.stockAlertsrequestan email when a sold-out variant is back.signupFormslistandsubmitthe store's sign-up forms.analyticstrackviews, 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.
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:
// 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.
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.
statusnumberThe HTTP status, or 0 when the API wasn't reached.codestringStable, for your code:cart_completed,validation_failed… When the API wasn't reached:network_error,timeoutoraborted. See Errors.messagestringA sentence for people.fieldError(name)string | undefinedWhat's wrong with one field, for forms.requestIdstring | undefinedThe request's ID, to quote to support.retryAfternumber | undefinedSeconds the API asked to wait, after a 429 or 503.isTemporary, isAbort, isMissingCartbooleanTrying again later may work; the request was stopped by its signal; the cart is over.
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:
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