@puddle/storefront
v3.2.0
Published
TypeScript SDK for the Puddle Storefront API.
Maintainers
Readme
@puddle/storefront
🇿🇦 Puddle is upgrading the South African headless e-commerce landscape! The waitlist is available at puddle.co.za.
The official TypeScript SDK for the Puddle Storefront API. Built with full type safety and modern web standards.
Installation
npm install @puddle/storefrontInitialization
Initialize the Storefront API client with your storefrontPublicKey (or apiKey). The key is sent as Authorization: Bearer <key> on every request.
import { PuddleStorefrontApi } from "@puddle/storefront";
const storefront = new PuddleStorefrontApi({
storefrontPublicKey: "pk_storefront_test_...",
// Required for server-side requests when Origin/Referer headers are not present:
storefrontHost: "shop.example.com",
});Headers & Cookies
The Storefront API uses four main request headers:
| Header | Option | Notes |
| --- | --- | --- |
| Authorization | storefrontPublicKey or apiKey | Sent as Bearer <key> on every request. |
| x-puddle-storefront-host | storefrontHost | Required on server-side requests when Origin / Referer are absent. |
| Cookie | cookies or cookie | Forwards customer session (customer_session_<storeId>) and guest cart (guest-id-<storeId>) cookies when proxying requests from a server. |
| Content-Type | (automatic) | application/json is sent automatically on all POST, PUT, and PATCH requests — including bodyless endpoints such as accounts.auth.signOut(), cart.migrate(), and cart.checkout(). |
You can also pass any additional default headers via headers (plain object, Headers instance, or [key, value][] tuples):
const storefront = new PuddleStorefrontApi({
storefrontPublicKey: "pk_storefront_test_...",
storefrontHost: "shop.example.com",
headers: {
"accept-language": "en-ZA",
},
});For browser-direct requests that rely on cross-origin cookies, pass credentials: "include":
const storefront = new PuddleStorefrontApi({
storefrontPublicKey: "pk_storefront_test_...",
credentials: "include",
});Proxying Storefront Requests (Forwarding Cookies)
When proxying storefront API requests through your own server (e.g. Next.js Route Handlers, Server Components, Remix, Fastify, or Express), keep a shared base client with your storefrontPublicKey and storefrontHost, then create a lightweight per-request scoped client with withCookies, withHeaders, or withOptions. Scoping never mutates the shared instance, so cookies cannot leak between concurrent shoppers.
import {
PuddleStorefrontApi,
getSetCookieHeaders,
} from "@puddle/storefront";
const storefront = new PuddleStorefrontApi({
storefrontPublicKey: process.env.PUDDLE_STOREFRONT_KEY!,
storefrontHost: "shop.example.com",
});
export async function POST(request: Request) {
// Forward incoming shopper cookies (customer session, guest ID, etc.)
const client = storefront.withCookies(request.headers.get("cookie"));
const { data, response } = await client.accounts.auth.signOut({
throwOnError: true,
});
// Forward any Set-Cookie headers from Puddle back to the browser
const headers = new Headers({ "content-type": "application/json" });
for (const setCookie of getSetCookieHeaders(response)) {
headers.append("set-cookie", setCookie);
}
return new Response(JSON.stringify(data), { headers });
}cookies / withCookies(...) accepts:
- A raw
Cookieheader string (e.g.request.headers.get("cookie")) - A key/value object (e.g.
{ "guest-id-...": "...", "customer_session_...": "..." }) - An array of
{ name, value }entries (e.g. Next.js(await cookies()).getAll()) nullto explicitly clear any inheritedCookieheader
You can also pass headers per request in the options argument of any method, or build a Headers instance directly with createStorefrontHeaders({ apiKey, storefrontHost, cookies, headers }).
Usage Examples
The SDK is grouped by top-level resources like accounts, cart, collections, products, content, and wishlist.
Here are some common examples of how to use it:
Get the current customer
const { data: customer } = await storefront.accounts.get({
throwOnError: true,
});
console.log(customer);Update the current customer
const { data } = await storefront.accounts.update({
body: {
firstName: "Jane",
lastName: "Doe",
phone: "+27123456789",
},
throwOnError: true,
});Browse, filter, and search products
GET /products (SDK: storefront.products.list(...)) is the unified catalog endpoint for browsing, collection listings, trending products, text search, filtering, sorting, pagination, and facet counts. When a customer session cookie is forwarded, audience-scoped product visibility and promotions are applied automatically.
// Trending products
const { data: trending } = await storefront.products.list({
sort: "TRENDING",
perPage: 12,
throwOnError: true,
});
// Collection products with filters & facets
const { data: collectionPage } = await storefront.products.list({
collection: "black-friday",
tags: ["tea"],
inStock: "true",
sort: "PRICE_ASC",
page: 1,
perPage: 24,
facets: ["tags", "options", "price"],
throwOnError: true,
});
// collectionPage.hits, collectionPage.total, collectionPage.facets, collectionPage.priceRange
// Text search
const { data: searchResults } = await storefront.products.list({
q: "rooibos",
sort: "RELEVANCE",
perPage: 24,
throwOnError: true,
});Get product recommendations (lazy-loadable)
GET /recommendations (SDK: storefront.recommendations.get(...)) returns personalized, audience-safe product recommendations combining behavioral co-occurrence (orders + views), semantic similarity, and multi-signal trending. For signed-in customers it automatically incorporates order history, cart, and wishlist (and for guests, their guest cart).
// On a product detail page
const { data: pdpRecs } = await storefront.recommendations.get({
context: "pdp",
productSlug: "classic-t-shirt",
limit: 8,
throwOnError: true,
});
// pdpRecs.hits, pdpRecs.strategy ("hybrid" | "behavioral" | "semantic" | "trending")
// On the homepage or cart drawer (with optional client-tracked recently viewed slugs)
const { data: homeRecs } = await storefront.recommendations.get({
context: "home",
recentlyViewedSlugs: ["classic-t-shirt", "linen-shorts"],
limit: 8,
throwOnError: true,
});Get a product (with redirects)
GET /product/{slug} (SDK: storefront.products.get({ slug })) returns one of:
{ type: "product", product: ... }for a current product visible to the shopper (including any audience-scopedpromotionPreview).{ type: "redirect", slug: "new-slug", path: "/products/new-slug", statusCode: 301 }when the merchant chose to redirect the old URL. Useslugto construct your storefront's product URL and issue a permanent redirect, preserving query parameters.{ type: "not_found" }for an unknown slug, an unpublished/deleted target, or an audience-restricted product the shopper is not eligible to view.
Puddle Sites handles redirects automatically. Redirects are scoped to the store, skip intermediate slugs after repeated renames, and never override a current product.
Get the current cart
const { data: cart } = await storefront.cart.get({
throwOnError: true,
});Add an item to the cart
const { data: updatedCart } = await storefront.cart.add({
body: {
productId: "product_123",
productVariantId: "variant_123",
quantity: 1,
},
throwOnError: true,
});Request an OTP
await storefront.accounts.authRequestOtp({
body: {
email: "[email protected]",
},
throwOnError: true,
});Error Handling
By default, the SDK returns a response object containing data and error. We highly recommend using the throwOnError: true option to automatically throw exceptions for non-2xx HTTP responses, which makes integration much simpler in modern frameworks.
try {
const { data } = await storefront.cart.add({
body: { productId: "invalid_123", quantity: 1 },
throwOnError: true,
});
} catch (error) {
console.error("Failed to add to cart:", error);
}