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.

Improve handling localization with SDK and Next packages

Damian Legawiec646cca29b9cf
diff --git a/packages/next/.changeset/auto-localization.md b/packages/next/.changeset/auto-localization.md
new file mode 100644
index 0000000000..1ac7c40c41
--- /dev/null
+++ b/packages/next/.changeset/auto-localization.md
@@ -0,0 +1,5 @@
+---
+"@spree/next": patch
+---
+
+Added automatic localization. Data functions now auto-read locale and country from cookies when no explicit options are provided. New exports: `setLocale` server action for country/language switchers, `createSpreeMiddleware` (from `@spree/next/middleware`) for URL-based routing with geo-detection. Added `country` to `SpreeNextOptions` and `countryCookieName`, `localeCookieName`, `defaultCountry` to `SpreeNextConfig`.
diff --git a/packages/next/.changeset/flat-query-params.md b/packages/next/.changeset/flat-query-params.md
new file mode 100644
index 0000000000..e530045fbd
--- /dev/null
+++ b/packages/next/.changeset/flat-query-params.md
@@ -0,0 +1,5 @@
+---
+"@spree/next": patch
+---
+
+Updated data function params to use typed flat query params (`ProductListParams`, `TaxonListParams`, `OrderListParams`) instead of `Record<string, unknown>`.
diff --git a/packages/next/README.md b/packages/next/README.md
index 238e45086b..dd2c9c4894 100644
--- a/packages/next/README.md
+++ b/packages/next/README.md
@@ -240,11 +240,45 @@ const giftCard = await getGiftCard(giftCardId);
## Localization
-Pass locale and currency options to data functions:
+### Automatic (recommended)
+
+Data functions automatically read locale and country from cookies. Use the included middleware to handle URL-based routing and cookie persistence:
+
+```typescript
+// middleware.ts
+import { createSpreeMiddleware } from '@spree/next/middleware';
+
+export default createSpreeMiddleware({
+ defaultCountry: 'us',
+ defaultLocale: 'en',
+});
+
+export const config = {
+ matcher: ['/((?!_next/static|_next/image|favicon.ico|.*\\..*$).*)'],
+};
+```
+
+Data functions work without any locale arguments:
+
+```typescript
+const products = await listProducts({ per_page: 10 });
+const taxon = await getTaxon('categories/clothing');
+```
+
+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({ per_page: 10 }, { locale: 'fr', currency: 'EUR' });
-const taxon = await getTaxon('categories/clothing', {}, { locale: 'de', currency: 'EUR' });
+const products = await listProducts({ per_page: 10 }, { locale: 'fr', country: 'FR' });
```
## TypeScript
diff --git a/packages/next/package.json b/packages/next/package.json
index da164455fc..6cb258f450 100644
--- a/packages/next/package.json
+++ b/packages/next/package.json
@@ -16,6 +16,13 @@
"default": "./dist/index.js"
},
"default": "./dist/index.js"
+ },
+ "./middleware": {
+ "import": {
+ "types": "./dist/middleware.d.ts",
+ "default": "./dist/middleware.js"
+ },
+ "default": "./dist/middleware.js"
}
},
"files": [
@@ -23,7 +30,7 @@
"README.md"
],
"scripts": {
- "build": "tsup",
+ "build": "rm -rf dist && tsup",
"dev": "tsup --watch",
"typecheck": "tsc --noEmit",
"test": "vitest run",
diff --git a/packages/next/src/actions/locale.ts b/packages/next/src/actions/locale.ts
new file mode 100644
index 0000000000..363b46e34b
--- /dev/null
+++ b/packages/next/src/actions/locale.ts
@@ -0,0 +1,30 @@
+'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/data/countries.ts b/packages/next/src/data/countries.ts
index 504c7952a4..8754dcde8b 100644
--- a/packages/next/src/data/countries.ts
+++ b/packages/next/src/data/countries.ts
@@ -1,32 +1,31 @@
import type { StoreCountry } from '@spree/sdk';
import { getClient } from '../config';
+import { getLocaleOptions } from '../locale';
import type { SpreeNextOptions } from '../types';
/**
* List countries available in the store.
* Each country includes currency and default_locale derived from its market.
+ * Locale/country are auto-read from cookies when not provided.
*/
export async function listCountries(
options?: SpreeNextOptions
): Promise<{ data: StoreCountry[] }> {
- return getClient().store.countries.list({
- locale: options?.locale,
- currency: options?.currency,
- });
+ const resolved = options ?? await getLocaleOptions();
+ return getClient().store.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., { include: 'states' } for address forms)
+ * Locale/country are auto-read from cookies when not provided.
*/
export async function getCountry(
iso: string,
params?: { include?: string },
options?: SpreeNextOptions
): Promise<StoreCountry> {
- return getClient().store.countries.get(iso, params, {
- locale: options?.locale,
- currency: options?.currency,
- });
+ const resolved = options ?? await getLocaleOptions();
+ return getClient().store.countries.get(iso, params, resolved);
}
diff --git a/packages/next/src/data/currencies.ts b/packages/next/src/data/currencies.ts
index c3de4584a2..598eb2350c 100644
--- a/packages/next/src/data/currencies.ts
+++ b/packages/next/src/data/currencies.ts
@@ -1,15 +1,15 @@
import type { StoreCurrency } 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: StoreCurrency[] }> {
- return getClient().store.currencies.list({
- locale: options?.locale,
- currency: options?.currency,
- });
+ const resolved = options ?? await getLocaleOptions();
+ return getClient().store.currencies.list(resolved);
}
diff --git a/packages/next/src/data/locales.ts b/packages/next/src/data/locales.ts
index 4ee0a1f2b1..1411e2bd08 100644
--- a/packages/next/src/data/locales.ts
+++ b/packages/next/src/data/locales.ts
@@ -1,15 +1,15 @@
import type { StoreLocale } 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: StoreLocale[] }> {
- return getClient().store.locales.list({
- locale: options?.locale,
- currency: options?.currency,
- });
+ const resolved = options ?? await getLocaleOptions();
+ return getClient().store.locales.list(resolved);
}
diff --git a/packages/next/src/data/products.ts b/packages/next/src/data/products.ts
index e5258eb961..3865a0d7fa 100644
--- a/packages/next/src/data/products.ts
+++ b/packages/next/src/data/products.ts
@@ -1,43 +1,41 @@
import type { StoreProduct, 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<StoreProduct>> {
- return getClient().store.products.list(params, {
- locale: options?.locale,
- currency: options?.currency,
- });
+ const resolved = options ?? await getLocaleOptions();
+ return getClient().store.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?: { includes?: string },
options?: SpreeNextOptions
): Promise<StoreProduct> {
- return getClient().store.products.get(slugOrId, params, {
- locale: options?.locale,
- currency: options?.currency,
- });
+ const resolved = options ?? await getLocaleOptions();
+ return getClient().store.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> {
- return getClient().store.products.filters(params, {
- locale: options?.locale,
- currency: options?.currency,
- });
+ const resolved = options ?? await getLocaleOptions();
+ return getClient().store.products.filters(params, resolved);
}
diff --git a/packages/next/src/data/store.ts b/packages/next/src/data/store.ts
index a34b29f1c4..02a78edacc 100644
--- a/packages/next/src/data/store.ts
+++ b/packages/next/src/data/store.ts
@@ -1,13 +1,13 @@
import type { StoreStore } from '@spree/sdk';
import { getClient } from '../config';
+import { getLocaleOptions } from '../locale';
import type { SpreeNextOptions } from '../types';
/**
* Get the current store configuration.
+ * Locale/country are auto-read from cookies when not provided.
*/
export async function getStore(options?: SpreeNextOptions): Promise<StoreStore> {
- return getClient().store.store.get({
- locale: options?.locale,
- currency: options?.currency,
- });
+ const resolved = options ?? await getLocaleOptions();
+ return getClient().store.store.get(resolved);
}
diff --git a/packages/next/src/data/taxonomies.ts b/packages/next/src/data/taxonomies.ts
index bdac7600ba..923311f416 100644
--- a/packages/next/src/data/taxonomies.ts
+++ b/packages/next/src/data/taxonomies.ts
@@ -1,30 +1,29 @@
import type { StoreTaxonomy, PaginatedResponse } from '@spree/sdk';
import { getClient } from '../config';
+import { getLocaleOptions } from '../locale';
import type { SpreeNextOptions } from '../types';
/**
* List taxonomies with optional filtering and pagination.
+ * Locale/country are auto-read from cookies when not provided.
*/
export async function listTaxonomies(
params?: Record<string, unknown>,
options?: SpreeNextOptions
): Promise<PaginatedResponse<StoreTaxonomy>> {
- return getClient().store.taxonomies.list(params, {
- locale: options?.locale,
- currency: options?.currency,
- });
+ const resolved = options ?? await getLocaleOptions();
+ return getClient().store.taxonomies.list(params, resolved);
}
/**
* Get a single taxonomy by ID.
+ * Locale/country are auto-read from cookies when not provided.
*/
export async function getTaxonomy(
id: string,
params?: Record<string, unknown>,
options?: SpreeNextOptions
): Promise<StoreTaxonomy> {
- return getClient().store.taxonomies.get(id, params, {
- locale: options?.locale,
- currency: options?.currency,
- });
+ const resolved = options ?? await getLocaleOptions();
+ return getClient().store.taxonomies.get(id, params, resolved);
}
diff --git a/packages/next/src/data/taxons.ts b/packages/next/src/data/taxons.ts
index f3ace60582..b07d485221 100644
--- a/packages/next/src/data/taxons.ts
+++ b/packages/next/src/data/taxons.ts
@@ -1,44 +1,42 @@
import type { StoreTaxon, StoreProduct, PaginatedResponse, TaxonListParams, ProductListParams } from '@spree/sdk';
import { getClient } from '../config';
+import { getLocaleOptions } from '../locale';
import type { SpreeNextOptions } from '../types';
/**
* List taxons (categories) with optional filtering and pagination.
+ * Locale/country are auto-read from cookies when not provided.
*/
export async function listTaxons(
params?: TaxonListParams,
options?: SpreeNextOptions
): Promise<PaginatedResponse<StoreTaxon>> {
- return getClient().store.taxons.list(params, {
- locale: options?.locale,
- currency: options?.currency,
- });
+ const resolved = options ?? await getLocaleOptions();
+ return getClient().store.taxons.list(params, resolved);
}
/**
* Get a single taxon by ID or permalink.
+ * Locale/country are auto-read from cookies when not provided.
*/
export async function getTaxon(
idOrPermalink: string,
params?: Record<string, unknown>,
options?: SpreeNextOptions
): Promise<StoreTaxon> {
- return getClient().store.taxons.get(idOrPermalink, params, {
- locale: options?.locale,
- currency: options?.currency,
- });
+ const resolved = options ?? await getLocaleOptions();
+ return getClient().store.taxons.get(idOrPermalink, params, resolved);
}
/**
* List products within a taxon.
+ * Locale/country are auto-read from cookies when not provided.
*/
export async function listTaxonProducts(
taxonId: string,
params?: ProductListParams,
options?: SpreeNextOptions
): Promise<PaginatedResponse<StoreProduct>> {
- return getClient().store.taxons.products.list(taxonId, params, {
- locale: options?.locale,
- currency: options?.currency,
- });
+ const resolved = options ?? await getLocaleOptions();
+ return getClient().store.taxons.products.list(taxonId, params, resolved);
}
diff --git a/packages/next/src/index.ts b/packages/next/src/index.ts
index dd1d01b2e1..581b90b427 100644
--- a/packages/next/src/index.ts
+++ b/packages/next/src/index.ts
@@ -51,6 +51,7 @@ export {
} 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';
diff --git a/packages/next/src/locale.ts b/packages/next/src/locale.ts
new file mode 100644
index 0000000000..3466796c4b
--- /dev/null
+++ b/packages/next/src/locale.ts
@@ -0,0 +1,28 @@
+import { cookies } from 'next/headers';
+import { getConfig } from './config';
+
+const DEFAULT_COUNTRY_COOKIE = 'spree_country';
+const DEFAULT_LOCALE_COOKIE = 'spree_locale';
+
+/**
+ * Read locale/currency/country from cookies (set by middleware).
+ * Falls back to config defaults.
+ * @internal
+ */
+export async function getLocaleOptions(): Promise<{
+ locale?: string;
+ currency?: string;
+ country?: string;
+}> {
+ const config = getConfig();
+ const cookieStore = await cookies();
+
+ const country = cookieStore.get(config.countryCookieName ?? DEFAULT_COUNTRY_COOKIE)?.value;
+ const locale = cookieStore.get(config.localeCookieName ?? DEFAULT_LOCALE_COOKIE)?.value;
+
+ return {
+ locale: locale || config.defaultLocale,
+ country: country || config.defaultCountry,
+ // No currency — backend resolves from country via X-Spree-Country header
+ };
+}
diff --git a/packages/next/src/middleware.ts b/packages/next/src/middleware.ts
new file mode 100644
index 0000000000..366de2e0be
--- /dev/null
+++ b/packages/next/src/middleware.ts
@@ -0,0 +1,65 @@
+import { NextResponse, type NextRequest } from 'next/server';
+
+export interface SpreeMiddlewareConfig {
+ /** Default country ISO code (default: 'us') */
+ defaultCountry?: string;
+ /** Default locale code (default: 'en') */
+ defaultLocale?: string;
+ /** Routes to skip — prefixes matched with startsWith (default: ['/_next', '/api', '/favicon.ico']) */
+ staticRoutes?: string[];
+}
+
+/**
+ * Creates a Next.js middleware that handles:
+ * - Redirecting bare paths to /{country}/{locale}/...
+ * - Detecting country from cookies → geo headers → default
+ * - Detecting locale from cookies → accept-language → default
+ *
+ * Usage in your middleware.ts:
+ * ```typescript
+ * import { createSpreeMiddleware } from '@spree/next/middleware';
+ * export default createSpreeMiddleware({ defaultCountry: 'us', defaultLocale: 'en' });
+ * export const config = { matcher: ['/((?!_next/static|_next/image|favicon.ico|.*\\..*$).*)'] };
+ * ```
+ */
+export function createSpreeMiddleware(config: SpreeMiddlewareConfig = {}) {
+ const defaultCountry = config.defaultCountry ?? 'us';
+ const defaultLocale = config.defaultLocale ?? 'en';
+ const staticRoutes = config.staticRoutes ?? ['/_next', '/api', '/favicon.ico'];
+
+ return function middleware(request: NextRequest) {
+ const { pathname } = request.nextUrl;
+
+ // Skip static routes
+ if (staticRoutes.some((route) => pathname.startsWith(route))) {
+ return NextResponse.next();
+ }
+
+ // Skip if pathname contains a file extension (static assets)
+ if (/\.\w+$/.test(pathname)) {
+ return NextResponse.next();
+ }
+
+ // Already has /{country}/{locale} prefix
+ if (/^\/[a-z]{2}\/[a-z]{2}(\/|$)/i.test(pathname)) {
+ return NextResponse.next();
+ }
+
+ // Detect country: cookie → geo headers → default
+ const country =
+ request.cookies.get('spree_country')?.value ??
+ request.headers.get('x-vercel-ip-country')?.toLowerCase() ??
+ request.headers.get('cf-ipcountry')?.toLowerCase() ??
+ defaultCountry;
+
+ // Detect locale: cookie → accept-language → default
+ const locale =
+ request.cookies.get('spree_locale')?.value ??
+ request.headers.get('accept-language')?.split(',')[0]?.split('-')[0]?.toLowerCase() ??
+ defaultLocale;
+
+ const url = request.nextUrl.clone();
+ url.pathname = `/${country}/${locale}${pathname === '/' ? '' : pathname}`;
+ return NextResponse.redirect(url);
+ };
+}
diff --git a/packages/next/src/types.ts b/packages/next/src/types.ts
index d21dd98e80..0e6ec02387 100644
--- a/packages/next/src/types.ts
+++ b/packages/next/src/types.ts
@@ -7,10 +7,16 @@ export interface SpreeNextConfig {
cartCookieName?: string;
/** Cookie name for the JWT access token (default: '_spree_jwt') */
accessTokenCookieName?: string;
+ /** Cookie name for country (default: 'spree_country') */
+ countryCookieName?: string;
+ /** Cookie name for locale (default: 'spree_locale') */
+ localeCookieName?: string;
/** Default locale for API requests */
defaultLocale?: string;
/** Default currency for API requests */
defaultCurrency?: string;
+ /** Default country ISO code for market resolution */
+ defaultCountry?: string;
}
export interface SpreeNextOptions {
@@ -18,4 +24,6 @@ export interface SpreeNextOptions {
locale?: string;
/** Currency for prices (e.g., 'USD', 'EUR') */
currency?: string;
+ /** Country ISO code for market resolution (e.g., 'US', 'DE') */
+ country?: string;
}
diff --git a/packages/next/tsup.config.ts b/packages/next/tsup.config.ts
index c18a014cb3..1226d9480e 100644
--- a/packages/next/tsup.config.ts
+++ b/packages/next/tsup.config.ts
@@ -7,6 +7,7 @@ export default defineConfig([
index: 'src/index.ts',
config: 'src/config.ts',
types: 'src/types.ts',
+ locale: 'src/locale.ts',
'data/products': 'src/data/products.ts',
'data/taxons': 'src/data/taxons.ts',
'data/taxonomies': 'src/data/taxonomies.ts',
@@ -19,7 +20,6 @@ export default defineConfig([
dts: true,
splitting: false,
sourcemap: true,
- clean: true,
treeshake: true,
external: ['next', 'next/cache', 'next/headers', '@spree/sdk', 'react'],
},
@@ -35,6 +35,7 @@ export default defineConfig([
'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,
@@ -42,4 +43,15 @@ export default defineConfig([
sourcemap: true,
external: ['next', 'next/cache', 'next/headers', '@spree/sdk', 'react'],
},
+ // Middleware — separate entry (Edge runtime, no next/headers)
+ {
+ entry: {
+ middleware: 'src/middleware.ts',
+ },
+ format: ['esm'],
+ dts: true,
+ splitting: false,
+ sourcemap: true,
+ external: ['next', 'next/server', '@spree/sdk'],
+ },
]);
diff --git a/packages/sdk/.changeset/auto-localization.md b/packages/sdk/.changeset/auto-localization.md
new file mode 100644
index 0000000000..530c9b116e
--- /dev/null
+++ b/packages/sdk/.changeset/auto-localization.md
@@ -0,0 +1,5 @@
+---
+"@spree/sdk": patch
+---
+
+Added client-level locale, currency, and country defaults. Set them at initialization (`createSpreeClient({ locale: 'fr', currency: 'EUR', country: 'FR' })`) or update later with `client.setLocale()`, `client.setCurrency()`, `client.setCountry()`. Per-request options still override defaults.
diff --git a/packages/sdk/.changeset/flat-query-params.md b/packages/sdk/.changeset/flat-query-params.md
new file mode 100644
index 0000000000..60b855dd8a
--- /dev/null
+++ b/packages/sdk/.changeset/flat-query-params.md
@@ -0,0 +1,5 @@
+---
+"@spree/sdk": patch
+---
+
+Added flat query params for filtering and sorting. Instead of `{ 'q[name_cont]': 'shirt' }`, you can now write `{ name_cont: 'shirt', sort: 'price asc' }`. The SDK transforms these to Ransack format automatically. Old `q[...]` syntax still works for backward compatibility.
diff --git a/packages/sdk/README.md b/packages/sdk/README.md
index 2fd4919fd1..75e624130b 100644
--- a/packages/sdk/README.md
+++ b/packages/sdk/README.md
@@ -517,21 +517,40 @@ await client.store.wishlists.items.create(wishlistId, params, options);
## Localization & Currency
-Pass locale and currency headers with any request:
+### Client-level defaults
+
+Set locale, currency, and country when creating the client:
```typescript
-// Set locale and currency per request
-const products = await client.store.products.list({}, {
+const client = createSpreeClient({
+ baseUrl: 'https://api.mystore.com',
+ publishableKey: 'spree_pk_xxx',
locale: 'fr',
currency: 'EUR',
+ country: 'FR',
});
-// Works with all endpoints
-const taxon = await client.store.taxons.get('categories/clothing', {
- includes: 'ancestors',
-}, {
- locale: 'de',
+// All requests use fr/EUR/FR automatically
+const products = await client.store.products.list();
+```
+
+Update defaults at any time:
+
+```typescript
+client.setLocale('de');
+client.setCurrency('EUR');
+client.setCountry('DE');
+```
+
+### Per-request overrides
+
+Pass locale and currency headers with any request to override defaults:
+
+```typescript
+const products = await client.store.products.list({}, {
+ locale: 'fr',
currency: 'EUR',
+ country: 'FR',
});
```
diff --git a/packages/sdk/src/client.ts b/packages/sdk/src/client.ts
index a0177dcba3..a8efb8258d 100644
--- a/packages/sdk/src/client.ts
+++ b/packages/sdk/src/client.ts
@@ -1,10 +1,11 @@
import { createRequestFn } from './request';
import type { RetryConfig, RequestConfig } from './request';
+import type { LocaleDefaults } from './types';
import { StoreClient } from './store-client';
import { AdminClient } from './admin-client';
// Re-export types for convenience
-export type { AddressParams, StoreCreditCard } from './types';
+export type { AddressParams, StoreCreditCard, LocaleDefaults } from './types';
export interface SpreeClientConfig {
/** Base URL of the Spree API (e.g., 'https://api.mystore.com') */
@@ -17,6 +18,12 @@ export interface SpreeClientConfig {
fetch?: typeof fetch;
/** Retry configuration. Enabled by default. Pass false to disable. */
retry?: RetryConfig | false;
+ /** Default locale for API requests (e.g., 'fr') */
+ locale?: string;
+ /** Default currency for API requests (e.g., 'EUR') */
+ currency?: string;
+ /** Default country ISO code for market resolution (e.g., 'FR') */
+ country?: string;
}
export class SpreeClient {
@@ -25,11 +32,19 @@ export class SpreeClient {
/** Admin API — administrative endpoints (manage orders, products, settings) */
readonly admin: AdminClient;
+ private readonly _defaults: LocaleDefaults;
+
constructor(config: SpreeClientConfig) {
const baseUrl = config.baseUrl.replace(/\/$/, '');
// Bind fetch to globalThis to avoid "Illegal invocation" errors in browsers
const fetchFn = config.fetch || fetch.bind(globalThis);
+ this._defaults = {
+ locale: config.locale,
+ currency: config.currency,
+ country: config.country,
+ };
+
let retryConfig: Required<RetryConfig> | false;
if (config.retry === false) {
retryConfig = false;
@@ -48,7 +63,8 @@ export class SpreeClient {
const storeRequestFn = createRequestFn(
requestConfig,
'/api/v3/store',
- { headerName: 'x-spree-api-key', headerValue: config.publishableKey }
+ { headerName: 'x-spree-api-key', headerValue: config.publishableKey },
+ this._defaults
);
const adminRequestFn = createRequestFn(
@@ -57,12 +73,28 @@ export class SpreeClient {
{
headerName: 'Authorization',
headerValue: config.secretKey ? `Bearer ${config.secretKey}` : '',
- }
+ },
+ this._defaults
);
this.store = new StoreClient(storeRequestFn);
this.admin = new AdminClient(adminRequestFn);
}
+
+ /** Set default locale for all subsequent requests */
+ setLocale(locale: string): void {
+ this._defaults.locale = locale;
+ }
+
+ /** Set default currency for all subsequent requests */
+ setCurrency(currency: string): void {
+ this._defaults.currency = currency;
+ }
+
+ /** Set default country for all subsequent requests */
+ setCountry(country: string): void {
+ this._defaults.country = country;
+ }
}
/**
diff --git a/packages/sdk/src/request.ts b/packages/sdk/src/request.ts
index 0b0f8a4c6b..8e95f44064 100644
--- a/packages/sdk/src/request.ts
+++ b/packages/sdk/src/request.ts
@@ -1,4 +1,4 @@
-import type { ErrorResponse } from './types';
+import type { ErrorResponse, LocaleDefaults } from './types';
export interface RetryConfig {
/** Maximum number of retries (default: 2) */
@@ -93,14 +93,20 @@ export interface AuthConfig {
export function createRequestFn(
config: RequestConfig,
basePath: string,
- auth: AuthConfig
+ auth: AuthConfig,
+ defaults?: LocaleDefaults
): RequestFn {
return async function request<T>(
method: string,
path: string,
options: InternalRequestOptions = {}
): Promise<T> {
- const { token, orderToken, locale, currency, country, headers = {}, body, params } = options;
+ const { token, orderToken, headers = {}, body, params } = options;
+
+ // Per-request options override client-level defaults
+ const locale = options.locale ?? defaults?.locale;
+ const currency = options.currency ?? defaults?.currency;
+ const country = options.country ?? defaults?.country;
// Build URL with query params
const url = new URL(`${config.baseUrl}${basePath}${path}`);
diff --git a/packages/sdk/src/types/index.ts b/packages/sdk/src/types/index.ts
index f0c24f74d7..851c31729e 100644
--- a/packages/sdk/src/types/index.ts
+++ b/packages/sdk/src/types/index.ts
@@ -1,6 +1,13 @@
// Re-export all generated types
export * from './generated';
+// Locale defaults for client-level configuration
+export interface LocaleDefaults {
+ locale?: string;
+ currency?: string;
+ country?: string;
+}
+
// API Response types
export interface PaginationMeta {
page: number;