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.

Add channel setting to Store SDK

Damian Legawiecb3cadc7c4e8b
diff --git a/docs/developer/core-concepts/channels.mdx b/docs/developer/core-concepts/channels.mdx
index 37406c67b0..c0eb3af06b 100644
--- a/docs/developer/core-concepts/channels.mdx
+++ b/docs/developer/core-concepts/channels.mdx
@@ -1,5 +1,5 @@
---
-title: Sales Channels
+title: Channels
description: Per-store distribution surfaces — online storefront, POS, marketplace, wholesale — each with its own product catalog and order attribution.
---
@@ -9,7 +9,7 @@ import { Since } from '/snippets/since.mdx';
## Overview
-Sales channels segment a single [Store](/developer/core-concepts/stores) into distinct selling surfaces. A channel represents *where* an order originates from — the online storefront, an in-person point-of-sale till, a marketplace integration (Amazon, eBay), a B2B wholesale portal, a mobile app — and *which* subset of the store's products is available there.
+Channels segment a single [Store](/developer/core-concepts/stores) into distinct selling surfaces. A channel represents *where* an order originates from — the online storefront, an in-person point-of-sale till, a marketplace integration (Amazon, eBay), a B2B wholesale portal, a mobile app — and *which* subset of the store's products is available there.
Every store ships with one default channel named *Online Store*. You can add more from **Settings → Sales channels** in the admin dashboard.
@@ -31,11 +31,42 @@ Every store ships with one default channel named *Online Store*. You can add mor
Every incoming Store API or storefront request resolves to a channel:
-1. If the `X-Spree-Channel` header is present and matches a channel `code` on the current store, that channel is used.
+1. If the `X-Spree-Channel` header is present, the value is matched against `channels.code` — or `channels.id` when the value looks like a prefixed ID (`ch_…`) — scoped to the current store.
2. Otherwise, the store's default channel is used.
The resolved channel is then available to controllers, models, and serializers throughout the request.
+### Selecting a channel from the Store SDK
+
+The Store SDK sends `X-Spree-Channel` on every request when configured. The value can be either the channel `code` (merchant-meaningful, recommended) or the prefixed ID (`ch_…`).
+
+<CodeGroup>
+
+```typescript SDK
+// Client-level default
+const client = createClient({
+ baseUrl: 'https://api.mystore.com',
+ publishableKey: 'pk_xxx',
+ channel: 'pos',
+})
+
+// Sticky setter (mirrors setLocale / setCurrency / setCountry)
+client.setChannel('wholesale')
+
+// Per-request override
+const products = await client.products.list({}, { channel: 'pos' })
+```
+
+```bash cURL
+curl 'https://api.mystore.com/api/v3/store/products' \
+ -H 'X-Spree-API-Key: pk_xxx' \
+ -H 'X-Spree-Channel: pos'
+```
+
+</CodeGroup>
+
+The Admin API does not consume `X-Spree-Channel` — admin endpoints return data across all channels for the current store. Filter by channel on the admin side via Ransack (`q[channel_id_eq]=ch_xxx` for orders, `q[channels_id_in][]=ch_xxx` for products).
+
### Product visibility
A product is visible on a channel only when it has a publication record joining the two. Each publication carries an optional window:
@@ -74,8 +105,10 @@ Three endpoints cover the publishing surface:
| `POST /api/v3/admin/channels/:id/remove_products` | Unpublish products from a specific channel |
| `POST /api/v3/admin/products/bulk_add_to_channels` | Publish many products across many channels in a single request |
+<CodeGroup>
+
```typescript SDK
-await client.channels.addProducts('ch_xxx', {
+await adminClient.channels.addProducts('ch_xxx', {
product_ids: ['prod_aaa', 'prod_bbb'],
// Optional window — when omitted, existing schedules are preserved
published_at: '2026-07-01T00:00:00Z',
@@ -83,12 +116,27 @@ await client.channels.addProducts('ch_xxx', {
})
```
+```bash cURL
+curl -X POST 'https://api.mystore.com/api/v3/admin/channels/ch_xxx/add_products' \
+ -H 'X-Spree-API-Key: sk_xxx' \
+ -H 'Content-Type: application/json' \
+ -d '{
+ "product_ids": ["prod_aaa", "prod_bbb"],
+ "published_at": "2026-07-01T00:00:00Z",
+ "unpublished_at": "2026-12-31T23:59:59Z"
+ }'
+```
+
+</CodeGroup>
+
`channels.addProducts` is idempotent: re-publishing an already-published product is a no-op for its window unless `published_at` / `unpublished_at` are explicitly passed. Cross-store onboarding is allowed when the caller's key has update permission on the product.
For per-product updates, use `PATCH /api/v3/admin/products/:id` with a `product_publications` array:
+<CodeGroup>
+
```typescript SDK
-await client.products.update('prod_xxx', {
+await adminClient.products.update('prod_xxx', {
product_publications: [
{ channel_id: 'ch_online' },
{ channel_id: 'ch_pos', published_at: '2026-07-01T00:00:00Z' },
@@ -96,11 +144,25 @@ await client.products.update('prod_xxx', {
})
```
+```bash cURL
+curl -X PATCH 'https://api.mystore.com/api/v3/admin/products/prod_xxx' \
+ -H 'X-Spree-API-Key: sk_xxx' \
+ -H 'Content-Type: application/json' \
+ -d '{
+ "product_publications": [
+ { "channel_id": "ch_online" },
+ { "channel_id": "ch_pos", "published_at": "2026-07-01T00:00:00Z" }
+ ]
+ }'
+```
+
+</CodeGroup>
+
The write contract is **full-set**: the array represents the complete desired state. Channels absent from the payload are detached.
## Auto-Publish Behavior
-- **Dashboard** — new products are auto-published on the store's default channel, matching Shopify's "Online Store" behavior. The merchant can untick channels via the Publishing card post-create.
+- **Dashboard** — new products are auto-published on the store's default channel. The merchant can untick channels via the Publishing card post-create.
- **Admin API** — new products are **not** auto-published. The caller supplies `product_publications: [{ channel_id }]` on create, or calls `POST /admin/channels/:id/add_products` afterwards.
- **Sample data** (`bin/rake spree:load_sample_data`) — all loaded products are explicitly published on the default channel.
diff --git a/docs/developer/core-concepts/products.mdx b/docs/developer/core-concepts/products.mdx
index 4b4008c744..76db3c3ca8 100644
--- a/docs/developer/core-concepts/products.mdx
+++ b/docs/developer/core-concepts/products.mdx
@@ -3,6 +3,8 @@ title: Products
description: Products, variants, option types, images, prices, and categories
---
+import { Since } from '/snippets/since.mdx';
+
## Overview
A product represents something you sell. Each product has one or more **variants** — the actual purchasable items with their own SKU, price, and inventory. For example, a "T-Shirt" product might have variants for each size and color combination.
@@ -372,8 +374,157 @@ curl 'https://api.mystore.com/api/v3/store/categories/clothing/shirts/products?l
Category `name` and `description` fields are translatable.
</Info>
+## Publications and Sales Channels <Since version="5.5" />
+
+A product is visible on a [Channel](/developer/core-concepts/channels) only when a `ProductPublication` record joins the two. Publications carry an optional time window so a product can be scheduled to go live and come down without code or manual toggles.
+
+| Publication state | What customers see |
+|---|---|
+| No publication exists | Product is not on this channel — invisible |
+| Publication has no dates set | Live now and indefinitely |
+| `published_at` is in the future | Scheduled — not yet visible |
+| `unpublished_at` is in the past | Hidden — was visible, now sunset |
+| Within the window | Live |
+
+Product `status` (`draft` / `active` / `archived`) is the **outer gate**: a Draft or Archived product is hidden on every channel regardless of its publication window. Only `active` products consult publication state.
+
+### Reading publications
+
+Publications appear in the API under `product_publications` when expanded; the same data is available through the `channels` association as a flat list of joined channels.
+
+<CodeGroup>
+
+```typescript SDK
+const product = await adminClient.products.get('prod_abc', {
+ expand: ['product_publications', 'channels'],
+})
+```
+
+```bash cURL
+curl 'https://api.mystore.com/api/v3/admin/products/prod_abc?expand=product_publications,channels' \
+ -H 'X-Spree-API-Key: sk_xxx'
+```
+
+</CodeGroup>
+
+```json Response
+{
+ "data": {
+ "id": "prod_abc",
+ "status": "active",
+ "channels": [
+ { "id": "ch_online", "code": "online", "name": "Online Store" }
+ ],
+ "product_publications": [
+ {
+ "id": "pp_xyz",
+ "channel_id": "ch_online",
+ "published_at": "2026-07-01T00:00:00Z",
+ "unpublished_at": null
+ }
+ ]
+ }
+}
+```
+
+### Writing publications
+
+Two write surfaces serve different shapes:
+
+- **Per-product, full-set** — `PATCH /api/v3/admin/products/{id}` with a `product_publications` array. The array represents the complete desired state; channels absent from the payload are detached.
+
+ <CodeGroup>
+
+ ```typescript SDK
+ await adminClient.products.update('prod_abc', {
+ product_publications: [
+ { channel_id: 'ch_online' },
+ { channel_id: 'ch_pos', published_at: '2026-07-01T00:00:00Z' },
+ ],
+ })
+ ```
+
+ ```bash cURL
+ curl -X PATCH 'https://api.mystore.com/api/v3/admin/products/prod_abc' \
+ -H 'X-Spree-API-Key: sk_xxx' \
+ -H 'Content-Type: application/json' \
+ -d '{
+ "product_publications": [
+ { "channel_id": "ch_online" },
+ { "channel_id": "ch_pos", "published_at": "2026-07-01T00:00:00Z" }
+ ]
+ }'
+ ```
+
+ </CodeGroup>
+
+- **Per-channel, bulk** — `POST /api/v3/admin/channels/{id}/add_products` and `POST /api/v3/admin/channels/{id}/remove_products` for publishing or unpublishing many products at once. Idempotent: re-publishing an already-published product is a no-op for its window unless `published_at` / `unpublished_at` are explicitly passed.
+
+ <CodeGroup>
+
+ ```typescript SDK
+ await adminClient.channels.addProducts('ch_online', {
+ product_ids: ['prod_abc', 'prod_def'],
+ published_at: '2026-07-01T00:00:00Z',
+ })
+
+ await adminClient.channels.removeProducts('ch_online', {
+ product_ids: ['prod_abc'],
+ })
+ ```
+
+ ```bash cURL
+ curl -X POST 'https://api.mystore.com/api/v3/admin/channels/ch_online/add_products' \
+ -H 'X-Spree-API-Key: sk_xxx' \
+ -H 'Content-Type: application/json' \
+ -d '{
+ "product_ids": ["prod_abc", "prod_def"],
+ "published_at": "2026-07-01T00:00:00Z"
+ }'
+
+ curl -X POST 'https://api.mystore.com/api/v3/admin/channels/ch_online/remove_products' \
+ -H 'X-Spree-API-Key: sk_xxx' \
+ -H 'Content-Type: application/json' \
+ -d '{ "product_ids": ["prod_abc"] }'
+ ```
+
+ </CodeGroup>
+
+The two surfaces converge on the same `spree_product_publications` table — pick whichever matches your call site.
+
+### Listing products on a specific channel
+
+Storefronts and `client.products.list()` calls return only products published on the resolved channel (live within the publication window, with the product itself `active`). To scope a Store SDK request to a non-default channel — e.g. a POS app querying for the POS catalog — set the channel `code` on the client or per-request:
+
+<CodeGroup>
+
+```typescript SDK
+// Client-level default
+const client = createClient({ baseUrl, publishableKey, channel: 'pos' })
+
+// Per-request override
+const posProducts = await client.products.list({}, { channel: 'pos' })
+```
+
+```bash cURL
+curl 'https://api.mystore.com/api/v3/store/products' \
+ -H 'X-Spree-API-Key: pk_xxx' \
+ -H 'X-Spree-Channel: pos'
+```
+
+</CodeGroup>
+
+For Admin API filtering across channels (back-office reports, admin UI lists), use Ransack instead: `q[channels_id_in][]=ch_xxx`. See [Sales Channels](/developer/core-concepts/channels) for the resolution rules.
+
+### Auto-publish on the default channel
+
+When a product is created via the dashboard, it is auto-published on the store's default channel (the only channel where `default = true`). The Admin API does **not** auto-publish — supply `product_publications: [{ channel_id }]` on create or call `add_products` afterwards.
+
+See [Sales Channels](/developer/core-concepts/channels) for the full channel lifecycle, including default-channel resolution and the `X-Spree-Channel` header.
+
## Related Documentation
+- [Sales Channels](/developer/core-concepts/channels) — Channels, publications, and order attribution
- [Pricing](/developer/core-concepts/pricing) — Price Lists, Price Rules, and market-specific pricing
- [Inventory](/developer/core-concepts/inventory) — Stock management and backorders
- [Media](/developer/core-concepts/media) — Image management
diff --git a/docs/developer/sdk/configuration.mdx b/docs/developer/sdk/configuration.mdx
index d869fe9355..53e8b1321c 100644
--- a/docs/developer/sdk/configuration.mdx
+++ b/docs/developer/sdk/configuration.mdx
@@ -21,6 +21,30 @@ const category = await client.categories.get('clothing/shirts', {
})
```
+import { Since } from '/snippets/since.mdx';
+
+## Sales Channels <Since version="5.5" />
+
+Select which [sales channel](/developer/core-concepts/channels) scopes a request. The SDK sends the value as the `X-Spree-Channel` header. Pass either the channel `code` (e.g. `online`, `pos`, `wholesale`) or the prefixed ID (`ch_…`) — `code` is preferred since it's merchant-meaningful and stable across environments. When omitted, the store's default channel is used.
+
+```typescript
+// Client-level default — every request runs against the POS channel
+const client = createClient({
+ baseUrl: 'https://api.mystore.com',
+ publishableKey: 'pk_xxx',
+ channel: 'pos',
+})
+
+// Sticky setter — switch channels mid-session (e.g. after the user
+// changes storefront context)
+client.setChannel('wholesale')
+
+// Per-request override — one request only
+const products = await client.products.list({}, { channel: 'pos' })
+```
+
+The channel scopes product visibility (only products published on that channel are returned), pricing fallback (per-channel pricing rules), and order attribution (a cart created with `channel: 'pos'` gets `order.channel_id` set to the POS channel).
+
## Error Handling
```typescript
diff --git a/docs/developer/upgrades/5.4-to-5.5.mdx b/docs/developer/upgrades/5.4-to-5.5.mdx
index 8c7d022c55..26f0eb31cc 100644
--- a/docs/developer/upgrades/5.4-to-5.5.mdx
+++ b/docs/developer/upgrades/5.4-to-5.5.mdx
@@ -72,7 +72,7 @@ For single-store deployments this is invisible; you can move on without touching
#### Behavioral changes
-- Newly-created products in **the dashboard SPA** are auto-published on the store's default channel (Shopify-style; the merchant can untick channels post-create via the Publishing card).
+- Newly-created products in **the dashboard SPA** are auto-published on the store's default channel; the merchant can untick channels post-create via the Publishing card.
- Newly-created products via the **Admin API** are NOT auto-published — the caller must supply `product_publications: [{ channel_id }]` on create or use `POST /api/v3/admin/channels/:id/add_products` afterwards.
- `Product.available_on=` and `Product.discontinue_on=` setters emit deprecation warnings and now write to every per-channel publication's `published_at` / `unpublished_at`. Reading these attributes on a product prefers the current-channel publication's value over the legacy column.
- `Spree::Channel#add_products(product_ids)` is idempotent and **preserves existing publication windows** when called without `published_at`/`unpublished_at` kwargs.
diff --git a/packages/dashboard-core/README.md b/packages/dashboard-core/README.md
index b5e3497690..56e928daa0 100644
--- a/packages/dashboard-core/README.md
+++ b/packages/dashboard-core/README.md
@@ -399,7 +399,7 @@ Equivalent to calling the underlying registry methods directly. Use whichever fe
## What's NOT here
-Resource-specific hooks (`use-orders`, `use-products`, `use-customers`, …), Zod schemas, feature pages, route definitions, and per-feature locale strings live in `@spree/dashboard` (the app). We do not publish feature internals — that's the same call Medusa, Vendure, and Saleor make. Plugin authors compose new pages out of `@spree/dashboard-ui` primitives + `@spree/dashboard-core` infra, not out of forked feature internals.
+Resource-specific hooks (`use-orders`, `use-products`, `use-customers`, …), Zod schemas, feature pages, route definitions, and per-feature locale strings live in `@spree/dashboard` (the app). We do not publish feature internals. Plugin authors compose new pages out of `@spree/dashboard-ui` primitives + `@spree/dashboard-core` infra, not out of forked feature internals.
Theme and toast UI live in `@spree/dashboard-ui` (they're rendering concerns, no Spree backend coupling): `ThemeProvider`, `useTheme`, `Toaster`.
diff --git a/packages/sdk-core/src/request.ts b/packages/sdk-core/src/request.ts
index 42bc0ef090..c0d1dec2e3 100644
--- a/packages/sdk-core/src/request.ts
+++ b/packages/sdk-core/src/request.ts
@@ -24,6 +24,8 @@ export interface RequestOptions {
currency?: string
/** Country ISO code for market resolution (e.g., 'US', 'DE') */
country?: string
+ /** Channel code (e.g., 'pos', 'wholesale') sent as X-Spree-Channel — selects which sales channel scopes the request */
+ channel?: string
/** Idempotency key for safe retries of mutating requests (max 255 characters) */
idempotencyKey?: string
/** Custom headers */
@@ -127,6 +129,7 @@ export function createRequestFn(
const locale = options.locale ?? defaults?.locale
const currency = options.currency ?? defaults?.currency
const country = options.country ?? defaults?.country
+ const channel = options.channel ?? defaults?.channel
// Build URL with query params.
// `new URL(path)` throws on a relative path. When baseUrl is empty (browser
@@ -182,6 +185,10 @@ export function createRequestFn(
requestHeaders['x-spree-country'] = country
}
+ if (channel) {
+ requestHeaders['x-spree-channel'] = channel
+ }
+
// Auto-generate idempotency key for mutating requests when retries are enabled (Stripe-style).
// User-supplied keys take precedence over auto-generated ones.
const isMutating = method !== 'GET' && method !== 'HEAD'
diff --git a/packages/sdk-core/src/types.ts b/packages/sdk-core/src/types.ts
index 73d978f7d7..bd866873ec 100644
--- a/packages/sdk-core/src/types.ts
+++ b/packages/sdk-core/src/types.ts
@@ -3,6 +3,8 @@ export interface LocaleDefaults {
locale?: string
currency?: string
country?: string
+ /** Channel code (e.g., 'pos', 'wholesale') sent as X-Spree-Channel */
+ channel?: string
}
// API Response types
diff --git a/packages/sdk/.changeset/store-channel-header.md b/packages/sdk/.changeset/store-channel-header.md
new file mode 100644
index 0000000000..526afe51ff
--- /dev/null
+++ b/packages/sdk/.changeset/store-channel-header.md
@@ -0,0 +1,11 @@
+---
+'@spree/sdk': patch
+---
+
+Add sales-channel selection to the Store SDK via the `X-Spree-Channel` header.
+
+- `createClient({ channel: 'pos' })` — set a client-level default
+- `client.setChannel('wholesale')` — sticky setter, mirrors `setLocale` / `setCurrency` / `setCountry`
+- `await client.products.list({}, { channel: 'pos' })` — per-request override
+
+The value can be either a channel `code` (e.g. `online`, `pos`, `wholesale`) or the prefixed ID (`ch_…`); `code` is preferred. Backend resolution stays at `Spree::Api::V3::ChannelResolution`: a matching header picks the channel for the request, otherwise the store's default channel applies.
diff --git a/packages/sdk/README.md b/packages/sdk/README.md
index 51237c837a..378ff57862 100644
--- a/packages/sdk/README.md
+++ b/packages/sdk/README.md
@@ -606,11 +606,11 @@ await client.categories.products.list(categoryId, params, options);
await client.wishlists.items.create(wishlistId, params, options);
```
-## Localization & Currency
+## Localization, Currency & Sales Channels
### Client-level defaults
-Set locale, currency, and country when creating the client:
+Set locale, currency, country, and sales channel when creating the client:
```typescript
const client = createClient({
@@ -619,9 +619,10 @@ const client = createClient({
locale: 'fr',
currency: 'EUR',
country: 'FR',
+ channel: 'pos',
});
-// All requests use fr/EUR/FR automatically
+// All requests use fr/EUR/FR and the 'pos' channel automatically
const products = await client.products.list();
```
@@ -631,17 +632,21 @@ Update defaults at any time:
client.setLocale('de');
client.setCurrency('EUR');
client.setCountry('DE');
+client.setChannel('wholesale');
```
+The `channel` value can be either a channel `code` (e.g. `online`, `pos`, `wholesale`) or the prefixed ID (`ch_…`). `code` is preferred — it's merchant-meaningful and stable across environments. The SDK maps it to the `X-Spree-Channel` request header, which selects which [sales channel](https://spreecommerce.org/docs/developer/core-concepts/channels) scopes the request. When omitted, the store's default channel is used.
+
### Per-request overrides
-Pass locale and currency headers with any request to override defaults:
+Pass headers with any request to override the defaults:
```typescript
const products = await client.products.list({}, {
locale: 'fr',
currency: 'EUR',
country: 'FR',
+ channel: 'pos',
});
```
diff --git a/packages/sdk/src/client.ts b/packages/sdk/src/client.ts
index a5d63f1917..d0c70a11ed 100644
--- a/packages/sdk/src/client.ts
+++ b/packages/sdk/src/client.ts
@@ -17,6 +17,8 @@ export interface ClientConfig {
currency?: string
/** Default country ISO code for market resolution (e.g., 'FR') */
country?: string
+ /** Default channel code (e.g., 'pos', 'wholesale') sent as X-Spree-Channel */
+ channel?: string
}
export interface Client extends StoreClient {
@@ -26,6 +28,8 @@ export interface Client extends StoreClient {
setCurrency(currency: string): void
/** Set default country for all subsequent requests */
setCountry(country: string): void
+ /** Set default sales-channel code for all subsequent requests */
+ setChannel(channel: string): void
}
/**
@@ -47,6 +51,7 @@ export function createClient(config: ClientConfig): Client {
locale: config.locale,
currency: config.currency,
country: config.country,
+ channel: config.channel,
}
const retryConfig = resolveRetryConfig(config.retry)
@@ -75,6 +80,9 @@ export function createClient(config: ClientConfig): Client {
client.setCountry = (country: string) => {
defaults.country = country
}
+ client.setChannel = (channel: string) => {
+ defaults.channel = channel
+ }
return client
}
diff --git a/packages/sdk/tests/client.test.ts b/packages/sdk/tests/client.test.ts
index c783454e5b..d8bf353864 100644
--- a/packages/sdk/tests/client.test.ts
+++ b/packages/sdk/tests/client.test.ts
@@ -167,9 +167,53 @@ describe('createClient', () => {
fetch: customFetch,
})
- await client.products.list({}, { locale: 'fr', currency: 'EUR' })
+ await client.products.list({}, { locale: 'fr', currency: 'EUR', channel: 'pos' })
expect(capturedHeaders['x-spree-locale']).toBe('fr')
expect(capturedHeaders['x-spree-currency']).toBe('EUR')
+ expect(capturedHeaders['x-spree-channel']).toBe('pos')
+ })
+
+ it('uses client-level channel default when no per-request override', async () => {
+ let capturedHeaders: Record<string, string> = {}
+ const customFetch = async (_input: string | URL | Request, init?: RequestInit) => {
+ capturedHeaders = Object.fromEntries(
+ Object.entries((init?.headers as Record<string, string>) || {}),
+ )
+ return new Response(
+ JSON.stringify({
+ data: [],
+ meta: {
+ page: 1,
+ limit: 25,
+ count: 0,
+ pages: 0,
+ from: 0,
+ to: 0,
+ in: 0,
+ previous: null,
+ next: null,
+ },
+ }),
+ {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ },
+ )
+ }
+
+ const client = createClient({
+ baseUrl: TEST_BASE_URL,
+ publishableKey: TEST_API_KEY,
+ channel: 'wholesale',
+ fetch: customFetch,
+ })
+
+ await client.products.list()
+ expect(capturedHeaders['x-spree-channel']).toBe('wholesale')
+
+ // Per-request override wins over the client default
+ await client.products.list({}, { channel: 'pos' })
+ expect(capturedHeaders['x-spree-channel']).toBe('pos')
})
it('exposes all resource namespaces directly', () => {
@@ -190,7 +234,7 @@ describe('createClient', () => {
expect(client.wishlists).toBeDefined()
})
- it('supports setLocale, setCurrency, setCountry', () => {
+ it('supports setLocale, setCurrency, setCountry, setChannel', () => {
const client = createClient({
baseUrl: TEST_BASE_URL,
publishableKey: TEST_API_KEY,
@@ -200,6 +244,53 @@ describe('createClient', () => {
client.setLocale('fr')
client.setCurrency('EUR')
client.setCountry('FR')
+ client.setChannel('pos')
}).not.toThrow()
})
+
+ it('setChannel updates the channel applied to subsequent requests', async () => {
+ let capturedHeaders: Record<string, string> = {}
+ const customFetch = async (_input: string | URL | Request, init?: RequestInit) => {
+ capturedHeaders = Object.fromEntries(
+ Object.entries((init?.headers as Record<string, string>) || {}),
+ )
+ return new Response(
+ JSON.stringify({
+ data: [],
+ meta: {
+ page: 1,
+ limit: 25,
+ count: 0,
+ pages: 0,
+ from: 0,
+ to: 0,
+ in: 0,
+ previous: null,
+ next: null,
+ },
+ }),
+ {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ },
+ )
+ }
+
+ const client = createClient({
+ baseUrl: TEST_BASE_URL,
+ publishableKey: TEST_API_KEY,
+ fetch: customFetch,
+ })
+
+ await client.products.list()
+ expect(capturedHeaders['x-spree-channel']).toBeUndefined()
+
+ client.setChannel('pos')
+ await client.products.list()
+ expect(capturedHeaders['x-spree-channel']).toBe('pos')
+
+ client.setChannel('wholesale')
+ await client.products.list()
+ expect(capturedHeaders['x-spree-channel']).toBe('wholesale')
+ })
})