npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@puddle/storefront

v3.2.0

Published

TypeScript SDK for the Puddle Storefront API.

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/storefront

Initialization

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 Cookie header 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())
  • null to explicitly clear any inherited Cookie header

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-scoped promotionPreview).
  • { type: "redirect", slug: "new-slug", path: "/products/new-slug", statusCode: 301 } when the merchant chose to redirect the old URL. Use slug to 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);
}