spree-typescript-sdk

Build storefronts and integrations using `@spree/sdk` — the official TypeScript SDK for Spree's API v3 (v5.4+). Covers installation, the resource-builder pattern (`spree.products.list`, `spree.checkout.create`, etc.), Zod schema validation, server-only auth (httpOnly JWTs, never exposing API keys), error handling, typing customizations, and pinning SDK versions to backend Spree releases. Use when integrating Spree into a Next.js / Node.js / TypeScript project.

17 stars

Best use case

spree-typescript-sdk is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Build storefronts and integrations using `@spree/sdk` — the official TypeScript SDK for Spree's API v3 (v5.4+). Covers installation, the resource-builder pattern (`spree.products.list`, `spree.checkout.create`, etc.), Zod schema validation, server-only auth (httpOnly JWTs, never exposing API keys), error handling, typing customizations, and pinning SDK versions to backend Spree releases. Use when integrating Spree into a Next.js / Node.js / TypeScript project.

Teams using spree-typescript-sdk should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/spree-typescript-sdk/SKILL.md --create-dirs "https://raw.githubusercontent.com/OrcaQubits/agentic-commerce-skills-plugins/main/dist/antigravity/spree-commerce/.agent/skills/spree-typescript-sdk/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/spree-typescript-sdk/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How spree-typescript-sdk Compares

Feature / Agentspree-typescript-sdkStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Build storefronts and integrations using `@spree/sdk` — the official TypeScript SDK for Spree's API v3 (v5.4+). Covers installation, the resource-builder pattern (`spree.products.list`, `spree.checkout.create`, etc.), Zod schema validation, server-only auth (httpOnly JWTs, never exposing API keys), error handling, typing customizations, and pinning SDK versions to backend Spree releases. Use when integrating Spree into a Next.js / Node.js / TypeScript project.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# Spree TypeScript SDK (`@spree/sdk`)

## Before writing code

**Fetch live docs**:
1. Fetch https://spreecommerce.org/docs/developer/sdk/quickstart for the SDK's current API surface.
2. Inspect the SDK's source / README on GitHub (likely under https://github.com/spree/sdk or as part of the `storefront` repo) for resource names and parameter shapes.
3. Check the npm registry page for `@spree/sdk` for the current version aligned to your Spree backend release.
4. Read the v5.4 announcement (https://spreecommerce.org/announcing-spree-commerce-5-4/) for the SDK's release context.
5. For the Next.js usage pattern, fetch https://spreecommerce.org/docs/developer/storefront/nextjs/quickstart.

## Conceptual Architecture

### Why an SDK?

Hand-writing API v3 clients works, but `@spree/sdk` gives you:
- **TypeScript types** generated against the same OpenAPI spec the backend ships
- **Zod validation** of responses so runtime drift is caught
- **Resource-builder pattern** (`spree.products.list(...)`) that mirrors the API
- **Auth handling** — token storage, refresh, cookies
- **Idempotency-key** plumbing for safe retries
- **Error mapping** from HTTP responses to typed exceptions

### Installation

```bash
npm install @spree/sdk
# or
pnpm add @spree/sdk
```

Pin to the version matching your backend Spree release:

```json
{ "dependencies": { "@spree/sdk": "5.4.x" } }
```

When upgrading Spree, bump both together.

### Client Initialization

```typescript
import { createSpreeClient } from '@spree/sdk';

const spree = createSpreeClient({
  apiUrl: process.env.SPREE_API_URL!,                         // https://your-spree.com
  publishableKey: process.env.NEXT_PUBLIC_SPREE_PUBLISHABLE_KEY!, // pk_live_…
  // For admin calls (server-side only):
  // adminApiKey: process.env.SPREE_ADMIN_API_KEY,
});
```

(Verify the actual factory name and option shape against the live `@spree/sdk` docs.)

### Resource Builder Pattern

The SDK exposes resources mirroring the API:

```typescript
// Read
const products = await spree.products.list({ limit: 20, expand: ['default_variant', 'images'] });
const product  = await spree.products.find('prod_…', { expand: ['variants'] });
const taxons   = await spree.taxons.list();

// Cart
const cart = await spree.cart.create();
const cart2 = await spree.cart.addItem({ variantId: 'var_…', quantity: 1 });

// Checkout
await spree.checkout.update({ email: 'guest@example.com', shippingAddress: { ... } });
const session = await spree.checkout.createPaymentSession({ paymentMethodId: 'pm_…' });
const order = await spree.checkout.complete();

// Customer
await spree.auth.signIn({ email, password });
const me = await spree.account.find();

// Admin (server-side only)
await spree.admin.orders.update('ord_…', { internalNote: '...' });
```

Method names are illustrative — verify against live SDK docs.

### Zod Schemas

Responses are parsed through Zod schemas:

```typescript
import { ProductSchema } from '@spree/sdk/schemas';

const product = await spree.products.find('prod_…');
// product is fully typed and validated; runtime mismatches throw
```

This catches API shape drift (e.g., your backend is on 5.4.1 but the SDK expects 5.4.3 conventions).

### Server-Only Auth Pattern

**Never expose the admin API key to the browser.** In Next.js:

```typescript
// app/api/account/route.ts (Server Action / Route Handler)
import { cookies } from 'next/headers';
import { createSpreeClient } from '@spree/sdk';

export async function GET() {
  const token = cookies().get('spree_jwt')?.value;
  const spree = createSpreeClient({
    apiUrl: process.env.SPREE_API_URL!,
    publishableKey: process.env.NEXT_PUBLIC_SPREE_PUBLISHABLE_KEY!,
    userToken: token,
  });
  const me = await spree.account.find();
  return Response.json(me);
}
```

User JWTs go in **httpOnly cookies** set server-side. Cart tokens go in httpOnly cookies. Public publishable key (`pk_…`) is fine in browser code (that's its purpose).

### Idempotency Keys

```typescript
const order = await spree.checkout.complete({
  idempotencyKey: crypto.randomUUID(),
});
```

Generate per logical operation; resend on transient failure to avoid double-charging.

### Error Handling

```typescript
import { SpreeError, ValidationError } from '@spree/sdk';

try {
  await spree.cart.addItem({ variantId: 'var_…', quantity: 99 });
} catch (err) {
  if (err instanceof ValidationError) {
    err.fieldErrors;  // { quantity: 'exceeds inventory' }
  } else if (err instanceof SpreeError) {
    err.code;         // e.g. 'invalid_variant'
    err.requestId;    // for support
  }
}
```

### Typing Customizations

If your Spree backend exposes custom Metafields or extension fields, extend the SDK's types via module augmentation:

```typescript
// types/spree.d.ts
declare module '@spree/sdk' {
  interface Product {
    metafields: {
      my_app: {
        launch_date?: string;
        editor_pick?: boolean;
      };
    };
  }
}
```

### Version Pinning

The SDK is generated against a specific OpenAPI spec version. Mismatches cause Zod validation failures. Strategy:
- Pin `@spree/sdk` to the exact backend Spree minor (`5.4.x`).
- Upgrade in lockstep with backend deploys.
- CI: run a smoke test against your staging backend before promoting.

## Implementation Guidance

### Recommended Project Layout (Next.js)

```
src/
├── lib/
│   ├── spree.server.ts    # createSpreeClient with adminApiKey — server-only
│   └── spree.public.ts    # createSpreeClient with publishableKey — safe for browser
├── app/
│   ├── (storefront)/      # public pages
│   └── api/               # Server Actions / Route Handlers
└── types/
    └── spree.d.ts          # type augmentations
```

**Never import `spree.server.ts` from a Client Component** — Next.js will yell, but it's also a credential leak.

### Caching API Responses

Use Next.js `fetch` cache or React `cache()`:

```typescript
import { cache } from 'react';

export const getProducts = cache(async () => {
  return await spree.products.list({ limit: 20 });
});
```

For ISR / revalidate:
```typescript
const products = await spree.products.list({}, { next: { revalidate: 60 } });
```

(Verify whether `@spree/sdk` exposes `fetch` options pass-through.)

### Webhook Verification Sidekick

The SDK may expose webhook signature verification helpers:

```typescript
import { verifyWebhookSignature } from '@spree/sdk/webhooks';

const event = verifyWebhookSignature({
  payload: rawBody,
  signature: request.headers['x-spree-webhook-signature'],
  secret: process.env.SPREE_WEBHOOK_SECRET!,
});
```

Verify in the live SDK docs.

### Pagination

```typescript
let cursor: string | undefined;
do {
  const page = await spree.products.list({ limit: 100, starting_after: cursor });
  for (const product of page.data) { /* process */ }
  cursor = page.has_more ? page.data[page.data.length - 1].id : undefined;
} while (cursor);
```

### Common Pitfalls

- **Importing the admin client from a Client Component** — exposes the admin key.
- **Pinning to `^5.4.0` instead of `5.4.x`** — minor releases can change generated schema shapes.
- **Storing JWT in localStorage** — XSS-vulnerable; use httpOnly cookies.
- **Not awaiting Zod parse errors** — silent stringy responses break runtime.
- **Using the SDK in browser code with admin key** — Next.js' server-only enforcement is your friend; opt into it.
- **Ignoring Idempotency-Key** — duplicate checkouts on retry.

Always verify resource names, method signatures, and option shapes against the live `@spree/sdk` README and the SDK's TypeScript declarations — the SDK is the youngest part of the Spree ecosystem and is iterating fast.

Related Skills

spree-upgrades

17
from OrcaQubits/agentic-commerce-skills-plugins

Upgrade a Spree application — version-to-version migration paths (v4 → v5 is a major rewrite; v5.x → v5.y are simpler), Gemfile pinning strategy, decorator brittleness across versions, deprecated gems to remove (`spree_auth_devise`, `deface`, `spree_backend`), API v2 → v3 migration via `spree_legacy_api_v2`, admin Bootstrap → Tailwind transition, the upgrade guide workflow, and rollback strategy. Use when planning a Spree upgrade or auditing technical debt blocking one.

spree-testing

17
from OrcaQubits/agentic-commerce-skills-plugins

Test Spree applications and extensions with RSpec — `spree_dev_tools` gem (v5.2+) for factories and helpers, FactoryBot patterns (prefer `build` over `create`), Capybara feature specs, controller/request specs, testing decorators and subscribers, dummy app for extension testing, system specs for the Hotwire admin, and CI patterns. Use when writing Spree tests, setting up CI, or refactoring slow specs.

spree-shipping-fulfillment

17
from OrcaQubits/agentic-commerce-skills-plugins

Build and customize Spree's shipping and fulfillment — ShippingMethod, ShippingCategory, Zone/ZoneMember, ShippingRate, the Stock::Estimator service, StockLocation/StockItem/StockMovement, multi-shipment orders, ShippingCalculator classes (FlatRate, FlatPercentItemTotal, PerItem, FlexiRate), shipment state machine, returns (ReturnAuthorization → CustomerReturn → Reimbursement → Refund), and integrating carrier APIs (UPS, FedEx, ShipStation). Use when configuring shipping rules, building fulfillment integrations, or debugging shipping-rate calculations.

spree-setup

17
from OrcaQubits/agentic-commerce-skills-plugins

Bootstrap a new Spree project — `create-spree-app` CLI (v5.2+), `spree-starter` Rails backend, the Next.js storefront repo, `bin/rails g spree:install`, sample data, Docker Compose, and the PostgreSQL + Redis + Sidekiq prerequisites. Use when starting a new Spree project from scratch or onboarding an existing repo.

spree-security

17
from OrcaQubits/agentic-commerce-skills-plugins

Secure a Spree deployment — Rails credentials and env-var hygiene, Devise auth (Spree v5 ships it in-core; `spree_auth_devise` is archived), CanCanCan authorization rules, Doorkeeper OAuth2 scopes, Storefront publishable key vs admin API key, webhook HMAC verification, OWASP Top 10 for Rails (mass assignment, CSRF, SQL injection via Ransack, XSS, IDOR through prefixed IDs), PCI scope (Spree never touches raw cards thanks to gateway tokenization), and multi-store data isolation. Use when auditing a Spree app, hardening a deploy, or addressing a security incident.

spree-promotions

17
from OrcaQubits/agentic-commerce-skills-plugins

Build and customize Spree's promotions engine — Promotion + PromotionRule + PromotionAction + CouponCode + Adjustment, the bundled rules (FirstOrder/ItemTotal/Product/Taxon/User/OneUsePerUser/Country/CustomerGroup/etc.), bundled actions (CreateAdjustment/CreateItemAdjustments/FreeShipping/CreateLineItems), Calculator classes, coupon batches with CSV export, the v5.1+ advanced rule-based engine, and authoring custom rules/actions/calculators. Use when modeling promotions, building discount UIs, or extending the promotions engine.

spree-performance

17
from OrcaQubits/agentic-commerce-skills-plugins

Profile and optimize a Spree application — N+1 queries with bullet/scout, database indexing strategy for Spree's polymorphic associations, Rails fragment + Russian doll caching, ActiveStorage variant pre-generation, Sidekiq queue tuning, MeiliSearch vs Postgres FTS tradeoffs, Puma worker/thread sizing, CDN strategy for catalog pages, asset precompile time, and load testing. Use when Spree is slow, the database is hot, or you're preparing for a traffic spike (Black Friday, launch).

spree-payments

17
from OrcaQubits/agentic-commerce-skills-plugins

Integrate payment gateways with Spree — PaymentMethod model, the v5.4+ PaymentSession provider-agnostic checkout flow, Stripe via `spree_stripe` (Apple/Google Pay, Link, Connect for marketplaces), Adyen via `spree_adyen`, PayPal via `spree_paypal_checkout`, StoreCredit / GiftCard as payment methods, refunds, payment state machine, and authoring a custom gateway. Use when wiring a payment integration, handling webhooks from a gateway, or debugging payment-state issues.

spree-multi-store

17
from OrcaQubits/agentic-commerce-skills-plugins

Configure Spree for multi-store and multi-region commerce — one Rails install running many `Store` records, the v5.4+ `Market` model (currency + locale + payment methods + shipping per region), what's shared vs per-store (products+inventory+customers shared; orders+payments+themes per-store), the Marketplace module (Enterprise — vendors/commission/payouts via Stripe Connect), and the Multi-tenant SaaS model. Use when planning a multi-brand or multi-region Spree deployment.

spree-legacy-api-v2

17
from OrcaQubits/agentic-commerce-skills-plugins

Work with Spree's legacy v2 APIs — JSON:API-style Storefront API at `/api/v2/storefront/*` and Platform API at `/api/v2/platform/*`, Doorkeeper OAuth2 (password grant for storefront, client_credentials + admin scope for platform), the `spree_legacy_api_v2` gem (required in v5+ for backward compatibility), and migration patterns to API v3. Use when maintaining a v2 client during a migration window, integrating an older partner system, or deciding when to cut over to v3.

spree-i18n

17
from OrcaQubits/agentic-commerce-skills-plugins

Localize a Spree application — the `spree_i18n` gem with 60+ locale packs, the v5.4+ Translations Center for product/CMS content (CSV import/export), Rails i18n basics applied to Spree (translation files, locale switching, pluralization, interpolation), per-Market locale routing in the headless storefront, RTL languages, and translating extensions. Use when localizing a Spree store, adding a new locale, or building i18n-aware extensions.

spree-headless-storefront

17
from OrcaQubits/agentic-commerce-skills-plugins

Build with Spree's headless Next.js storefront — the official `spree/storefront` repo (Next.js 16 App Router with Server Actions and Turbopack, React 19 Server Components, Tailwind CSS 4, TypeScript 5, `@spree/sdk`, Sentry), server-only auth (httpOnly JWT cookies + publishable key), MeiliSearch faceted catalog, one-page checkout with Apple/Google Pay/Klarna/Affirm/SEPA, multi-region market routing, GA4 + JSON-LD SEO, and Vercel/Docker deployment. Use when forking or customizing the storefront, or evaluating headless adoption.