Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Simplify `@spree/next` package and move actions back to storefront

Damian Legawiec84515d296c4c
diff --git a/docs/developer/storefront/nextjs/architecture.mdx b/docs/developer/storefront/nextjs/architecture.mdx
index e099c8c925..9ef81ccac4 100644
--- a/docs/developer/storefront/nextjs/architecture.mdx
+++ b/docs/developer/storefront/nextjs/architecture.mdx
@@ -8,14 +8,14 @@ description: Server-first architecture, project structure, and auth flow
The storefront follows a **server-first architecture** where all API calls are made server-side. The Spree API key is never exposed to the browser.
```
-Browser → Server Action → @spree/next → Spree API
- (with httpOnly cookies)
+Browser → Server Action → @spree/sdk → Spree API
+ (with httpOnly cookies via @spree/next helpers)
```
-- **Server Actions** (`src/lib/data/`) — thin wrappers around `@spree/next` data functions
+- **Server Actions** (`src/lib/data/`) — call `@spree/sdk` directly with auth/cookie helpers from `@spree/next`
- **httpOnly Cookies** — auth tokens, cart tokens, and locale are stored securely
- **No Client-Side API Calls** — the Spree API key stays on the server
-- **Auto-Localization** — locale and country are read from cookies automatically by `@spree/next`
+- **Auto-Localization** — locale and country are read from cookies via `getLocaleOptions()`
## Project Structure
@@ -59,7 +59,7 @@ src/
└── lib/
├── analytics/ # GTM integration
├── constants.ts # App constants
- ├── data/ # Server Actions
+ ├── data/ # Server Actions (call @spree/sdk directly)
│ ├── addresses.ts # Address CRUD
│ ├── cart.ts # Cart operations
│ ├── checkout.ts # Checkout flow
@@ -71,8 +71,7 @@ src/
│ ├── orders.ts # Order history
│ ├── payment.ts # Payment processing
│ ├── products.ts # Product queries
- │ ├── store.ts # Store configuration
- │ ├── categories.ts # Categories
+ │ ├── categories.ts # Categories
│ └── utils.ts # Shared helpers (actionResult, withFallback)
└── utils/ # Client utilities
├── address.ts # Address formatting
@@ -85,21 +84,26 @@ src/
## Authentication Flow
1. User submits login form
-2. Server action calls `@spree/next` which authenticates with the Spree API
-3. JWT token is stored in an httpOnly cookie by `@spree/next`
-4. Subsequent requests include the token automatically
+2. Server action calls `@spree/sdk` to authenticate
+3. JWT token is stored in an httpOnly cookie via `@spree/next` cookie helpers
+4. Subsequent requests use `withAuthRefresh()` which reads the token from cookies automatically
5. Token is never accessible to client-side JavaScript
```typescript
// src/lib/data/customer.ts
-import { login as _login, getCustomer as _getCustomer } from '@spree/next'
+import { getClient, withAuthRefresh, setAccessToken, setRefreshToken } from '@spree/next'
export async function login(email: string, password: string) {
- return _login(email, password) // token stored in httpOnly cookie automatically
+ const result = await getClient().auth.login({ email, password })
+ await setAccessToken(result.token)
+ await setRefreshToken(result.refresh_token)
+ return { success: true, user: result.user }
}
export async function getCustomer() {
- return _getCustomer() // reads token from cookie automatically
+ return withAuthRefresh(async (options) => {
+ return getClient().customer.get(options) // reads token from cookie
+ })
}
```
@@ -117,17 +121,17 @@ A middleware (`src/proxy.ts`) uses `createSpreeMiddleware` from `@spree/next` to
## Server Actions
-All data fetching is done through server actions in `src/lib/data/`. These are thin wrappers around `@spree/next` functions — locale and currency are resolved automatically from cookies:
+All data fetching is done through server actions in `src/lib/data/`. These call `@spree/sdk` directly, using `@spree/next` helpers for auth and locale:
```typescript
-// Products
+// Products — use getLocaleOptions() for locale-aware reads
import { getProducts, getProduct, getProductFilters } from '@/lib/data/products'
const products = await getProducts({ limit: 12 })
const product = await getProduct('product-slug')
const filters = await getProductFilters()
-// Cart
+// Cart — use getCartOptions()/requireCartId() for cart operations
import { getCart, addToCart, updateCartItem, removeCartItem } from '@/lib/data/cart'
const cart = await getCart()
@@ -135,14 +139,14 @@ await addToCart('var_xxx', 1)
await updateCartItem('li_xxx', 2)
await removeCartItem('li_xxx')
-// Authentication
+// Authentication — use withAuthRefresh() for authenticated endpoints
import { login, register, logout, getCustomer } from '@/lib/data/customer'
await login('[email protected]', 'password')
const customer = await getCustomer()
await logout()
-// Addresses
+// Addresses — use withAuthRefresh() for customer data
import { getAddresses, createAddress, updateAddress, deleteAddress } from '@/lib/data/addresses'
const addresses = await getAddresses()
diff --git a/docs/developer/storefront/nextjs/customization.mdx b/docs/developer/storefront/nextjs/customization.mdx
index fe8ea10d1a..5ca203f90f 100644
--- a/docs/developer/storefront/nextjs/customization.mdx
+++ b/docs/developer/storefront/nextjs/customization.mdx
@@ -111,7 +111,7 @@ To customize API behavior, modify the server actions in `src/lib/data/`. Each fi
| `gift-cards.ts` | Gift card management |
| `utils.ts` | Shared helpers (error handling, fallbacks) |
-These server actions wrap the `@spree/next` package functions. You can add custom logic, caching strategies, or additional transformations as needed.
+These server actions call `@spree/sdk` directly, using `@spree/next` helpers for auth cookies and locale resolution. You can add custom logic, caching strategies, or additional transformations as needed.
## Adding New Pages
@@ -122,10 +122,10 @@ src/app/[country]/[locale]/(storefront)/your-new-page/page.tsx
```
```typescript
-import { listProducts } from '@spree/next';
+import { getProducts } from '@/lib/data/products';
export default async function YourNewPage() {
- const products = await listProducts({ limit: 6 });
+ const products = await getProducts({ limit: 6 });
return (
<div>
diff --git a/docs/developer/storefront/nextjs/quickstart.mdx b/docs/developer/storefront/nextjs/quickstart.mdx
index 45dc0602bc..8a921cc235 100644
--- a/docs/developer/storefront/nextjs/quickstart.mdx
+++ b/docs/developer/storefront/nextjs/quickstart.mdx
@@ -12,7 +12,7 @@ The [Spree Storefront](https://github.com/spree/storefront) is a production-read
- **Tailwind CSS 4** - Utility-first styling
- **TypeScript 5** - Full type safety
- **[@spree/sdk](https://github.com/spree/spree/tree/main/packages/sdk)** - Official Spree Commerce SDK
-- **[@spree/next](https://github.com/spree/spree/tree/main/packages/next)** - Server actions, caching, and cookie-based auth
+- **[@spree/next](https://github.com/spree/spree/tree/main/packages/next)** - Cookie-based auth, middleware, and webhook helpers
- **Sentry** - Error tracking and performance monitoring
## Features
diff --git a/docs/developer/storefront/nextjs/spree-next-package.mdx b/docs/developer/storefront/nextjs/spree-next-package.mdx
index 12adb0cb97..b6975000cc 100644
--- a/docs/developer/storefront/nextjs/spree-next-package.mdx
+++ b/docs/developer/storefront/nextjs/spree-next-package.mdx
@@ -1,9 +1,11 @@
---
title: "@spree/next Package"
-description: Next.js integration library — server actions, caching, and cookie-based auth
+description: Next.js integration library — cookie-based auth, middleware, and webhook helpers
---
-The `@spree/next` package provides a complete Next.js integration for Spree Commerce with server actions, automatic cookie management, and full TypeScript support.
+The `@spree/next` package provides the server-side plumbing for building a Next.js storefront with `@spree/sdk`: JWT token lifecycle, httpOnly cookie management, locale/country middleware, and webhook verification.
+
+Your storefront calls `@spree/sdk` directly for all API operations. `@spree/next` handles the Next.js-specific concerns — cookies, auth refresh, and middleware — so you don't have to.
## Installation
@@ -42,211 +44,137 @@ initSpreeNext({
});
```
-## Data Functions
+## Architecture
-Plain async functions for reading data in Server Components. Wrap with `"use cache"` in your app for caching.
+`@spree/next` provides four things:
-### Products
+1. **`getClient()`** — singleton `@spree/sdk` Client instance (auto-inits from env vars)
+2. **Auth helpers** — `withAuthRefresh()` for JWT lifecycle, cookie read/write for tokens
+3. **Locale resolution** — `getLocaleOptions()` reads country/locale from cookies
+4. **Framework helpers** — `createSpreeMiddleware()` for URL routing, `createWebhookHandler()` for webhooks
-```typescript
-import { listProducts, getProduct, getProductFilters } from '@spree/next';
+Your storefront's server actions call `@spree/sdk` directly, using these helpers for auth and cookies:
-const products = await listProducts({ limit: 25 });
-const product = await getProduct('spree-tote', { expand: ['variants', 'media'] });
-const filters = await getProductFilters({ category_id: 'ctg_123' });
+```
+Server Action → getClient().products.list(params, localeOptions)
+Server Action → withAuthRefresh(fn) → getClient().customer.get(options)
+Server Action → getCartOptions() → getClient().carts.items.create(...)
```
-### Categories
+## Auth Helpers
-```typescript
-import { listCategories, getCategory, listCategoryProducts } from '@spree/next';
+### `withAuthRefresh(fn)`
-const categories = await listCategories({ depth_eq: 1 });
-const category = await getCategory('clothing/shirts');
-const products = await listCategoryProducts('clothing/shirts', { limit: 12 });
-```
+Wraps an authenticated SDK call with automatic token management:
-### Store & Geography
+1. Reads JWT from cookie
+2. Proactively refreshes if expiring within 5 minutes
+3. Executes your function with `{ token }` options
+4. On 401: refreshes token and retries once
+5. On refresh failure: clears cookies and throws
```typescript
-import { getStore, listCountries, getCountry, listCurrencies, listLocales } from '@spree/next';
+'use server';
-const store = await getStore();
-const countries = await listCountries();
-const usa = await getCountry('US');
-const currencies = await listCurrencies();
-const locales = await listLocales();
-```
+import { getClient, withAuthRefresh } from '@spree/next';
-### Using in Server Components
+export async function getCustomer() {
+ return withAuthRefresh(async (options) => {
+ return getClient().customer.get(options);
+ });
+}
-```typescript
-import { listProducts, listCategories } from '@spree/next';
-
-export default async function ProductsPage() {
- const products = await listProducts({ limit: 12 });
- const categories = await listCategories({ depth_eq: 1 });
-
- return (
- <div>
- {products.data.map((product) => (
- <div key={product.id}>{product.name}</div>
- ))}
- </div>
- );
+export async function listAddresses() {
+ return withAuthRefresh(async (options) => {
+ return getClient().customer.addresses.list(undefined, options);
+ });
}
```
-## Server Actions
+### `getAuthOptions()`
-Server actions handle mutations and auth-dependent reads. They automatically manage cookies for cart tokens and JWT authentication.
+Lower-level helper that returns `{ token }` or `{}` with proactive refresh. Use when you need the token but want to handle errors yourself.
-### Cart
+## Cookie Management
-```typescript
-import { getCart, getOrCreateCart, addItem, updateItem, removeItem, clearCart, associateCart } from '@spree/next';
-
-const cart = await getCart(); // null if no cart
-const cart = await getOrCreateCart(); // creates if needed
-await addItem(variantId, quantity);
-await updateItem(lineItemId, { quantity: 2 });
-await removeItem(lineItemId);
-await clearCart();
-await associateCart(); // link guest cart to logged-in user
-```
-
-### Checkout
-
-Checkout functions use the implicit cart resolved from cookies. No `orderId` is needed.
+All cookie helpers are async (they use Next.js `cookies()` API):
```typescript
import {
- getCheckout,
- updateCheckout,
- selectDeliveryRate,
- applyDiscountCode,
- removeDiscountCode,
- applyGiftCard,
- removeGiftCard,
- complete,
+ // Cart
+ getCartToken, getCartId, setCartCookies, clearCartCookies,
+ getCartOptions, // { spreeToken, token } for cart SDK calls
+ requireCartId, // throws if no cart
+
+ // Auth
+ getAccessToken, setAccessToken, clearAccessToken,
+ getRefreshToken, setRefreshToken, clearRefreshToken,
} from '@spree/next';
-
-const checkout = await getCheckout();
-await updateCheckout({ shipping_address: { ... }, billing_address: { ... } });
-await selectDeliveryRate(fulfillmentId, deliveryRateId);
-await applyDiscountCode('SAVE20');
-await removeDiscountCode('SAVE20');
-await applyGiftCard('GC-ABCD-1234');
-await removeGiftCard('gc_abc123');
-await complete();
```
-### Authentication
+### Cart operations pattern
```typescript
-import { login, register, logout, getCustomer, updateCustomer } from '@spree/next';
-
-await login(email, password);
-await register(email, password, passwordConfirmation);
-await logout();
-const customer = await getCustomer(); // null if not logged in
-await updateCustomer({ first_name: 'John' });
-```
+'use server';
-### Addresses
+import { getClient, getCartOptions, requireCartId } from '@spree/next';
-```typescript
-import { listAddresses, getAddress, createAddress, updateAddress, deleteAddress } from '@spree/next';
-
-const addresses = await listAddresses();
-const address = await getAddress(addressId);
-await createAddress({ first_name: 'John', address1: '123 Main St', ... });
-await updateAddress(addressId, { city: 'Brooklyn' });
-await deleteAddress(addressId);
-```
-
-### Orders
-
-```typescript
-import { listOrders, getOrder } from '@spree/next';
-
-const orders = await listOrders();
-const order = await getOrder(orderId);
+export async function updateCartItem(lineItemId: string, quantity: number) {
+ const options = await getCartOptions();
+ const cartId = await requireCartId();
+ return getClient().carts.items.update(cartId, lineItemId, { quantity }, options);
+}
```
-### Payment Sessions
-
-Payment session functions use the implicit cart. No `orderId` is needed.
+### Auth operations pattern
```typescript
-import {
- createPaymentSession,
- getPaymentSession,
- updatePaymentSession,
- completePaymentSession,
-} from '@spree/next';
-
-const session = await createPaymentSession({ payment_method_id: 'pm_123' });
-
-// Access provider data (e.g., Stripe client secret)
-const clientSecret = session.external_data.client_secret;
-
-const current = await getPaymentSession(sessionId);
-await updatePaymentSession(sessionId, { amount: '50.00' });
-await completePaymentSession(sessionId, { session_result: 'success' });
-```
+'use server';
-### Payment Setup Sessions
+import { getClient, setAccessToken, setRefreshToken, getCartToken, getCartId } from '@spree/next';
-For saving payment methods outside of checkout (e.g., "Add a credit card" in account settings):
+export async function login(email: string, password: string) {
+ const result = await getClient().auth.login({ email, password });
+ await setAccessToken(result.token);
+ await setRefreshToken(result.refresh_token);
-```typescript
-import {
- createPaymentSetupSession,
- getPaymentSetupSession,
- completePaymentSetupSession,
-} from '@spree/next';
+ // Associate guest cart if one exists
+ const cartToken = await getCartToken();
+ const cartId = await getCartId();
+ if (cartToken && cartId) {
+ await getClient().carts.associate(cartId, {
+ token: result.token,
+ spreeToken: cartToken,
+ }).catch(() => {}); // non-fatal
+ }
-const session = await createPaymentSetupSession({ payment_method_id: 'pm_123' });
-const current = await getPaymentSetupSession(sessionId);
-await completePaymentSetupSession(sessionId, { session_result: 'success' });
+ return { success: true, user: result.user };
+}
```
-### Credit Cards & Gift Cards
-
-```typescript
-import { listCreditCards, deleteCreditCard } from '@spree/next';
-import { listGiftCards, getGiftCard } from '@spree/next';
+## Locale Resolution
-const cards = await listCreditCards();
-await deleteCreditCard(cardId);
-
-const giftCards = await listGiftCards();
-const giftCard = await getGiftCard(giftCardId);
-```
-
-## Using Server Actions in Forms
+`getLocaleOptions()` reads country and locale from cookies (set by middleware or explicitly). All data-fetching server actions should use this:
```typescript
-import { addItem, getCart } from '@spree/next';
+'use server';
-export default async function CartPage() {
- const cart = await getCart();
+import { getClient, getLocaleOptions } from '@spree/next';
- async function handleAddItem(formData: FormData) {
- 'use server';
- await addItem(formData.get('variantId') as string, 1);
- }
+export async function getProducts(params?: { limit?: number }) {
+ const options = await getLocaleOptions();
+ return getClient().products.list(params, options);
+}
- return <form action={handleAddItem}>...</form>;
+export async function getCategory(idOrPermalink: string) {
+ const options = await getLocaleOptions();
+ return getClient().categories.get(idOrPermalink, undefined, options);
}
```
-## Localization
-
-### Automatic (recommended)
+## Middleware
-Data functions automatically read locale and country from cookies. Use the included middleware to set cookies based on the URL:
+Handles URL-based country/locale routing. Detects country from cookies, geo headers (Vercel/Cloudflare), or defaults, then redirects to `/{country}/{locale}/...`:
```typescript
// middleware.ts
@@ -262,31 +190,6 @@ export const config = {
};
```
-Then data functions work without any locale arguments:
-
-```typescript
-// Locale/country auto-read from cookies — no options needed
-const products = await listProducts({ limit: 10 });
-const category = await getCategory('clothing/shirts');
-```
-
-Use the `setLocale` server action in country/language switchers:
-
-```typescript
-import { setLocale } from '@spree/next';
-
-await setLocale({ country: 'de', locale: 'de' });
-```
-
-### Manual override
-
-You can still pass locale options explicitly — they override the auto-detected values:
-
-```typescript
-const products = await listProducts({ limit: 10 }, { locale: 'fr', country: 'FR' });
-const category = await getCategory('clothing/shirts', {}, { locale: 'de', country: 'DE' });
-```
-
## Webhooks
Handle Spree webhook events in your Next.js app with `@spree/next/webhooks`:
@@ -331,31 +234,14 @@ For more details, see [Webhooks](/developer/core-concepts/webhooks).
## TypeScript
-All types are re-exported from `@spree/sdk`:
+Import types directly from `@spree/sdk`:
```typescript
import type {
- Product,
- Order,
- LineItem,
- Variant,
- Category,
- Country,
- Currency,
- Locale,
- Address,
- Customer,
- CreditCard,
- GiftCard,
- Fulfillment,
- DeliveryRate,
- Payment,
- PaymentMethod,
- PaymentSession,
- PaymentSetupSession,
- PaginatedResponse,
- ProductFiltersResponse,
- AddressParams,
- SpreeError,
-} from '@spree/next';
+ Product, Order, Cart, LineItem, Variant,
+ Category, Country, Currency, Address, Customer,
+ CreditCard, GiftCard, Fulfillment, DeliveryRate,
+ Payment, PaymentSession, PaginatedResponse,
+ AddressParams, SpreeError,
+} from '@spree/sdk';
```
diff --git a/packages/next/README.md b/packages/next/README.md
index bd05a06d88..ff50401f72 100644
--- a/packages/next/README.md
+++ b/packages/next/README.md
@@ -1,14 +1,14 @@
# @spree/next
-Next.js integration for Spree Commerce — server actions, caching, and cookie-based auth.
+Next.js integration for Spree Commerce — cookie-based auth, middleware, and webhook helpers.
+
+Provides the server-side plumbing for building a Next.js storefront with `@spree/sdk`: JWT token lifecycle (proactive refresh, 401 retry), httpOnly cookie management, locale/country detection middleware, and webhook signature verification.
## Installation
```bash
npm install @spree/next @spree/sdk
# or
-yarn add @spree/next @spree/sdk
-# or
pnpm add @spree/next @spree/sdk
```
@@ -18,273 +18,136 @@ pnpm add @spree/next @spree/sdk
```env
SPREE_API_URL=https://api.mystore.com
-SPREE_API_KEY=your-publishable-api-key
+SPREE_PUBLISHABLE_KEY=your-publishable-api-key
```
The client auto-initializes from these env vars. Alternatively, initialize explicitly:
```typescript
-// lib/storefront.ts
import { initSpreeNext } from '@spree/next';
initSpreeNext({
baseUrl: process.env.SPREE_API_URL!,
- apiKey: process.env.SPREE_API_KEY!,
+ publishableKey: process.env.SPREE_PUBLISHABLE_KEY!,
});
```
-### 2. Fetch data in Server Components
+### 2. Call the SDK directly in your server actions
-```typescript
-import { listProducts, getProduct, listCategories } from '@spree/next';
-
-export default async function ProductsPage() {
- const products = await listProducts({ limit: 12 });
- const categories = await listCategories({ depth_eq: 1 });
-
- return (
- <div>
- {products.data.map((product) => (
- <div key={product.id}>{product.name}</div>
- ))}
- </div>
- );
-}
-```
-
-### 3. Use server actions for mutations
+`@spree/next` provides `getClient()` (the SDK singleton), auth helpers, and cookie management. You write server actions that call the SDK directly:
```typescript
-import { addItem, removeItem, getCart } from '@spree/next';
-
-export default async function CartPage() {
- const cart = await getCart(); // Cart | null
+'use server';
- async function handleAddItem(formData: FormData) {
- 'use server';
- await addItem(formData.get('variantId') as string, 1);
- }
+import { getClient, getLocaleOptions } from '@spree/next';
- return <form action={handleAddItem}>...</form>;
+export async function getProducts(params?: { limit?: number }) {
+ const options = await getLocaleOptions(); // reads country/locale from cookies
+ return getClient().products.list(params, options);
}
```
-## Configuration
-
-```typescript
-import { initSpreeNext } from '@spree/next';
-
-initSpreeNext({
- baseUrl: 'https://api.mystore.com',
- apiKey: 'your-publishable-api-key',
- cartCookieName: '_spree_cart_token', // default
- accessTokenCookieName: '_spree_jwt', // default
- defaultLocale: 'en',
- defaultCurrency: 'USD',
-});
-```
-
-## Data Functions
-
-Plain async functions for reading data in Server Components. Wrap with `"use cache"` in your app for caching.
-
-### Products
-
-```typescript
-import { listProducts, getProduct, getProductFilters } from '@spree/next';
-
-const products = await listProducts({ limit: 25, expand: ['variants', 'media'] });
-const product = await getProduct('spree-tote');
-const filters = await getProductFilters({ category_id: 'ctg_123' });
-```
-
-### Categories
+### 3. Use auth helpers for authenticated endpoints
```typescript
-import { listCategories, getCategory, listCategoryProducts } from '@spree/next';
-
-const categories = await listCategories({ depth_eq: 1 });
-const category = await getCategory('clothing/shirts');
-const products = await listCategoryProducts('clothing/shirts', { limit: 12 });
-```
+'use server';
-### Store & Geography
+import { getClient, withAuthRefresh } from '@spree/next';
-```typescript
-import { getStore, listCountries, getCountry } from '@spree/next';
-
-const store = await getStore();
-const countries = await listCountries();
-const usa = await getCountry('US');
+export async function getAddresses() {
+ return withAuthRefresh(async (options) => {
+ return getClient().customer.addresses.list(undefined, options);
+ });
+}
```
-## Server Actions
+`withAuthRefresh` reads the JWT from cookies, proactively refreshes if near expiry, and retries once on 401.
-Server actions handle mutations and auth-dependent reads. They automatically manage cookies for cart tokens and JWT authentication.
-
-### Cart
+### 4. Use cookie helpers for cart operations
```typescript
-import { getCart, getOrCreateCart, addItem, updateItem, removeItem, clearCart } from '@spree/next';
-
-const cart = await getCart(); // Cart | null
-const cart = await getOrCreateCart(); // Cart
-await addItem(variantId, quantity, { gift_message: 'Happy Birthday!' }); // Cart
-await updateItem(lineItemId, { quantity: 3 }); // Cart
-await updateItem(lineItemId, { metadata: { engraving: 'J.D.' } }); // Cart
-await removeItem(lineItemId); // Cart
-await clearCart();
-```
-
-### Checkout
+'use server';
-All checkout functions operate on the current cart implicitly (via the cart cookie).
+import { getClient, getCartOptions, requireCartId } from '@spree/next';
-```typescript
-import {
- getCheckout,
- updateCheckout,
- selectDeliveryRate,
- applyDiscountCode,
- removeDiscountCode,
- applyGiftCard,
- removeGiftCard,
- complete,
-} from '@spree/next';
-
-const checkout = await getCheckout();
-// Fulfillments are included in the checkout/cart response:
-// checkout.fulfillments
-await updateCheckout({ shipping_address: { ... }, billing_address: { ... } });
-await selectDeliveryRate(fulfillmentId, rateId);
-await applyDiscountCode('SAVE20');
-await removeDiscountCode('SAVE20');
-await applyGiftCard('GC-ABCD-1234');
-await removeGiftCard('gc_abc123'); // ID from cart.gift_card.id
-await complete();
+export async function addToCart(variantId: string, quantity: number) {
+ const options = await getCartOptions(); // { spreeToken, token } from cookies
+ const cartId = await requireCartId();
+ return getClient().carts.items.create(cartId, { variant_id: variantId, quantity }, options);
+}
```
-### Authentication
-
-```typescript
-import { login, register, logout, getCustomer, updateCustomer } from '@spree/next';
-
-await login(email, password);
-await register({ email, password, password_confirmation, first_name, last_name, phone, accepts_email_marketing });
-await logout();
-const customer = await getCustomer();
-await updateCustomer({ first_name: 'John' });
-```
+## API Reference
-### Password Reset
+### Configuration
```typescript
-import { requestPasswordReset, resetPassword } from '@spree/next';
+import { initSpreeNext, getClient, getConfig } from '@spree/next';
-// Request a password reset email — returns { message: string }
-await requestPasswordReset(email);
-
-// With redirect URL (validated against store's allowed origins)
-await requestPasswordReset(email, 'https://myshop.com/reset-password');
-
-// Reset password and auto-login — returns { success: boolean; error?: string }
-await resetPassword(token, password, password_confirmation);
-```
-
-### Addresses
-
-```typescript
-import { listAddresses, getAddress, createAddress, updateAddress, deleteAddress } from '@spree/next';
+// Initialize (or let it auto-init from env vars)
+initSpreeNext({
+ baseUrl: 'https://api.mystore.com',
+ publishableKey: 'pk_xxx',
+ cartCookieName: '_spree_cart_token', // default
+ accessTokenCookieName: '_spree_jwt', // default
+ defaultLocale: 'en',
+ defaultCurrency: 'USD',
+ defaultCountry: 'US',
+});
-const addresses = await listAddresses();
-const address = await getAddress(addressId);
-await createAddress({ first_name: 'John', address1: '123 Main St', ... });
-await updateAddress(addressId, { city: 'Brooklyn' });
-await deleteAddress(addressId);
+// Get the @spree/sdk Client instance
+const client = getClient();
```
-### Orders
+### Auth Helpers
```typescript
-import { listOrders, getOrder } from '@spree/next';
+import { withAuthRefresh, getAuthOptions } from '@spree/next';
-const orders = await listOrders();
-const order = await getOrder(orderId);
-```
-
-### Payments (Manual/Offline)
-
-All payment functions operate on the current cart implicitly (via the cart cookie).
-
-```typescript
-import { createPayment } from '@spree/next';
-
-// Create a payment for a non-session payment method
-// (e.g. Check, Cash on Delivery, Bank Transfer, Purchase Order)
-await createPayment({
- payment_method_id: 'pm_123',
- amount: '99.99', // Optional, defaults to order total minus store credits
- metadata: { // Optional, write-only metadata
- purchase_order_number: 'PO-12345',
- },
+// Wrap any authenticated SDK call — handles proactive refresh + 401 retry
+const customer = await withAuthRefresh(async (options) => {
+ return getClient().customer.get(options);
});
-```
-### Payment Sessions (Stripe, Adyen, PayPal, etc.)
+// Or get auth options manually
+const options = await getAuthOptions(); // { token: 'jwt...' } or {}
+```
-All payment session functions operate on the current cart implicitly (via the cart cookie).
+### Cookie Management
```typescript
import {
- createPaymentSession,
- getPaymentSession,
- updatePaymentSession,
- completePaymentSession,
+ // Cart cookies
+ getCartToken, // guest cart order token
+ getCartId, // cart prefixed ID
+ setCartCookies, // set both cart ID + token
+ clearCartCookies, // clear cart cookies
+ getCartOptions, // { spreeToken, token } for SDK calls
+ requireCartId, // throws if no cart found
+
+ // Auth cookies
+ getAccessToken, // JWT access token
+ setAccessToken,
+ clearAccessToken,
+ getRefreshToken, // refresh token
+ setRefreshToken,
+ clearRefreshToken,
} from '@spree/next';
-
-// Create a payment session (initializes provider-specific session)
-const session = await createPaymentSession({ payment_method_id: 'pm_123' });
-
-// Access provider data (e.g., Stripe client secret)
-const clientSecret = session.external_data.client_secret;
-
-// Get a payment session
-const session = await getPaymentSession(sessionId);
-
-// Update a payment session
-await updatePaymentSession(sessionId, { amount: '50.00' });
-
-// Complete a payment session (confirms payment with provider)
-await completePaymentSession(sessionId, { session_result: 'success' });
-```
-
-### Store Credits
-
-```typescript
-import { listStoreCredits, getStoreCredit } from '@spree/next';
-
-const credits = await listStoreCredits();
-const credit = await getStoreCredit(creditId);
```
-### Credit Cards & Gift Cards
+### Locale Resolution
```typescript
-import { listCreditCards, deleteCreditCard } from '@spree/next';
-import { listGiftCards, getGiftCard } from '@spree/next';
+import { getLocaleOptions } from '@spree/next';
-const cards = await listCreditCards();
-await deleteCreditCard(cardId);
-
-const giftCards = await listGiftCards();
-const giftCard = await getGiftCard(giftCardId);
+// Reads country/locale from cookies, falls back to config defaults
+const options = await getLocaleOptions();
+// { locale: 'en', country: 'us' }
```
-## Localization
-
-### Automatic (recommended)
+### Middleware
-Data functions automatically read locale and country from cookies. Use the included middleware to handle URL-based routing and cookie persistence:
+Handles URL-based country/locale routing with automatic detection:
```typescript
// middleware.ts
@@ -300,32 +163,11 @@ export const config = {
};
```
-Data functions work without any locale arguments:
+Detection order: cookie → geo headers (Vercel/Cloudflare) → default.
-```typescript
-const products = await listProducts({ limit: 10 });
-const category = await getCategory('clothing/shirts');
-```
+### Webhooks
-Use the `setLocale` server action in country/language switchers:
-
-```typescript
-import { setLocale } from '@spree/next';
-
-await setLocale({ country: 'de', locale: 'de' });
-```
-
-### Manual override
-
-You can still pass locale options explicitly — they override auto-detected values:
-
-```typescript
-const products = await listProducts({ limit: 10 }, { locale: 'fr', country: 'FR' });
-```
-
-## Webhooks
-
-Handle Spree webhook events in your Next.js app with a single function:
+Handle Spree webhook events with signature verification:
```typescript
// src/app/api/webhooks/spree/route.ts
@@ -335,51 +177,28 @@ export const POST = createWebhookHandler({
secret: process.env.SPREE_WEBHOOK_SECRET!,
handlers: {
'order.completed': async (event) => {
- const order = event.data; // typed as the data you pass
- await sendOrderConfirmationEmail(order);
+ await sendOrderConfirmationEmail(event.data);
},
'order.canceled': async (event) => {
await sendCancellationEmail(event.data);
},
- 'shipment.shipped': async (event) => {
- await sendShippingNotification(event.data);
- },
},
});
```
-`createWebhookHandler` handles:
+Features:
- HMAC-SHA256 signature verification (via `@spree/sdk/webhooks`)
- Replay protection (rejects timestamps older than 5 minutes)
- Event routing to your handlers by event name
-- Returns 200 immediately, processes handlers async (Spree won't time out)
+- Supports `waitUntil` for Vercel/Cloudflare serverless execution
- Unhandled events return 200 with `{ handled: false }` (no retries)
-### Setup
-
-1. Install [cloudflared](https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/) for local development: `brew install cloudflared`
-2. Expose your storefront: `cloudflared tunnel --url http://localhost:3001`
-3. Create a webhook endpoint in **Spree Admin → Settings → Developers → Webhooks** pointing to your tunnel URL + `/api/webhooks/spree`
-4. Add `SPREE_WEBHOOK_SECRET` to your `.env.local`
-
-For framework-agnostic webhook verification (Express, Hono, etc.), use `@spree/sdk/webhooks` directly — see the [`@spree/sdk` README](../sdk/README.md#webhooks).
-
## TypeScript
-All types are re-exported from `@spree/sdk` for convenience:
+Import types directly from `@spree/sdk`:
```typescript
-import type {
- Cart,
- StoreProduct,
- StoreOrder,
- StoreLineItem,
- StorePaymentSession,
- StoreCategory,
- UpdateCartParams,
- PaginatedResponse,
- SpreeError,
-} from '@spree/next';
+import type { Product, Cart, Order, Address, Customer, SpreeError } from '@spree/sdk';
```
## Development
@@ -393,16 +212,6 @@ pnpm test # Run tests
pnpm build # Production build
```
-### Releasing
-
-This package uses [Changesets](https://github.com/changesets/changesets) for version management.
-
-```bash
-npx changeset # Add a changeset after making changes
-npx changeset version # Bump version and update CHANGELOG
-pnpm release # Build and publish to npm
-```
-
## License
MIT
diff --git a/packages/next/package.json b/packages/next/package.json
index 5585119d4f..d4d201ab6d 100644
--- a/packages/next/package.json
+++ b/packages/next/package.json
@@ -1,7 +1,7 @@
{
"name": "@spree/next",
"version": "0.18.0",
- "description": "Next.js integration for Spree Commerce — server actions, caching, and cookie-based auth",
+ "description": "Next.js integration for Spree Commerce — cookie-based auth, middleware, and webhook helpers",
"type": "module",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
diff --git a/packages/next/src/actions/addresses.ts b/packages/next/src/actions/addresses.ts
deleted file mode 100644
index c1a1faca49..0000000000
--- a/packages/next/src/actions/addresses.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-'use server';
-
-import { revalidateTag } from 'next/cache';
-import type { Address, AddressParams } from '@spree/sdk';
-import { withAuthRefresh } from '../auth-helpers';
-import { getClient } from '../config';
-
-/**
- * List the authenticated customer's addresses.
- */
-export async function listAddresses(): Promise<{ data: Address[] }> {
- return withAuthRefresh(async (options) => {
- return getClient().customer.addresses.list(undefined, options);
- });
-}
-
-/**
- * Get a single address by ID.
- */
-export async function getAddress(id: string): Promise<Address> {
- return withAuthRefresh(async (options) => {
- return getClient().customer.addresses.get(id, options);
- });
-}
-
-/**
- * Create a new address for the customer.
- */
-export async function createAddress(params: AddressParams): Promise<Address> {
- const result = await withAuthRefresh(async (options) => {
- return getClient().customer.addresses.create(params, options);
- });
- revalidateTag('addresses');
- return result;
-}
-
-/**
- * Update an existing address.
- */
-export async function updateAddress(
- id: string,
- params: Partial<AddressParams>
-): Promise<Address> {
- const result = await withAuthRefresh(async (options) => {
- return getClient().customer.addresses.update(id, params, options);
- });
- revalidateTag('addresses');
- return result;
-}
-
-/**
- * Delete an address.
- */
-export async function deleteAddress(id: string): Promise<void> {
- await withAuthRefresh(async (options) => {
- return getClient().customer.addresses.delete(id, options);
- });
- revalidateTag('addresses');
-}
diff --git a/packages/next/src/actions/auth.ts b/packages/next/src/actions/auth.ts
deleted file mode 100644
index 969f65589b..0000000000
--- a/packages/next/src/actions/auth.ts
+++ /dev/null
@@ -1,203 +0,0 @@
-'use server';
-
-import { revalidateTag } from 'next/cache';
-import type { Customer } from '@spree/sdk';
-import { getClient } from '../config';
-import { setAccessToken, clearAccessToken, getAccessToken, setRefreshToken, getRefreshToken, clearRefreshToken, getCartToken, getCartId, clearCartCookies } from '../cookies';
-import { withAuthRefresh } from '../auth-helpers';
-
-/**
- * Login with email and password.
- * Automatically associates any guest cart with the authenticated user.
- */
-export async function login(
- email: string,
- password: string
-): Promise<{ success: boolean; user?: { id: string; email: string; first_name?: string | null; last_name?: string | null }; error?: string }> {
- try {
- const result = await getClient().auth.login({ email, password });
- await setAccessToken(result.token);
- await setRefreshToken(result.refresh_token);
-
- // Associate guest cart if one exists
- const cartToken = await getCartToken();
- const cartId = await getCartId();
- if (cartToken && cartId) {
- try {
- await getClient().carts.associate(cartId, {
- token: result.token,
- spreeToken: cartToken,
- });
- } catch {
- // Cart association failure is non-fatal
- }
- }
-
- revalidateTag('customer');
- revalidateTag('cart');
- return { success: true, user: result.user };
- } catch (error) {
- return {
- success: false,
- error: error instanceof Error ? error.message : 'Invalid email or password',
- };
- }
-}
-
-/**
- * Register a new customer account.
- * Automatically associates any guest cart with the new account.
- */
-export async function register(
- params: {
- email: string;
- password: string;
- password_confirmation: string;
- first_name?: string;
- last_name?: string;
- phone?: string;
- accepts_email_marketing?: boolean;
- metadata?: Record<string, unknown>;
- }
-): Promise<{ success: boolean; user?: { id: string; email: string; first_name?: string | null; last_name?: string | null }; error?: string }> {
- try {
- const result = await getClient().customers.create(params);
- await setAccessToken(result.token);
- await setRefreshToken(result.refresh_token);
-
- // Associate guest cart
- const cartToken = await getCartToken();
- const cartId = await getCartId();
- if (cartToken && cartId) {
- try {
- await getClient().carts.associate(cartId, {
- token: result.token,
- spreeToken: cartToken,
- });
- } catch {
- // Non-fatal
- }
- }
-
- revalidateTag('customer');
- revalidateTag('cart');
- return { success: true, user: result.user };
- } catch (error) {
- return {
- success: false,
- error: error instanceof Error ? error.message : 'Registration failed',
- };
- }
-}
-
-/**
- * Logout the current user.
- * Clears all auth and cart cookies to prevent the next guest session
- * from seeing/modifying the previous user's cart.
- */
-export async function logout(): Promise<void> {
- // Revoke refresh token server-side
- const refreshToken = await getRefreshToken();
- if (refreshToken) {
- try {
- await getClient().auth.logout({ refresh_token: refreshToken });
- } catch {
- // Non-fatal — token may already be expired/revoked
- }
- }
-
- await clearAccessToken();
- await clearRefreshToken();
- await clearCartCookies();
- revalidateTag('customer');
- revalidateTag('cart');
- revalidateTag('addresses');
- revalidateTag('credit-cards');
-}
-
-/**
- * Get the currently authenticated customer. Returns null if not logged in.
- */
-export async function getCustomer(): Promise<Customer | null> {
- const token = await getAccessToken();
- if (!token) return null;
-
- try {
- return await withAuthRefresh(async (options) => {
- return getClient().customer.get(options);
- });
- } catch {
- await clearAccessToken();
- await clearRefreshToken();
- return null;
- }
-}
-
-/**
- * Request a password reset email.
- * Always succeeds to prevent email enumeration.
- *
- * @param email - The email address of the account
- * @param redirectUrl - Optional URL to redirect the user to after clicking the reset link.
- * Must match one of the store's allowed origins.
- */
-export async function requestPasswordReset(
- email: string,
- redirectUrl?: string
-): Promise<{ message: string }> {
- return getClient().passwordResets.create({
- email,
- ...(redirectUrl && { redirect_url: redirectUrl }),
- });
-}
-
-/**
- * Reset password using a token from the password reset email.
- * On success, the user is automatically logged in.
- */
-export async function resetPassword(
- token: string,
- password: string,
- password_confirmation: string
-): Promise<{ success: boolean; error?: string }> {
- try {
- const result = await getClient().passwordResets.update(token, {
- password,
- password_confirmation,
- });
- await setAccessToken(result.token);
- await setRefreshToken(result.refresh_token);
- revalidateTag('customer');
- revalidateTag('cart');
- return { success: true };
- } catch (error) {
- return {
- success: false,
- error: error instanceof Error ? error.message : 'Password reset failed',
- };
- }
-}
-
-/**
- * Update the current customer's profile.
- */
-export async function updateCustomer(
- data: {
- first_name?: string;
- last_name?: string;
- email?: string;
- password?: string;
- password_confirmation?: string;
- /** Required when changing email or password */
- current_password?: string;
- phone?: string;
- accepts_email_marketing?: boolean;
- metadata?: Record<string, unknown>;
- }
-): Promise<Customer> {
- const result = await withAuthRefresh(async (options) => {
- return getClient().customer.update(data, options);
- });
- revalidateTag('customer');
- return result;
-}
diff --git a/packages/next/src/actions/cart.ts b/packages/next/src/actions/cart.ts
deleted file mode 100644
index 7ce17dd05e..0000000000
--- a/packages/next/src/actions/cart.ts
+++ /dev/null
@@ -1,259 +0,0 @@
-'use server';
-
-import { revalidateTag } from 'next/cache';
-import type { Cart, Order, CreateCartParams, UpdateCartParams } from '@spree/sdk';
-import { getClient } from '../config';
-import {
- getCartToken, getCartId,
- setCartCookies, clearCartCookies,
- getAccessToken,
- getCartOptions, requireCartId,
-} from '../cookies';
-
-/**
- * Get the current cart. Returns null if no cart exists.
- * @param explicitCartId - Optional cart ID to fetch directly, bypassing cookie lookup.
- */
-export async function getCart(explicitCartId?: string): Promise<Cart | null> {
- const spreeToken = await getCartToken();
- const token = await getAccessToken();
- const cartId = explicitCartId ?? await getCartId();
-
- if (!cartId && !token) return null;
-
- try {
- if (cartId) {
- return await getClient().carts.get(cartId, { spreeToken, token });
- }
-
- // Authenticated user without stored cart ID — find their most recent cart
- if (token) {
- const response = await getClient().carts.list({ token });
- if (response.data.length > 0) {
- const cart = response.data[0];
- await setCartCookies(cart.id, cart.token);
- return cart;
- }
- }
-
- return null;
- } catch {
- // Cart not found (e.g., order was completed) — clear stale cookies
- if (!explicitCartId) {
- await clearCartCookies();
- }
- return null;
- }
-}
-
-/**
- * Get existing cart or create a new one.
- * @param params - Optional cart creation params (metadata, items)
- */
-export async function getOrCreateCart(
- params?: CreateCartParams
-): Promise<Cart> {
- const existing = await getCart();
- if (existing) return existing;
-
- const token = await getAccessToken();
- const cartParams = params && Object.keys(params).length > 0 ? params : undefined;
- const cart = await getClient().carts.create(cartParams, token ? { token } : undefined);
-
- await setCartCookies(cart.id, cart.token);
-
- revalidateTag('cart');
- return cart;
-}
-
-/**
- * Add an item to the cart. Creates a cart if none exists.
- * Returns the updated cart with recalculated totals.
- */
-export async function addItem(
- variantId: string,
- quantity: number = 1,
- metadata?: Record<string, unknown>
-): Promise<Cart> {
- const cart = await getOrCreateCart();
- const spreeToken = await getCartToken();
- const token = await getAccessToken();
-
- const updatedCart = await getClient().carts.items.create(
- cart.id,
- { variant_id: variantId, quantity, metadata },
- { spreeToken, token }
- );
-
- revalidateTag('cart');
- return updatedCart;
-}
-
-/**
- * Update a line item in the cart (quantity and/or metadata).
- * Returns the updated cart with recalculated totals.
- */
-export async function updateItem(
- lineItemId: string,
- params: { quantity?: number; metadata?: Record<string, unknown> }
-): Promise<Cart> {
- const options = await getCartOptions();
- const cartId = await requireCartId();
-
- const cart = await getClient().carts.items.update(
- cartId,
- lineItemId,
- params,
- options
- );
-
- revalidateTag('cart');
- return cart;
-}
-
-/**
- * Remove a line item from the cart.
- * Returns the updated cart with recalculated totals.
- */
-export async function removeItem(lineItemId: string): Promise<Cart> {
- const options = await getCartOptions();
- const cartId = await requireCartId();
-
- const cart = await getClient().carts.items.delete(cartId, lineItemId, options);
-
- revalidateTag('cart');
- return cart;
-}
-
-/**
- * Clear the cart (abandons the current cart).
- */
-export async function clearCart(): Promise<void> {
- await clearCartCookies();
- revalidateTag('cart');
-}
-
-/**
- * Associate a guest cart with the currently authenticated user.
- * Call this after login/register when the user has an existing guest cart.
- */
-export async function associateCart(): Promise<Cart | null> {
- const spreeToken = await getCartToken();
- const token = await getAccessToken();
- const cartId = await getCartId();
- if (!cartId || !token) return null;
-
- try {
- const result = await getClient().carts.associate(cartId, { spreeToken, token });
- revalidateTag('cart');
- return result;
- } catch {
- // Cart might already belong to another user — clear it
- await clearCartCookies();
- revalidateTag('cart');
- return null;
- }
-}
-
-/**
- * Update cart info (email, addresses, special instructions).
- */
-export async function updateCart(
- params: UpdateCartParams
-): Promise<Cart> {
- const options = await getCartOptions();
- const cartId = await requireCartId();
- const result = await getClient().carts.update(cartId, params, options);
- revalidateTag('checkout');
- return result;
-}
-
-/**
- * Select a delivery rate for a fulfillment.
- * Returns the updated cart with recalculated totals.
- */
-export async function selectDeliveryRate(
- fulfillmentId: string,
- deliveryRateId: string
-): Promise<Cart> {
- const options = await getCartOptions();
- const cartId = await requireCartId();
- const result = await getClient().carts.fulfillments.update(
- cartId,
- fulfillmentId,
- { selected_delivery_rate_id: deliveryRateId },
- options
- );
- revalidateTag('checkout');
- return result;
-}
-
-/**
- * Apply a discount code to the cart.
- */
-export async function applyDiscountCode(
- code: string
-): Promise<Cart> {
- const options = await getCartOptions();
- const cartId = await requireCartId();
- const result = await getClient().carts.discountCodes.apply(cartId, code, options);
- revalidateTag('checkout');
- revalidateTag('cart');
- return result;
-}
-
-/**
- * Remove a discount code from the cart.
- */
-export async function removeDiscountCode(
- code: string
-): Promise<Cart> {
- const options = await getCartOptions();
- const cartId = await requireCartId();
- const result = await getClient().carts.discountCodes.remove(cartId, code, options);
- revalidateTag('checkout');
- revalidateTag('cart');
- return result;
-}
-
-/**
- * Apply a gift card to the cart.
- * Gift cards are treated as a payment method — the cart total stays the same
- * while `amount_due` is reduced.
- */
-export async function applyGiftCard(
- code: string
-): Promise<Cart> {
- const options = await getCartOptions();
- const cartId = await requireCartId();
- const result = await getClient().carts.giftCards.apply(cartId, code, options);
- revalidateTag('checkout');
- revalidateTag('cart');
- return result;
-}
-
-/**
- * Remove the applied gift card from the cart.
- * @param giftCardId - Gift card prefixed ID (e.g., 'gc_abc123') from cart.gift_card.id
- */
-export async function removeGiftCard(giftCardId: string): Promise<Cart> {
- const options = await getCartOptions();
- const cartId = await requireCartId();
- const result = await getClient().carts.giftCards.remove(cartId, giftCardId, options);
- revalidateTag('checkout');
- revalidateTag('cart');
- return result;
-}
-
-/**
- * Complete the checkout and place the order.
- * @param explicitCartId - Optional cart ID to complete. If not provided, uses the cart cookie.
- */
-export async function complete(explicitCartId?: string): Promise<Order> {
- const options = await getCartOptions();
- const cartId = explicitCartId ?? await requireCartId();
- const result = await getClient().carts.complete(cartId, options);
- revalidateTag('checkout');
- revalidateTag('cart');
- return result;
-}
diff --git a/packages/next/src/actions/credit-cards.ts b/packages/next/src/actions/credit-cards.ts
deleted file mode 100644
index b0803f9137..0000000000
--- a/packages/next/src/actions/credit-cards.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-'use server';
-
-import { revalidateTag } from 'next/cache';
-import type { CreditCard } from '@spree/sdk';
-import { withAuthRefresh } from '../auth-helpers';
-import { getClient } from '../config';
-
-/**
- * List the authenticated customer's credit cards.
- */
-export async function listCreditCards(): Promise<{ data: CreditCard[] }> {
- return withAuthRefresh(async (options) => {
- return getClient().customer.creditCards.list(undefined, options);
- });
-}
-
-/**
- * Delete a credit card.
- */
-export async function deleteCreditCard(id: string): Promise<void> {
- await withAuthRefresh(async (options) => {
- return getClient().customer.creditCards.delete(id, options);
- });
- revalidateTag('credit-cards');
-}
diff --git a/packages/next/src/actions/gift-cards.ts b/packages/next/src/actions/gift-cards.ts
deleted file mode 100644
index 460fa6ff88..0000000000
--- a/packages/next/src/actions/gift-cards.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-'use server';
-
-import type { GiftCard } from '@spree/sdk';
-import { withAuthRefresh } from '../auth-helpers';
-import { getClient } from '../config';
-
-/**
- * List the authenticated customer's gift cards.
- */
-export async function listGiftCards(): Promise<{ data: GiftCard[] }> {
- return withAuthRefresh(async (options) => {
- return getClient().customer.giftCards.list(undefined, options);
- });
-}
-
-/**
- * Get a single gift card by ID.
- */
-export async function getGiftCard(id: string): Promise<GiftCard> {
- return withAuthRefresh(async (options) => {
- return getClient().customer.giftCards.get(id, options);
- });
-}
diff --git a/packages/next/src/actions/locale.ts b/packages/next/src/actions/locale.ts
deleted file mode 100644
index 363b46e34b..0000000000
--- a/packages/next/src/actions/locale.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-'use server';
-
-import { cookies } from 'next/headers';
-import { getConfig } from '../config';
-
-/**
- * Set locale/country cookies for subsequent requests.
- * Use this in country/language switchers instead of manipulating cookies directly.
- */
-export async function setLocale(params: {
- country?: string;
- locale?: string;
-}): Promise<void> {
- const config = getConfig();
- const cookieStore = await cookies();
- const maxAge = 60 * 60 * 24 * 365; // 1 year
-
- if (params.country) {
- cookieStore.set(config.countryCookieName ?? 'spree_country', params.country, {
- path: '/',
- maxAge,
- });
- }
- if (params.locale) {
- cookieStore.set(config.localeCookieName ?? 'spree_locale', params.locale, {
- path: '/',
- maxAge,
- });
- }
-}
diff --git a/packages/next/src/actions/orders.ts b/packages/next/src/actions/orders.ts
deleted file mode 100644
index 87e0bd58f7..0000000000
--- a/packages/next/src/actions/orders.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-'use server';
-
-import type { Order, PaginatedResponse, OrderListParams } from '@spree/sdk';
-import { withAuthRefresh } from '../auth-helpers';
-import { getClient } from '../config';
-import { getCartOptions } from '../cookies';
-
-/**
- * List the authenticated customer's orders.
- */
-export async function listOrders(
- params?: OrderListParams
-): Promise<PaginatedResponse<Order>> {
- return withAuthRefresh(async (options) => {
- return getClient().customer.orders.list(params, options);
- });
-}
-
-/**
- * Get a single order by ID or number.
- * Works for both authenticated users (JWT) and guests (spreeToken).
- */
-export async function getOrder(
- idOrNumber: string,
- params?: Record<string, unknown>
-): Promise<Order> {
- const options = await getCartOptions();
- return getClient().orders.get(idOrNumber, params, options);
-}
diff --git a/packages/next/src/actions/payment-sessions.ts b/packages/next/src/actions/payment-sessions.ts
deleted file mode 100644
index 1a7ea931bf..0000000000
--- a/packages/next/src/actions/payment-sessions.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-'use server';
-
-import { revalidateTag } from 'next/cache';
-import type {
- PaymentSession,
- CreatePaymentSessionParams,
- UpdatePaymentSessionParams,
- CompletePaymentSessionParams,
-} from '@spree/sdk';
-import { getClient } from '../config';
-import { getCartOptions, requireCartId } from '../cookies';
-
-/**
- * Create a payment session for the current cart.
- * Delegates to the payment gateway to initialize a provider-specific session.
- */
-export async function createPaymentSession(
- params: CreatePaymentSessionParams
-): Promise<PaymentSession> {
- const options = await getCartOptions();
- const cartId = await requireCartId();
- const result = await getClient().carts.paymentSessions.create(cartId, params, options);
- revalidateTag('checkout');
- return result;
-}
-
-/**
- * Get a payment session by ID.
- */
-export async function getPaymentSession(
- sessionId: string
-): Promise<PaymentSession> {
- const options = await getCartOptions();
- const cartId = await requireCartId();
- return getClient().carts.paymentSessions.get(cartId, sessionId, options);
-}
-
-/**
- * Update a payment session.
- * Delegates to the payment gateway to sync changes with the provider.
- */
-export async function updatePaymentSession(
- sessionId: string,
- params: UpdatePaymentSessionParams
-): Promise<PaymentSession> {
- const options = await getCartOptions();
- const cartId = await requireCartId();
- const result = await getClient().carts.paymentSessions.update(cartId, sessionId, params, options);
- revalidateTag('checkout');
- return result;
-}
-
-/**
- * Complete a payment session.
- * Confirms the payment with the provider, triggering capture/authorization.
- */
-export async function completePaymentSession(
- sessionId: string,
- params?: CompletePaymentSessionParams
-): Promise<PaymentSession> {
- const options = await getCartOptions();
- const cartId = await requireCartId();
- const result = await getClient().carts.paymentSessions.complete(cartId, sessionId, params, options);
- revalidateTag('checkout');
- return result;
-}
diff --git a/packages/next/src/actions/payment-setup-sessions.ts b/packages/next/src/actions/payment-setup-sessions.ts
deleted file mode 100644
index 3ce4bdc3d9..0000000000
--- a/packages/next/src/actions/payment-setup-sessions.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-'use server';
-
-import type {
- PaymentSetupSession,
- CreatePaymentSetupSessionParams,
- CompletePaymentSetupSessionParams,
-} from '@spree/sdk';
-import { withAuthRefresh } from '../auth-helpers';
-import { getClient } from '../config';
-
-/**
- * Create a payment setup session for saving a payment method.
- * Delegates to the payment gateway to initialize a setup flow.
- */
-export async function createPaymentSetupSession(
- params: CreatePaymentSetupSessionParams
-): Promise<PaymentSetupSession> {
- return withAuthRefresh(async (options) => {
- return getClient().customer.paymentSetupSessions.create(params, options);
- });
-}
-
-/**
- * Get a payment setup session by ID.
- */
-export async function getPaymentSetupSession(
- id: string
-): Promise<PaymentSetupSession> {
- return withAuthRefresh(async (options) => {
- return getClient().customer.paymentSetupSessions.get(id, options);
- });
-}
-
-/**
- * Complete a payment setup session.
- * Confirms the setup with the provider, resulting in a saved payment method.
- */
-export async function completePaymentSetupSession(
- id: string,
- params?: CompletePaymentSetupSessionParams
-): Promise<PaymentSetupSession> {
- return withAuthRefresh(async (options) => {
- return getClient().customer.paymentSetupSessions.complete(id, params, options);
- });
-}
diff --git a/packages/next/src/actions/payments.ts b/packages/next/src/actions/payments.ts
deleted file mode 100644
index beb12e5f4f..0000000000
--- a/packages/next/src/actions/payments.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-'use server';
-
-import { revalidateTag } from 'next/cache';
-import type { Payment, CreatePaymentParams } from '@spree/sdk';
-import { getClient } from '../config';
-import { getCartOptions, requireCartId } from '../cookies';
-
-/**
- * Create a payment for a non-session payment method (e.g. Check, Cash on Delivery, Bank Transfer).
- * For session-based payment methods (e.g. Stripe, PayPal), use createPaymentSession instead.
- */
-export async function createPayment(
- params: CreatePaymentParams
-): Promise<Payment> {
- const options = await getCartOptions();
- const cartId = await requireCartId();
- const result = await getClient().carts.payments.create(cartId, params, options);
- revalidateTag('checkout');
- return result;
-}
diff --git a/packages/next/src/actions/store-credits.ts b/packages/next/src/actions/store-credits.ts
deleted file mode 100644
index 2d93f3f782..0000000000
--- a/packages/next/src/actions/store-credits.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-'use server';
-
-import type { StoreCredit, PaginatedResponse, ListParams } from '@spree/sdk';
-import { withAuthRefresh } from '../auth-helpers';
-import { getClient } from '../config';
-
-/**
- * List store credits for the authenticated customer.
- * Filtered by current store and currency on the backend.
- */
-export async function listStoreCredits(
- params?: ListParams
-): Promise<PaginatedResponse<StoreCredit>> {
- return withAuthRefresh(async (options) => {
- return getClient().customer.storeCredits.list(params, options);
- });
-}
diff --git a/packages/next/src/data/categories.ts b/packages/next/src/data/categories.ts
deleted file mode 100644
index a8d8890a9a..0000000000
--- a/packages/next/src/data/categories.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import type { Category, Product, PaginatedResponse, CategoryListParams, ProductListParams } from '@spree/sdk';
-import { getClient } from '../config';
-import { getLocaleOptions } from '../locale';
-import type { SpreeNextOptions } from '../types';
-
-/**
- * List categories with optional filtering and pagination.
- * Locale/country are auto-read from cookies when not provided.
- */
-export async function listCategories(
- params?: CategoryListParams,
- options?: SpreeNextOptions
-): Promise<PaginatedResponse<Category>> {
- const resolved = options ?? await getLocaleOptions();
- return getClient().categories.list(params, resolved);
-}
-
-/**
- * Get a single category by ID or permalink.
- * Locale/country are auto-read from cookies when not provided.
- */
-export async function getCategory(
- idOrPermalink: string,
- params?: Record<string, unknown>,
- options?: SpreeNextOptions
-): Promise<Category> {
- const resolved = options ?? await getLocaleOptions();
- return getClient().categories.get(idOrPermalink, params, resolved);
-}
-
-/**
- * List products within a category (includes descendants).
- * Uses the in_category scope on the /products endpoint.
- * Locale/country are auto-read from cookies when not provided.
- */
-export async function listCategoryProducts(
- categoryId: string,
- params?: ProductListParams,
- options?: SpreeNextOptions
-): Promise<PaginatedResponse<Product>> {
- const resolved = options ?? await getLocaleOptions();
- return getClient().products.list({ ...params, in_category: categoryId }, resolved);
-}
diff --git a/packages/next/src/data/countries.ts b/packages/next/src/data/countries.ts
deleted file mode 100644
index 118530bb93..0000000000
--- a/packages/next/src/data/countries.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import type { Country } from '@spree/sdk';
-import { getClient } from '../config';
-import { getLocaleOptions } from '../locale';
-import type { SpreeNextOptions } from '../types';
-
-/**
- * List countries available in the store.
- * Use ?expand=market to expand market details (currency, locale, tax_inclusive).
- */
-export async function listCountries(
- options?: SpreeNextOptions
-): Promise<{ data: Country[] }> {
- const resolved = options ?? await getLocaleOptions();
- return getClient().countries.list(resolved);
-}
-
-/**
- * Get a country by ISO code.
- * @param iso - ISO 3166-1 alpha-2 code (e.g., "US", "DE")
- * @param params - Optional params (e.g., { expand: ['states'] } or { expand: ['market'] })
- */
-export async function getCountry(
- iso: string,
- params?: { expand?: string[] },
- options?: SpreeNextOptions
-): Promise<Country> {
- const resolved = options ?? await getLocaleOptions();
- return getClient().countries.get(iso, params, resolved);
-}
diff --git a/packages/next/src/data/currencies.ts b/packages/next/src/data/currencies.ts
deleted file mode 100644
index 5f7536a01e..0000000000
--- a/packages/next/src/data/currencies.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import type { Currency } from '@spree/sdk';
-import { getClient } from '../config';
-import { getLocaleOptions } from '../locale';
-import type { SpreeNextOptions } from '../types';
-
-/**
- * List currencies supported by the store (derived from markets).
- * Locale/country are auto-read from cookies when not provided.
- */
-export async function listCurrencies(
- options?: SpreeNextOptions
-): Promise<{ data: Currency[] }> {
- const resolved = options ?? await getLocaleOptions();
- return getClient().currencies.list(resolved);
-}
diff --git a/packages/next/src/data/locales.ts b/packages/next/src/data/locales.ts
deleted file mode 100644
index 985eb7c526..0000000000
--- a/packages/next/src/data/locales.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import type { Locale } from '@spree/sdk';
-import { getClient } from '../config';
-import { getLocaleOptions } from '../locale';
-import type { SpreeNextOptions } from '../types';
-
-/**
- * List locales supported by the store (derived from markets).
- * Locale/country are auto-read from cookies when not provided.
- */
-export async function listLocales(
- options?: SpreeNextOptions
-): Promise<{ data: Locale[] }> {
- const resolved = options ?? await getLocaleOptions();
- return getClient().locales.list(resolved);
-}
diff --git a/packages/next/src/data/markets.ts b/packages/next/src/data/markets.ts
deleted file mode 100644
index d5938fa768..0000000000
--- a/packages/next/src/data/markets.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-import type { Market, Country } from '@spree/sdk';
-import { getClient } from '../config';
-import { getLocaleOptions } from '../locale';
-import type { SpreeNextOptions } from '../types';
-
-/**
- * List all markets for the current store.
- * Each market contains currency, locales, tax_inclusive flag, and countries.
- */
-export async function listMarkets(
- options?: SpreeNextOptions
-): Promise<{ data: Market[] }> {
- const resolved = options ?? await getLocaleOptions();
- return getClient().markets.list(resolved);
-}
-
-/**
- * Get a market by prefixed ID.
- * @param id - Market prefixed ID (e.g., "mkt_k5nR8xLq")
- */
-export async function getMarket(
- id: string,
- options?: SpreeNextOptions
-): Promise<Market> {
- const resolved = options ?? await getLocaleOptions();
- return getClient().markets.get(id, resolved);
-}
-
-/**
- * Resolve which market applies for a given country.
- * @param country - ISO 3166-1 alpha-2 code (e.g., "DE", "US")
- */
-export async function resolveMarket(
- country: string,
- options?: SpreeNextOptions
-): Promise<Market> {
- const resolved = options ?? await getLocaleOptions();
- return getClient().markets.resolve(country, resolved);
-}
-
-/**
- * List countries belonging to a market.
- * @param marketId - Market prefixed ID
- */
-export async function listMarketCountries(
- marketId: string,
- options?: SpreeNextOptions
-): Promise<{ data: Country[] }> {
- const resolved = options ?? await getLocaleOptions();
- return getClient().markets.countries.list(marketId, resolved);
-}
-
-/**
- * Get a country by ISO code within a market.
- * @param marketId - Market prefixed ID
- * @param iso - Country ISO code (e.g., "DE")
- */
-export async function getMarketCountry(
- marketId: string,
- iso: string,
- params?: { expand?: string[] },
- options?: SpreeNextOptions
-): Promise<Country> {
- const resolved = options ?? await getLocaleOptions();
- return getClient().markets.countries.get(marketId, iso, params, resolved);
-}
diff --git a/packages/next/src/data/policies.ts b/packages/next/src/data/policies.ts
deleted file mode 100644
index fda3eb04d4..0000000000
--- a/packages/next/src/data/policies.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import type { Policy } from '@spree/sdk';
-import { getClient } from '../config';
-import { getLocaleOptions } from '../locale';
-import type { SpreeNextOptions } from '../types';
-
-/**
- * List store policies (return policy, privacy policy, terms of service, etc.)
- * Locale/country are auto-read from cookies when not provided.
- */
-export async function listPolicies(
- options?: SpreeNextOptions
-): Promise<{ data: Policy[] }> {
- const resolved = options ?? await getLocaleOptions();
- return getClient().policies.list(resolved);
-}
-
-/**
- * Get a single policy by slug or prefixed ID.
- * @param id - Policy slug (e.g., 'return-policy') or prefixed ID (e.g., 'pol_abc123')
- */
-export async function getPolicy(
- id: string,
- options?: SpreeNextOptions
-): Promise<Policy> {
- const resolved = options ?? await getLocaleOptions();
- return getClient().policies.get(id, resolved);
-}
diff --git a/packages/next/src/data/products.ts b/packages/next/src/data/products.ts
deleted file mode 100644
index e818a166d6..0000000000
--- a/packages/next/src/data/products.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import type { Product, PaginatedResponse, ProductFiltersResponse, ProductListParams } from '@spree/sdk';
-import { getClient } from '../config';
-import { getLocaleOptions } from '../locale';
-import type { SpreeNextOptions } from '../types';
-
-/**
- * List products with optional filtering, sorting, and pagination.
- * Locale/country are auto-read from cookies when not provided.
- */
-export async function listProducts(
- params?: ProductListParams,
- options?: SpreeNextOptions
-): Promise<PaginatedResponse<Product>> {
- const resolved = options ?? await getLocaleOptions();
- return getClient().products.list(params, resolved);
-}
-
-/**
- * Get a single product by slug or ID.
- * Locale/country are auto-read from cookies when not provided.
- */
-export async function getProduct(
- slugOrId: string,
- params?: { expand?: string[] },
- options?: SpreeNextOptions
-): Promise<Product> {
- const resolved = options ?? await getLocaleOptions();
- return getClient().products.get(slugOrId, params, resolved);
-}
-
-/**
- * Get available product filters (price ranges, option values, etc.).
- * Locale/country are auto-read from cookies when not provided.
- */
-export async function getProductFilters(
- params?: Record<string, unknown>,
- options?: SpreeNextOptions
-): Promise<ProductFiltersResponse> {
- const resolved = options ?? await getLocaleOptions();
- return getClient().products.filters(params, resolved);
-}
diff --git a/packages/next/src/index.ts b/packages/next/src/index.ts
index dfb2c977fd..0d4542cb05 100644
--- a/packages/next/src/index.ts
+++ b/packages/next/src/index.ts
@@ -1,115 +1,25 @@
// Configuration
-export { initSpreeNext, getClient } from './config';
+export { initSpreeNext, getClient, getConfig } from './config';
export type { SpreeNextConfig, SpreeNextOptions } from './types';
-// Data reads (plain async functions — wrap with "use cache" in your app)
-export { listProducts, getProduct, getProductFilters } from './data/products';
-export { listCategories, getCategory, listCategoryProducts } from './data/categories';
-export { listCountries, getCountry } from './data/countries';
-export { listCurrencies } from './data/currencies';
-export { listLocales } from './data/locales';
-export { listMarkets, getMarket, resolveMarket, listMarketCountries, getMarketCountry } from './data/markets';
-export { listPolicies, getPolicy } from './data/policies';
+// Auth helpers (token refresh, cookie-based auth)
+export { withAuthRefresh, getAuthOptions } from './auth-helpers';
-// Server actions (mutations + auth-dependent reads)
+// Cookie management
export {
- getCart,
- getOrCreateCart,
- addItem,
- updateItem,
- removeItem,
- clearCart,
- associateCart,
- updateCart,
- selectDeliveryRate,
- applyDiscountCode,
- removeDiscountCode,
- applyGiftCard,
- removeGiftCard,
- complete,
-} from './actions/cart';
-
-export {
- login,
- register,
- logout,
- getCustomer,
- updateCustomer,
- requestPasswordReset,
- resetPassword,
-} from './actions/auth';
-
-export {
- listAddresses,
- getAddress,
- createAddress,
- updateAddress,
- deleteAddress,
-} from './actions/addresses';
-
-export { listOrders, getOrder } from './actions/orders';
-export { setLocale } from './actions/locale';
-export { listCreditCards, deleteCreditCard } from './actions/credit-cards';
-export { listGiftCards, getGiftCard } from './actions/gift-cards';
-export { listStoreCredits } from './actions/store-credits';
-
-export { createPayment } from './actions/payments';
-
-export {
- createPaymentSession,
- getPaymentSession,
- updatePaymentSession,
- completePaymentSession,
-} from './actions/payment-sessions';
-
-export {
- createPaymentSetupSession,
- getPaymentSetupSession,
- completePaymentSetupSession,
-} from './actions/payment-setup-sessions';
-
-// Re-export commonly used SDK types for convenience
-export type {
- Cart,
- CartWarning,
- Product,
- Order,
- LineItem,
- Variant,
- Category,
- Country,
- Currency,
- Locale,
- Market,
- Policy,
- Address,
- Customer,
- CreditCard,
- DigitalLink,
- GiftCard,
- StoreCredit,
- Fulfillment,
- DeliveryRate,
- Payment,
- PaymentMethod,
- PaymentSession,
- PaymentSetupSession,
- Media,
- OptionType,
- OptionValue,
- Price,
- Discount,
- PaginatedResponse,
- AddressParams,
- CreateCartParams,
- LineItemInput,
- UpdateCartParams,
- ProductFiltersResponse,
- CreatePaymentParams,
- CreatePaymentSessionParams,
- UpdatePaymentSessionParams,
- CompletePaymentSessionParams,
- CreatePaymentSetupSessionParams,
- CompletePaymentSetupSessionParams,
- SpreeError,
-} from '@spree/sdk';
+ getCartToken,
+ getCartId,
+ setCartCookies,
+ clearCartCookies,
+ getAccessToken,
+ setAccessToken,
+ clearAccessToken,
+ getRefreshToken,
+ setRefreshToken,
+ clearRefreshToken,
+ getCartOptions,
+ requireCartId,
+} from './cookies';
+
+// Locale resolution (reads country/locale from cookies)
+export { getLocaleOptions } from './locale';
diff --git a/packages/next/tests/actions/addresses.test.ts b/packages/next/tests/actions/addresses.test.ts
deleted file mode 100644
index 5272e63f0f..0000000000
--- a/packages/next/tests/actions/addresses.test.ts
+++ /dev/null
@@ -1,142 +0,0 @@
-import { describe, it, expect, beforeEach, vi } from 'vitest';
-import { mockCookieStore } from '../setup';
-import { initSpreeNext, resetClient } from '../../src/config';
-
-const mockClient = {
- customer: {
- addresses: {
- list: vi.fn(),
- get: vi.fn(),
- create: vi.fn(),
- update: vi.fn(),
- delete: vi.fn(),
- },
- },
- auth: {
- refresh: vi.fn(),
- },
-};
-
-vi.mock('@spree/sdk', () => ({
- createClient: vi.fn(() => mockClient),
- SpreeError: class SpreeError extends Error {
- public readonly status: number;
- constructor(response: { error: { message: string } }, status: number) {
- super(response.error.message);
- this.status = status;
- }
- },
-}));
-
-import {
- listAddresses,
- getAddress,
- createAddress,
- updateAddress,
- deleteAddress,
-} from '../../src/actions/addresses';
-import { revalidateTag } from 'next/cache';
-
-// Create a JWT that expires far in the future (no proactive refresh)
-function makeFutureJwt(): string {
- const payload = { exp: Math.floor(Date.now() / 1000) + 86400 }; // 24h from now
- return `header.${btoa(JSON.stringify(payload))}.signature`;
-}
-
-describe('address actions', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- resetClient();
- initSpreeNext({ baseUrl: 'https://api.test.com', publishableKey: 'pk_test' });
- // Authenticated user with valid JWT
- mockCookieStore.get.mockReturnValue({ value: makeFutureJwt() });
- });
-
- describe('listAddresses', () => {
- it('returns addresses list', async () => {
- const mockAddresses = { data: [{ id: '1', first_name: 'John' }] };
- mockClient.customer.addresses.list.mockResolvedValue(mockAddresses);
-
- const result = await listAddresses();
- expect(result).toEqual(mockAddresses);
- expect(mockClient.customer.addresses.list).toHaveBeenCalledWith(
- undefined,
- expect.objectContaining({ token: expect.any(String) })
- );
- });
- });
-
- describe('getAddress', () => {
- it('returns a single address', async () => {
- const mockAddress = { id: '1', first_name: 'John', last_name: 'Doe' };
- mockClient.customer.addresses.get.mockResolvedValue(mockAddress);
-
- const result = await getAddress('1');
- expect(result).toEqual(mockAddress);
- expect(mockClient.customer.addresses.get).toHaveBeenCalledWith(
- '1',
- expect.objectContaining({ token: expect.any(String) })
- );
- });
- });
-
- describe('createAddress', () => {
- it('creates address and revalidates', async () => {
- const params = {
- first_name: 'Jane',
- last_name: 'Doe',
- address1: '456 Oak Ave',
- city: 'LA',
- postal_code: '90001',
- country_iso: 'US',
- };
- const mockAddress = { id: '2', ...params };
- mockClient.customer.addresses.create.mockResolvedValue(mockAddress);
-
- const result = await createAddress(params);
- expect(result).toEqual(mockAddress);
- expect(mockClient.customer.addresses.create).toHaveBeenCalledWith(
- params,
- expect.objectContaining({ token: expect.any(String) })
- );
- expect(revalidateTag).toHaveBeenCalledWith('addresses');
- });
- });
-
- describe('updateAddress', () => {
- it('updates address and revalidates', async () => {
- const params = { first_name: 'Updated' };
- const mockAddress = { id: '1', first_name: 'Updated', last_name: 'Doe' };
- mockClient.customer.addresses.update.mockResolvedValue(mockAddress);
-
- const result = await updateAddress('1', params);
- expect(result).toEqual(mockAddress);
- expect(mockClient.customer.addresses.update).toHaveBeenCalledWith(
- '1',
- params,
- expect.objectContaining({ token: expect.any(String) })
- );
- expect(revalidateTag).toHaveBeenCalledWith('addresses');
- });
- });
-
- describe('deleteAddress', () => {
- it('deletes address and revalidates', async () => {
- mockClient.customer.addresses.delete.mockResolvedValue(undefined);
-
- await deleteAddress('1');
- expect(mockClient.customer.addresses.delete).toHaveBeenCalledWith(
- '1',
- expect.objectContaining({ token: expect.any(String) })
- );
- expect(revalidateTag).toHaveBeenCalledWith('addresses');
- });
- });
-
- describe('when not authenticated', () => {
- it('throws error', async () => {
- mockCookieStore.get.mockReturnValue(undefined);
- await expect(listAddresses()).rejects.toThrow('Not authenticated');
- });
- });
-});
diff --git a/packages/next/tests/actions/auth.test.ts b/packages/next/tests/actions/auth.test.ts
deleted file mode 100644
index ac319e6189..0000000000
--- a/packages/next/tests/actions/auth.test.ts
+++ /dev/null
@@ -1,250 +0,0 @@
-import { describe, it, expect, beforeEach, vi } from 'vitest';
-import { mockCookieStore } from '../setup';
-import { initSpreeNext, resetClient } from '../../src/config';
-
-const mockClient = {
- auth: {
- login: vi.fn(),
- refresh: vi.fn(),
- },
- customers: {
- create: vi.fn(),
- },
- customer: {
- get: vi.fn(),
- update: vi.fn(),
- },
- carts: {
- associate: vi.fn(),
- },
-};
-
-vi.mock('@spree/sdk', () => ({
- createClient: vi.fn(() => mockClient),
- SpreeError: class SpreeError extends Error {
- public readonly code: string;
- public readonly status: number;
- constructor(response: { error: { code: string; message: string } }, status: number) {
- super(response.error.message);
- this.code = response.error.code;
- this.status = status;
- }
- },
-}));
-
-import { login, register, logout, getCustomer, updateCustomer } from '../../src/actions/auth';
-import { revalidateTag } from 'next/cache';
-
-function mockCookies(values: Record<string, string | undefined>) {
- mockCookieStore.get.mockImplementation((name: string) => {
- const val = values[name];
- return val ? { value: val } : undefined;
- });
-}
-
-describe('auth actions', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- resetClient();
- initSpreeNext({ baseUrl: 'https://api.test.com', publishableKey: 'pk_test' });
- });
-
- describe('login', () => {
- it('returns user on success and sets token', async () => {
- const authResult = {
- token: 'jwt_new',
- user: { id: '1', email: '[email protected]', first_name: 'Test', last_name: 'User' },
- };
- mockCookies({}); // no cart token
- mockClient.auth.login.mockResolvedValue(authResult);
-
- const result = await login('[email protected]', 'password123');
- expect(result.success).toBe(true);
- expect(result.user).toEqual(authResult.user);
- expect(mockCookieStore.set).toHaveBeenCalledWith(
- '_spree_jwt',
- 'jwt_new',
- expect.any(Object)
- );
- expect(revalidateTag).toHaveBeenCalledWith('customer');
- });
-
- it('associates guest cart after login', async () => {
- const authResult = { token: 'jwt_new', user: { id: '1', email: '[email protected]' } };
- mockCookies({
- '_spree_cart_token': 'guest_cart_token',
- '_spree_cart_token_id': 'cart_1',
- });
- mockClient.auth.login.mockResolvedValue(authResult);
- mockClient.carts.associate.mockResolvedValue({});
-
- await login('[email protected]', 'pass');
- expect(mockClient.carts.associate).toHaveBeenCalledWith(
- 'cart_1',
- {
- token: 'jwt_new',
- spreeToken: 'guest_cart_token',
- }
- );
- });
-
- it('returns error on failure', async () => {
- mockClient.auth.login.mockRejectedValue(new Error('Invalid credentials'));
-
- const result = await login('[email protected]', 'wrong');
- expect(result.success).toBe(false);
- expect(result.error).toBe('Invalid credentials');
- });
- });
-
- describe('logout', () => {
- it('clears all auth and cart cookies and invalidates caches', async () => {
- await logout();
- // JWT cleared
- expect(mockCookieStore.set).toHaveBeenCalledWith(
- '_spree_jwt', '', expect.objectContaining({ maxAge: -1 })
- );
- // Cart cookies cleared
- expect(mockCookieStore.set).toHaveBeenCalledWith(
- '_spree_cart_token', '', expect.objectContaining({ maxAge: -1 })
- );
- expect(mockCookieStore.set).toHaveBeenCalledWith(
- '_spree_cart_token_id', '', expect.objectContaining({ maxAge: -1 })
- );
- expect(revalidateTag).toHaveBeenCalledWith('customer');
- expect(revalidateTag).toHaveBeenCalledWith('cart');
- expect(revalidateTag).toHaveBeenCalledWith('addresses');
- expect(revalidateTag).toHaveBeenCalledWith('credit-cards');
- });
- });
-
- describe('register', () => {
- it('calls customers.create with all params and sets token', async () => {
- const authResult = {
- token: 'jwt_new',
- user: { id: '1', email: '[email protected]', first_name: 'John', last_name: 'Doe' },
- };
- mockCookies({}); // no cart token
- mockClient.customers.create.mockResolvedValue(authResult);
-
- const result = await register({
- email: '[email protected]',
- password: 'password123',
- password_confirmation: 'password123',
- first_name: 'John',
- last_name: 'Doe',
- phone: '+1234567890',
- accepts_email_marketing: true,
- metadata: { source: 'storefront' },
- });
-
- expect(result.success).toBe(true);
- expect(result.user).toEqual(authResult.user);
- expect(mockClient.customers.create).toHaveBeenCalledWith({
- email: '[email protected]',
- password: 'password123',
- password_confirmation: 'password123',
- first_name: 'John',
- last_name: 'Doe',
- phone: '+1234567890',
- accepts_email_marketing: true,
- metadata: { source: 'storefront' },
- });
- expect(mockCookieStore.set).toHaveBeenCalledWith(
- '_spree_jwt',
- 'jwt_new',
- expect.any(Object)
- );
- expect(revalidateTag).toHaveBeenCalledWith('customer');
- expect(revalidateTag).toHaveBeenCalledWith('cart');
- });
-
- it('associates guest cart after registration', async () => {
- const authResult = { token: 'jwt_new', user: { id: '1', email: '[email protected]' } };
- mockCookies({
- '_spree_cart_token': 'guest_cart_token',
- '_spree_cart_token_id': 'cart_1',
- });
- mockClient.customers.create.mockResolvedValue(authResult);
- mockClient.carts.associate.mockResolvedValue({});
-
- await register({
- email: '[email protected]',
- password: 'password123',
- password_confirmation: 'password123',
- });
-
- expect(mockClient.carts.associate).toHaveBeenCalledWith(
- 'cart_1',
- {
- token: 'jwt_new',
- spreeToken: 'guest_cart_token',
- }
- );
- });
-
- it('returns error on failure', async () => {
- mockClient.customers.create.mockRejectedValue(new Error('Email taken'));
-
- const result = await register({
- email: '[email protected]',
- password: 'password123',
- password_confirmation: 'password123',
- });
-
- expect(result.success).toBe(false);
- expect(result.error).toBe('Email taken');
- });
- });
-
- describe('updateCustomer', () => {
- it('calls customer.update with all params', async () => {
- const updatedCustomer = {
- id: '1',
- email: '[email protected]',
- first_name: 'Updated',
- last_name: 'Name',
- phone: '+1234567890',
- accepts_email_marketing: true,
- };
- mockCookies({ '_spree_jwt': 'valid_jwt' });
- mockClient.customer.update.mockResolvedValue(updatedCustomer);
-
- const result = await updateCustomer({
- first_name: 'Updated',
- phone: '+1234567890',
- accepts_email_marketing: true,
- metadata: { preferred_contact: 'email' },
- });
-
- expect(result).toEqual(updatedCustomer);
- expect(mockClient.customer.update).toHaveBeenCalledWith(
- {
- first_name: 'Updated',
- phone: '+1234567890',
- accepts_email_marketing: true,
- metadata: { preferred_contact: 'email' },
- },
- expect.any(Object)
- );
- expect(revalidateTag).toHaveBeenCalledWith('customer');
- });
- });
-
- describe('getCustomer', () => {
- it('returns null when not authenticated', async () => {
- mockCookies({});
- const customer = await getCustomer();
- expect(customer).toBeNull();
- });
-
- it('returns customer when authenticated', async () => {
- const mockUser = { id: '1', email: '[email protected]' };
- mockCookies({ '_spree_jwt': 'valid_jwt' });
- mockClient.customer.get.mockResolvedValue(mockUser);
-
- const customer = await getCustomer();
- expect(customer).toEqual(mockUser);
- });
- });
-});
diff --git a/packages/next/tests/actions/cart.test.ts b/packages/next/tests/actions/cart.test.ts
deleted file mode 100644
index a55f6b4b1b..0000000000
--- a/packages/next/tests/actions/cart.test.ts
+++ /dev/null
@@ -1,389 +0,0 @@
-import { describe, it, expect, beforeEach, vi } from 'vitest';
-import { mockCookieStore } from '../setup';
-import { initSpreeNext, resetClient } from '../../src/config';
-
-// Mock the SDK client
-const mockClient = {
- carts: {
- get: vi.fn(),
- list: vi.fn(),
- create: vi.fn(),
- update: vi.fn(),
- complete: vi.fn(),
- associate: vi.fn(),
- items: {
- create: vi.fn(),
- update: vi.fn(),
- delete: vi.fn(),
- },
- fulfillments: {
- update: vi.fn(),
- },
- discountCodes: {
- apply: vi.fn(),
- remove: vi.fn(),
- },
- giftCards: {
- apply: vi.fn(),
- remove: vi.fn(),
- },
- },
-};
-
-vi.mock('@spree/sdk', () => ({
- createClient: vi.fn(() => mockClient),
-}));
-
-import {
- getCart, getOrCreateCart, addItem, updateItem, removeItem, clearCart, associateCart,
- updateCart, selectDeliveryRate, applyDiscountCode, removeDiscountCode, applyGiftCard, removeGiftCard, complete,
-} from '../../src/actions/cart';
-import { revalidateTag } from 'next/cache';
-
-// Cookie names used by the actions:
-// _spree_cart_token → getCartToken()
-// _spree_cart_token_id → getCartId()
-// _spree_jwt → getAccessToken()
-
-function mockCookies(values: Record<string, string | undefined>) {
- mockCookieStore.get.mockImplementation((name: string) => {
- const val = values[name];
- return val ? { value: val } : undefined;
- });
-}
-
-describe('cart actions', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- resetClient();
- initSpreeNext({ baseUrl: 'https://api.test.com', publishableKey: 'pk_test' });
- });
-
- describe('getCart', () => {
- it('returns null when no tokens exist', async () => {
- mockCookies({});
- const cart = await getCart();
- expect(cart).toBeNull();
- });
-
- it('returns cart when cart ID and token exist', async () => {
- const mockCart = { id: 'cart_1', token: 'order_abc', items: [] };
- mockCookies({
- '_spree_cart_token': 'order_abc',
- '_spree_cart_token_id': 'cart_1',
- });
- mockClient.carts.get.mockResolvedValue(mockCart);
-
- const cart = await getCart();
- expect(cart).toEqual(mockCart);
- expect(mockClient.carts.get).toHaveBeenCalledWith(
- 'cart_1',
- expect.objectContaining({ spreeToken: 'order_abc' })
- );
- });
-
- it('returns null when cart fetch fails', async () => {
- mockCookies({
- '_spree_cart_token': 'bad_token',
- '_spree_cart_token_id': 'cart_1',
- });
- mockClient.carts.get.mockRejectedValue(new Error('Not found'));
-
- const cart = await getCart();
- expect(cart).toBeNull();
- });
- });
-
- describe('getOrCreateCart', () => {
- it('returns existing cart if available', async () => {
- const mockCart = { id: 'cart_1', token: 'existing', items: [] };
- mockCookies({
- '_spree_cart_token': 'existing',
- '_spree_cart_token_id': 'cart_1',
- });
- mockClient.carts.get.mockResolvedValue(mockCart);
-
- const cart = await getOrCreateCart();
- expect(cart).toEqual(mockCart);
- expect(mockClient.carts.create).not.toHaveBeenCalled();
- });
-
- it('creates new cart when none exists', async () => {
- const newCart = { id: 'cart_2', token: 'new_token', items: [] };
- mockCookies({});
- mockClient.carts.create.mockResolvedValue(newCart);
-
- const cart = await getOrCreateCart();
- expect(cart).toEqual(newCart);
- expect(mockClient.carts.create).toHaveBeenCalled();
- expect(mockCookieStore.set).toHaveBeenCalledWith(
- '_spree_cart_token',
- 'new_token',
- expect.any(Object)
- );
- expect(mockCookieStore.set).toHaveBeenCalledWith(
- '_spree_cart_token_id',
- 'cart_2',
- expect.any(Object)
- );
- });
- });
-
- describe('addItem', () => {
- it('adds item and invalidates cache', async () => {
- const mockCart = { id: 'cart_1', token: 'cart_token', items: [] };
- const updatedCart = { id: 'cart_1', token: 'cart_token', items: [{ id: 'li_1' }] };
- mockCookies({
- '_spree_cart_token': 'cart_token',
- '_spree_cart_token_id': 'cart_1',
- });
- mockClient.carts.get.mockResolvedValue(mockCart);
- mockClient.carts.items.create.mockResolvedValue(updatedCart);
-
- const result = await addItem('v1', 2);
- expect(result).toEqual(updatedCart);
- expect(mockClient.carts.items.create).toHaveBeenCalledWith(
- 'cart_1',
- { variant_id: 'v1', quantity: 2, metadata: undefined },
- expect.objectContaining({ spreeToken: 'cart_token' })
- );
- expect(revalidateTag).toHaveBeenCalledWith('cart');
- });
- });
-
- describe('updateItem', () => {
- it('updates item and invalidates cache', async () => {
- const updatedCart = { id: 'cart_1', token: 'cart_token', total_quantity: 3 };
- mockCookies({
- '_spree_cart_token': 'cart_token',
- '_spree_cart_token_id': 'cart_1',
- });
- mockClient.carts.items.update.mockResolvedValue(updatedCart);
-
- const result = await updateItem('li_1', { quantity: 3 });
- expect(result).toEqual(updatedCart);
- expect(mockClient.carts.items.update).toHaveBeenCalledWith(
- 'cart_1',
- 'li_1',
- { quantity: 3 },
- expect.objectContaining({ spreeToken: 'cart_token' })
- );
- expect(revalidateTag).toHaveBeenCalledWith('cart');
- });
- });
-
- describe('removeItem', () => {
- it('removes item and invalidates cache', async () => {
- const updatedCart = { id: 'cart_1', token: 'cart_token', total_quantity: 0 };
- mockCookies({
- '_spree_cart_token': 'cart_token',
- '_spree_cart_token_id': 'cart_1',
- });
- mockClient.carts.items.delete.mockResolvedValue(updatedCart);
-
- const result = await removeItem('li_1');
- expect(result).toEqual(updatedCart);
- expect(mockClient.carts.items.delete).toHaveBeenCalledWith(
- 'cart_1',
- 'li_1',
- expect.objectContaining({ spreeToken: 'cart_token' })
- );
- expect(revalidateTag).toHaveBeenCalledWith('cart');
- });
- });
-
- describe('clearCart', () => {
- it('clears cart cookies and invalidates cache', async () => {
- await clearCart();
- expect(mockCookieStore.set).toHaveBeenCalledWith(
- '_spree_cart_token',
- '',
- expect.objectContaining({ maxAge: -1 })
- );
- expect(mockCookieStore.set).toHaveBeenCalledWith(
- '_spree_cart_token_id',
- '',
- expect.objectContaining({ maxAge: -1 })
- );
- expect(revalidateTag).toHaveBeenCalledWith('cart');
- });
- });
-
- describe('associateCart', () => {
- it('returns null when no cart ID', async () => {
- mockCookies({});
- const result = await associateCart();
- expect(result).toBeNull();
- });
-
- it('associates cart when cart ID and JWT exist', async () => {
- const mockCart = { id: 'cart_1', token: 'cart_token' };
- mockCookies({
- '_spree_cart_token': 'cart_token',
- '_spree_cart_token_id': 'cart_1',
- '_spree_jwt': 'jwt_token',
- });
- mockClient.carts.associate.mockResolvedValue(mockCart);
-
- const result = await associateCart();
- expect(result).toEqual(mockCart);
- expect(mockClient.carts.associate).toHaveBeenCalledWith(
- 'cart_1',
- { spreeToken: 'cart_token', token: 'jwt_token' }
- );
- });
- });
-
- describe('updateCart', () => {
- it('updates cart and revalidates', async () => {
- const updatedCart = { id: 'cart_1', number: 'R123' };
- const params = { email: '[email protected]' };
- mockCookies({
- '_spree_cart_token': 'order_token',
- '_spree_cart_token_id': 'cart_1',
- '_spree_jwt': 'jwt_token',
- });
- mockClient.carts.update.mockResolvedValue(updatedCart);
-
- const result = await updateCart(params);
- expect(result).toEqual(updatedCart);
- expect(mockClient.carts.update).toHaveBeenCalledWith(
- 'cart_1',
- params,
- { spreeToken: 'order_token', token: 'jwt_token' }
- );
- expect(revalidateTag).toHaveBeenCalledWith('checkout');
- });
- });
-
- describe('selectDeliveryRate', () => {
- it('selects delivery rate and revalidates', async () => {
- const updatedCart = { id: 'cart_1', delivery_total: '10.0' };
- mockCookies({
- '_spree_cart_token': 'order_token',
- '_spree_cart_token_id': 'cart_1',
- '_spree_jwt': 'jwt_token',
- });
- mockClient.carts.fulfillments.update.mockResolvedValue(updatedCart);
-
- const result = await selectDeliveryRate('ful_1', 'dr_1');
- expect(result).toEqual(updatedCart);
- expect(mockClient.carts.fulfillments.update).toHaveBeenCalledWith(
- 'cart_1',
- 'ful_1',
- { selected_delivery_rate_id: 'dr_1' },
- { spreeToken: 'order_token', token: 'jwt_token' }
- );
- expect(revalidateTag).toHaveBeenCalledWith('checkout');
- });
- });
-
- describe('applyDiscountCode', () => {
- it('applies discount code and revalidates checkout and cart', async () => {
- const updatedCart = { id: 'cart_1', discount_total: -10 };
- mockCookies({
- '_spree_cart_token': 'order_token',
- '_spree_cart_token_id': 'cart_1',
- '_spree_jwt': 'jwt_token',
- });
- mockClient.carts.discountCodes.apply.mockResolvedValue(updatedCart);
-
- const result = await applyDiscountCode('SAVE10');
- expect(result).toEqual(updatedCart);
- expect(mockClient.carts.discountCodes.apply).toHaveBeenCalledWith(
- 'cart_1',
- 'SAVE10',
- { spreeToken: 'order_token', token: 'jwt_token' }
- );
- expect(revalidateTag).toHaveBeenCalledWith('checkout');
- expect(revalidateTag).toHaveBeenCalledWith('cart');
- });
- });
-
- describe('removeDiscountCode', () => {
- it('removes discount code and revalidates checkout and cart', async () => {
- const updatedCart = { id: 'cart_1', discount_total: 0 };
- mockCookies({
- '_spree_cart_token': 'order_token',
- '_spree_cart_token_id': 'cart_1',
- '_spree_jwt': 'jwt_token',
- });
- mockClient.carts.discountCodes.remove.mockResolvedValue(updatedCart);
-
- const result = await removeDiscountCode('SAVE10');
- expect(result).toEqual(updatedCart);
- expect(mockClient.carts.discountCodes.remove).toHaveBeenCalledWith(
- 'cart_1',
- 'SAVE10',
- { spreeToken: 'order_token', token: 'jwt_token' }
- );
- expect(revalidateTag).toHaveBeenCalledWith('checkout');
- expect(revalidateTag).toHaveBeenCalledWith('cart');
- });
- });
-
- describe('applyGiftCard', () => {
- it('applies gift card and revalidates checkout and cart', async () => {
- const updatedCart = { id: 'cart_1', gift_card_total: '50.0', amount_due: '59.08' };
- mockCookies({
- '_spree_cart_token': 'order_token',
- '_spree_cart_token_id': 'cart_1',
- '_spree_jwt': 'jwt_token',
- });
- mockClient.carts.giftCards.apply.mockResolvedValue(updatedCart);
-
- const result = await applyGiftCard('GC-ABCD-1234');
- expect(result).toEqual(updatedCart);
- expect(mockClient.carts.giftCards.apply).toHaveBeenCalledWith(
- 'cart_1',
- 'GC-ABCD-1234',
- { spreeToken: 'order_token', token: 'jwt_token' }
- );
- expect(revalidateTag).toHaveBeenCalledWith('checkout');
- expect(revalidateTag).toHaveBeenCalledWith('cart');
- });
- });
-
- describe('removeGiftCard', () => {
- it('removes gift card and revalidates checkout and cart', async () => {
- const updatedCart = { id: 'cart_1', gift_card_total: '0.0', amount_due: '109.08' };
- mockCookies({
- '_spree_cart_token': 'order_token',
- '_spree_cart_token_id': 'cart_1',
- '_spree_jwt': 'jwt_token',
- });
- mockClient.carts.giftCards.remove.mockResolvedValue(updatedCart);
-
- const result = await removeGiftCard('gc_abc123');
- expect(result).toEqual(updatedCart);
- expect(mockClient.carts.giftCards.remove).toHaveBeenCalledWith(
- 'cart_1',
- 'gc_abc123',
- { spreeToken: 'order_token', token: 'jwt_token' }
- );
- expect(revalidateTag).toHaveBeenCalledWith('checkout');
- expect(revalidateTag).toHaveBeenCalledWith('cart');
- });
- });
-
- describe('complete', () => {
- it('completes checkout and revalidates', async () => {
- const mockOrder = { id: 'cart_1', state: 'complete' };
- mockCookies({
- '_spree_cart_token': 'order_token',
- '_spree_cart_token_id': 'cart_1',
- '_spree_jwt': 'jwt_token',
- });
- mockClient.carts.complete.mockResolvedValue(mockOrder);
-
- const result = await complete();
- expect(result).toEqual(mockOrder);
- expect(mockClient.carts.complete).toHaveBeenCalledWith(
- 'cart_1',
- { spreeToken: 'order_token', token: 'jwt_token' }
- );
- expect(revalidateTag).toHaveBeenCalledWith('checkout');
- expect(revalidateTag).toHaveBeenCalledWith('cart');
- });
- });
-});
diff --git a/packages/next/tests/actions/credit-cards.test.ts b/packages/next/tests/actions/credit-cards.test.ts
deleted file mode 100644
index 9c99fe6b28..0000000000
--- a/packages/next/tests/actions/credit-cards.test.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-import { describe, it, expect, beforeEach, vi } from 'vitest';
-import { mockCookieStore } from '../setup';
-import { initSpreeNext, resetClient } from '../../src/config';
-
-const mockClient = {
- customer: {
- creditCards: {
- list: vi.fn(),
- delete: vi.fn(),
- },
- },
- auth: {
- refresh: vi.fn(),
- },
-};
-
-vi.mock('@spree/sdk', () => ({
- createClient: vi.fn(() => mockClient),
- SpreeError: class SpreeError extends Error {
- public readonly status: number;
- constructor(response: { error: { message: string } }, status: number) {
- super(response.error.message);
- this.status = status;
- }
- },
-}));
-
-import { listCreditCards, deleteCreditCard } from '../../src/actions/credit-cards';
-import { revalidateTag } from 'next/cache';
-
-// Create a JWT that expires far in the future
-function makeFutureJwt(): string {
- const payload = { exp: Math.floor(Date.now() / 1000) + 86400 };
- return `header.${btoa(JSON.stringify(payload))}.signature`;
-}
-
-describe('credit card actions', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- resetClient();
- initSpreeNext({ baseUrl: 'https://api.test.com', publishableKey: 'pk_test' });
- mockCookieStore.get.mockReturnValue({ value: makeFutureJwt() });
- });
-
- describe('listCreditCards', () => {
- it('returns credit cards list', async () => {
- const mockCards = { data: [{ id: '1', last4: '4242' }] };
- mockClient.customer.creditCards.list.mockResolvedValue(mockCards);
-
- const result = await listCreditCards();
- expect(result).toEqual(mockCards);
- expect(mockClient.customer.creditCards.list).toHaveBeenCalledWith(
- undefined,
- expect.objectContaining({ token: expect.any(String) })
- );
- });
- });
-
- describe('deleteCreditCard', () => {
- it('deletes card and revalidates', async () => {
- mockClient.customer.creditCards.delete.mockResolvedValue(undefined);
-
- await deleteCreditCard('1');
- expect(mockClient.customer.creditCards.delete).toHaveBeenCalledWith(
- '1',
- expect.objectContaining({ token: expect.any(String) })
- );
- expect(revalidateTag).toHaveBeenCalledWith('credit-cards');
- });
- });
-
- describe('when not authenticated', () => {
- it('throws error', async () => {
- mockCookieStore.get.mockReturnValue(undefined);
- await expect(listCreditCards()).rejects.toThrow('Not authenticated');
- });
- });
-});
diff --git a/packages/next/tests/actions/gift-cards.test.ts b/packages/next/tests/actions/gift-cards.test.ts
deleted file mode 100644
index 5770b1d76a..0000000000
--- a/packages/next/tests/actions/gift-cards.test.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-import { describe, it, expect, beforeEach, vi } from 'vitest';
-import { mockCookieStore } from '../setup';
-import { initSpreeNext, resetClient } from '../../src/config';
-
-const mockClient = {
- customer: {
- giftCards: {
- list: vi.fn(),
- get: vi.fn(),
- },
- },
- auth: {
- refresh: vi.fn(),
- },
-};
-
-vi.mock('@spree/sdk', () => ({
- createClient: vi.fn(() => mockClient),
- SpreeError: class SpreeError extends Error {
- public readonly status: number;
- constructor(response: { error: { message: string } }, status: number) {
- super(response.error.message);
- this.status = status;
- }
- },
-}));
-
-import { listGiftCards, getGiftCard } from '../../src/actions/gift-cards';
-
-// Create a JWT that expires far in the future
-function makeFutureJwt(): string {
- const payload = { exp: Math.floor(Date.now() / 1000) + 86400 };
- return `header.${btoa(JSON.stringify(payload))}.signature`;
-}
-
-describe('gift card actions', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- resetClient();
- initSpreeNext({ baseUrl: 'https://api.test.com', publishableKey: 'pk_test' });
- mockCookieStore.get.mockReturnValue({ value: makeFutureJwt() });
- });
-
- describe('listGiftCards', () => {
- it('returns gift cards list', async () => {
- const mockCards = { data: [{ id: '1', code: 'GIFT100', balance: 100 }] };
- mockClient.customer.giftCards.list.mockResolvedValue(mockCards);
-
- const result = await listGiftCards();
- expect(result).toEqual(mockCards);
- expect(mockClient.customer.giftCards.list).toHaveBeenCalledWith(
- undefined,
- expect.objectContaining({ token: expect.any(String) })
- );
- });
- });
-
- describe('getGiftCard', () => {
- it('returns a single gift card', async () => {
- const mockCard = { id: '1', code: 'GIFT100', balance: 100 };
- mockClient.customer.giftCards.get.mockResolvedValue(mockCard);
-
- const result = await getGiftCard('1');
- expect(result).toEqual(mockCard);
- expect(mockClient.customer.giftCards.get).toHaveBeenCalledWith(
- '1',
- expect.objectContaining({ token: expect.any(String) })
- );
- });
- });
-
- describe('when not authenticated', () => {
- it('throws error', async () => {
- mockCookieStore.get.mockReturnValue(undefined);
- await expect(listGiftCards()).rejects.toThrow('Not authenticated');
- });
- });
-});
diff --git a/packages/next/tests/actions/orders.test.ts b/packages/next/tests/actions/orders.test.ts
deleted file mode 100644
index 3a97d764b5..0000000000
--- a/packages/next/tests/actions/orders.test.ts
+++ /dev/null
@@ -1,109 +0,0 @@
-import { describe, it, expect, beforeEach, vi } from 'vitest';
-import { mockCookieStore } from '../setup';
-import { initSpreeNext, resetClient } from '../../src/config';
-
-const mockClient = {
- orders: {
- get: vi.fn(),
- },
- customer: {
- orders: {
- list: vi.fn(),
- },
- },
- auth: {
- refresh: vi.fn(),
- },
-};
-
-vi.mock('@spree/sdk', () => ({
- createClient: vi.fn(() => mockClient),
- SpreeError: class SpreeError extends Error {
- public readonly status: number;
- constructor(response: { error: { message: string } }, status: number) {
- super(response.error.message);
- this.status = status;
- }
- },
-}));
-
-import { listOrders, getOrder } from '../../src/actions/orders';
-
-// Create a JWT that expires far in the future
-function makeFutureJwt(): string {
- const payload = { exp: Math.floor(Date.now() / 1000) + 86400 };
- return `header.${btoa(JSON.stringify(payload))}.signature`;
-}
-
-describe('order actions', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- resetClient();
- initSpreeNext({ baseUrl: 'https://api.test.com', publishableKey: 'pk_test' });
- mockCookieStore.get.mockReturnValue({ value: makeFutureJwt() });
- });
-
- describe('listOrders', () => {
- it('returns paginated orders', async () => {
- const mockResponse = {
- data: [{ id: '1', number: 'R001' }],
- meta: { total_count: 1, total_pages: 1 },
- };
- mockClient.customer.orders.list.mockResolvedValue(mockResponse);
-
- const result = await listOrders({ page: 1 });
- expect(result).toEqual(mockResponse);
- expect(mockClient.customer.orders.list).toHaveBeenCalledWith(
- { page: 1 },
- expect.objectContaining({ token: expect.any(String) })
- );
- });
-
- it('works without params', async () => {
- const mockResponse = { data: [], meta: { total_count: 0, total_pages: 0 } };
- mockClient.customer.orders.list.mockResolvedValue(mockResponse);
-
- const result = await listOrders();
- expect(result).toEqual(mockResponse);
- expect(mockClient.customer.orders.list).toHaveBeenCalledWith(
- undefined,
- expect.objectContaining({ token: expect.any(String) })
- );
- });
- });
-
- describe('getOrder', () => {
- it('returns a single order by id', async () => {
- const mockOrder = { id: '1', number: 'R001', state: 'complete' };
- mockClient.orders.get.mockResolvedValue(mockOrder);
-
- const result = await getOrder('1');
- expect(result).toEqual(mockOrder);
- expect(mockClient.orders.get).toHaveBeenCalledWith(
- '1',
- undefined,
- expect.objectContaining({ token: expect.any(String) })
- );
- });
-
- it('passes params through', async () => {
- const mockOrder = { id: '1', number: 'R001' };
- mockClient.orders.get.mockResolvedValue(mockOrder);
-
- const result = await getOrder('R001', { expand: ['line_items'] });
- expect(result).toEqual(mockOrder);
- expect(mockClient.orders.get).toHaveBeenCalledWith(
- 'R001',
- { expand: ['line_items'] },
- expect.objectContaining({ token: expect.any(String) })
- );
- });
- });
-
- describe('when not authenticated', () => {
- it('throws error', async () => {
- mockCookieStore.get.mockReturnValue(undefined);
- await expect(listOrders()).rejects.toThrow('Not authenticated');
- });
- });
-});
diff --git a/packages/next/tests/actions/payment-sessions.test.ts b/packages/next/tests/actions/payment-sessions.test.ts
deleted file mode 100644
index efceb07817..0000000000
--- a/packages/next/tests/actions/payment-sessions.test.ts
+++ /dev/null
@@ -1,125 +0,0 @@
-import { describe, it, expect, beforeEach, vi } from 'vitest';
-import { mockCookieStore } from '../setup';
-import { initSpreeNext, resetClient } from '../../src/config';
-
-const mockClient = {
- carts: {
- paymentSessions: {
- create: vi.fn(),
- get: vi.fn(),
- update: vi.fn(),
- complete: vi.fn(),
- },
- },
-};
-
-vi.mock('@spree/sdk', () => ({
- createClient: vi.fn(() => mockClient),
-}));
-
-import {
- createPaymentSession,
- getPaymentSession,
- updatePaymentSession,
- completePaymentSession,
-} from '../../src/actions/payment-sessions';
-import { revalidateTag } from 'next/cache';
-
-function mockCookies(values: Record<string, string | undefined>) {
- mockCookieStore.get.mockImplementation((name: string) => {
- const val = values[name];
- return val ? { value: val } : undefined;
- });
-}
-
-describe('payment session actions', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- resetClient();
- initSpreeNext({ baseUrl: 'https://api.test.com', publishableKey: 'pk_test' });
- mockCookies({
- '_spree_cart_token': 'order_token_123',
- '_spree_cart_token_id': 'cart_1',
- '_spree_jwt': 'jwt_token_abc',
- });
- });
-
- describe('createPaymentSession', () => {
- it('creates a payment session and revalidates checkout', async () => {
- const mockSession = { id: 'ps_1', status: 'pending', payment_method_id: 'pm_1' };
- mockClient.carts.paymentSessions.create.mockResolvedValue(mockSession);
-
- const result = await createPaymentSession({ payment_method_id: 'pm_1' });
- expect(result).toEqual(mockSession);
- expect(mockClient.carts.paymentSessions.create).toHaveBeenCalledWith(
- 'cart_1',
- { payment_method_id: 'pm_1' },
- { spreeToken: 'order_token_123', token: 'jwt_token_abc' }
- );
- expect(revalidateTag).toHaveBeenCalledWith('checkout');
- });
- });
-
- describe('getPaymentSession', () => {
- it('returns a payment session by ID', async () => {
- const mockSession = { id: 'ps_1', status: 'pending', amount: '99.99' };
- mockClient.carts.paymentSessions.get.mockResolvedValue(mockSession);
-
- const result = await getPaymentSession('ps_1');
- expect(result).toEqual(mockSession);
- expect(mockClient.carts.paymentSessions.get).toHaveBeenCalledWith(
- 'cart_1',
- 'ps_1',
- { spreeToken: 'order_token_123', token: 'jwt_token_abc' }
- );
- });
- });
-
- describe('updatePaymentSession', () => {
- it('updates a payment session and revalidates checkout', async () => {
- const mockSession = { id: 'ps_1', status: 'pending', amount: '50.00' };
- mockClient.carts.paymentSessions.update.mockResolvedValue(mockSession);
-
- const result = await updatePaymentSession('ps_1', { amount: '50.00' });
- expect(result).toEqual(mockSession);
- expect(mockClient.carts.paymentSessions.update).toHaveBeenCalledWith(
- 'cart_1',
- 'ps_1',
- { amount: '50.00' },
- { spreeToken: 'order_token_123', token: 'jwt_token_abc' }
- );
- expect(revalidateTag).toHaveBeenCalledWith('checkout');
- });
- });
-
- describe('completePaymentSession', () => {
- it('completes a payment session and revalidates checkout', async () => {
- const mockSession = { id: 'ps_1', status: 'completed' };
- mockClient.carts.paymentSessions.complete.mockResolvedValue(mockSession);
-
- const result = await completePaymentSession('ps_1', { session_result: 'success' });
- expect(result).toEqual(mockSession);
- expect(mockClient.carts.paymentSessions.complete).toHaveBeenCalledWith(
- 'cart_1',
- 'ps_1',
- { session_result: 'success' },
- { spreeToken: 'order_token_123', token: 'jwt_token_abc' }
- );
- expect(revalidateTag).toHaveBeenCalledWith('checkout');
- });
-
- it('completes without params', async () => {
- const mockSession = { id: 'ps_1', status: 'completed' };
- mockClient.carts.paymentSessions.complete.mockResolvedValue(mockSession);
-
- const result = await completePaymentSession('ps_1');
- expect(result).toEqual(mockSession);
- expect(mockClient.carts.paymentSessions.complete).toHaveBeenCalledWith(
- 'cart_1',
- 'ps_1',
- undefined,
- { spreeToken: 'order_token_123', token: 'jwt_token_abc' }
- );
- });
- });
-});
diff --git a/packages/next/tsconfig.json b/packages/next/tsconfig.json
index a0e8cc61ca..c816b38d4e 100644
--- a/packages/next/tsconfig.json
+++ b/packages/next/tsconfig.json
@@ -5,7 +5,6 @@
"moduleResolution": "bundler",
"lib": ["ES2022"],
"types": ["node"],
- "ignoreDeprecations": "6.0",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
diff --git a/packages/next/tsup.config.ts b/packages/next/tsup.config.ts
index 545f8758c4..c5b1d57669 100644
--- a/packages/next/tsup.config.ts
+++ b/packages/next/tsup.config.ts
@@ -1,19 +1,15 @@
import { defineConfig } from 'tsup';
export default defineConfig([
- // Plain modules (no directive) — config, types, data reads
+ // Core modules — config, types, auth helpers, cookies, locale
{
entry: {
index: 'src/index.ts',
config: 'src/config.ts',
types: 'src/types.ts',
locale: 'src/locale.ts',
- 'data/products': 'src/data/products.ts',
- 'data/categories': 'src/data/categories.ts',
- 'data/countries': 'src/data/countries.ts',
- 'data/currencies': 'src/data/currencies.ts',
- 'data/locales': 'src/data/locales.ts',
- 'data/markets': 'src/data/markets.ts',
+ 'auth-helpers': 'src/auth-helpers.ts',
+ cookies: 'src/cookies.ts',
},
format: ['esm'],
dts: true,
@@ -22,25 +18,6 @@ export default defineConfig([
treeshake: true,
external: ['next', 'next/cache', 'next/headers', '@spree/sdk', 'react'],
},
- // Server action files — need "use server" banner preserved
- {
- entry: {
- 'actions/cart': 'src/actions/cart.ts',
- 'actions/auth': 'src/actions/auth.ts',
- 'actions/addresses': 'src/actions/addresses.ts',
- 'actions/orders': 'src/actions/orders.ts',
- 'actions/credit-cards': 'src/actions/credit-cards.ts',
- 'actions/gift-cards': 'src/actions/gift-cards.ts',
- 'actions/payment-sessions': 'src/actions/payment-sessions.ts',
- 'actions/payment-setup-sessions': 'src/actions/payment-setup-sessions.ts',
- 'actions/locale': 'src/actions/locale.ts',
- },
- format: ['esm'],
- dts: true,
- splitting: false,
- sourcemap: true,
- external: ['next', 'next/cache', 'next/headers', '@spree/sdk', 'react'],
- },
// Middleware — separate entry (Edge runtime, no next/headers)
{
entry: {