> ## Documentation Index
> Fetch the complete documentation index at: https://quickbutik.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Client

> createShopkitClient, every ShopkitConfig option, and what the client exposes.

> [!NOTE]
>
> This page is the curated reference. The complete, generated type reference for the root entry lives at [/kit/api/core](https://quickbutik.dev/kit/api/core.md) and is regenerated from the published typings.

```ts theme={null}
import { createShopkitClient } from "@quickbutik/kit"

const shopkit = createShopkitClient({
  publishableKey: process.env.NEXT_PUBLIC_QUICKBUTIK_PUBLISHABLE_KEY!,
})
```

Available from `@quickbutik/kit` and `@quickbutik/kit/sdk`. On a script-tag page the same function is `Quickbutik.createShopkitClient`.

A client is cheap. Create **one per app in the browser** and **one per request on the server**, because the cookie accessor belongs to that request. See [Storage & SSR](https://quickbutik.dev/kit/concepts/storage-and-ssr.md).

## createShopkitClient

```ts theme={null}
function createShopkitClient(config: ShopkitConfig): ShopkitClient
```

Throws `ShopkitConfigError` synchronously for a malformed key (including a `qb_pat_…` token), a malformed campaign storefront id, an unknown `surface`, or two conflicting storefront ids.

## ShopkitConfig

Only `publishableKey` is required.

**publishableKey** `string` *required*

The shop's publishable key, `qb_pk_<shopPrefix>_<secret>`. Safe to ship to a browser. A `qb_pat_…` personal access token is rejected with a `ShopkitConfigError`.

**apiUrl** `string` (default: [https://commerce.quickbutik.com](https://commerce.quickbutik.com))

Commerce API origin. Leave it unset in production. A trailing `/v2` is stripped, since every request path carries its own `/v2`.

**checkoutUrl** `string` (default: [https://pay.quickbutik.com](https://pay.quickbutik.com))

Origin of the hosted checkout (checkout-v2). When you set it explicitly it **wins** over the URL the platform returns for a checkout-v2 handoff. Use it only for a preview environment or a checkout proxied onto your own domain. It is ignored for a shop on the legacy checkout.

**imageBaseUrl** `string`

Fallback base for image `path`s. Rarely needed, because images already arrive with an absolute `url`. It is the shop-scoped base without the `products/` segment, for example `https://cdn.quickbutik.com/images/<shopPrefix>`.

**scopes** `ShopkitScope[] | string[] | null` (default: DEFAULT\_SHOPKIT\_SCOPES)

The scopes the key carries, used for a local pre-flight check that throws a named `ShopkitScopeError` before the request leaves the process. Pass `null` to turn the check off. The platform enforces scopes either way. See [Errors & scopes](https://quickbutik.dev/kit/reference/errors.md#scopes).

**storage** `'auto' | 'cookie' | 'localStorage' | 'memory' | StorageAdapter` (default: auto)

Where the cart id, checkout session id and a logged-in customer's session are remembered. `auto` picks server cookies when `cookies` is given, then `document.cookie`, then `localStorage`, then memory. Resolution never throws; an unusable choice degrades to memory.

**cookies** `CookieAccessor`

Server-side cookie access: `get(name)`, plus optional `set(name, value, attributes)`, `remove(name, attributes)` and `getAll()`. Each may return a promise. Supplying it is what lets a server render see the browser's cart, currency and consent decision. A read-only accessor (only `get`) is valid; writes are then dropped silently.

**methods**

**get(name)** `string | null | undefined` *required*

Read one cookie.

**set(name, value, attributes)** `void`

Write one cookie. Omit it in a context that cannot write (a React Server Component).

**remove(name, attributes)** `void`

Delete one cookie.

**getAll()** `ReadonlyArray\<\{ name: string; value: string \}\>`

Every cookie on the request. Read by one thing only: `checkout.start()` uses it to find the Google Analytics `_ga_<property>` cookie (whose name is not known in advance), so the GA client and session ids reach the hosted checkout along with the consent decision. In Next.js, `() => jar.getAll()`.

**cookieAttributes** `CookieAttributes` (default: \{})

Attributes for the cookies the kit writes.

**properties**

**path** `string` (default: /)

**maxAge** `number`

Seconds. Defaults to the value's TTL. Fractions are floored.

**domain** `string`

Host-only when omitted. Set a parent domain to share the cart across subdomains.

**secure** `boolean`

True on https origins in the browser. Pass it explicitly on a server.

**sameSite** `'lax' | 'strict' | 'none'` (default: lax)

`lax` is required for the shopper's return from the hosted checkout.

**httpOnly** `boolean` (default: false)

Leave off when browser code also reads the cart.

**consent** `boolean | \{ revision?: number; cookieName?: string \}` (default: true)

Cookie consent and the shop's analytics, **on by default**. `<ShopkitProvider>`, the elements and `checkout.start()` on a server client all read this one setting, so the browser and the server agree.

* An object sets the cookie-policy `revision` (default `1`; bump it to ask every shopper again) and the consent `cookieName` (default `qb_consent`) for all of them at once.
* `false` turns the whole layer off: no banner, no consent store, no analytics, and nothing appended to hosted checkout URLs.

See [Consent and analytics](https://quickbutik.dev/kit/concepts/consent-and-analytics.md).

**currency** `string | null`

The currency to browse in (`"EUR"`, any case) until the shopper picks one with `setCurrency()`. Every product read and cart request then carries `?currency=`, and every checkout session and handoff carries `currency`. Omitted or `null`: the shop's own currency, and nothing is sent. A value that is not a three-letter ISO 4217 code throws a `ShopkitConfigError`.

It is a **default**, not an override: a choice made with `setCurrency()` is remembered under `${storageKeyPrefix}_currency` and wins on later visits. See [Currencies](https://quickbutik.dev/kit/concepts/currencies.md).

**storefront** `\{ id: string; surface?: StorefrontSurface \} | null`

Bind this client to one campaign storefront (a Säljsida). Product reads are priced for the campaign, carts are created bound to it and checkouts are attributed to it. `surface` defaults to `"shopkit"`. Also changes the default `storageKeyPrefix`. See [Campaign storefronts](https://quickbutik.dev/kit/concepts/campaign-storefronts.md).

**storefrontId** `string | null`

Shorthand for `storefront: { id }`. May be given together with `storefront` only when both name the same campaign (compared case-insensitively). `null` and `""` mean not set.

**storageKeyPrefix** `string` (default: qb)

Prefix for the remembered keys (`qb_cart_id`, `qb_store_id`, `qb_checkout_session`, `qb_checkout_store`, `qb_currency`, `qb_customer_session`). Defaults to `qb_<storefront id lower-cased>` on a client bound to a campaign. Change it to run two shops in one browser.

**cartTtlSeconds** `number` (default: 2592000)

Lifetime of the remembered cart id (30 days).

**fetch** `typeof fetch` (default: globalThis.fetch)

Injected fetch, for tests or a framework's instrumented fetch.

**timeoutMs** `number` (default: 15000)

Per-request timeout. `0` disables it.

**maxRetries** `number` (default: 2)

Retries for transient failures (network error, 429, 5xx). Mutations carry an automatic `Idempotency-Key`, so a retried `POST /cart` cannot create a second cart. Do not wrap cart mutations in a retry loop of your own.

**headers** `Record\<string, string\>` (default: \{})

Extra headers on every request. An `authorization` header is ignored; it can never override the key.

**onUnauthorized** `() =\> string | null | Promise\<string | null\>`

Called when a request answers 401. Return a fresh key to adopt it and retry the request once. Concurrent 401s share one refresh. Return `null` to let the 401 surface. A 401 about the shopper rather than the key (`invalid_credentials`, an expired customer token) never calls it.

**customerSession** `\{ renew?: boolean \}` (default: \{})

How this client treats a logged-in customer's session. `renew: false` uses the access token while it is valid but never renews it; an expired one is treated as a guest for this client's requests. Renewal is already off on storage that cannot be written (`StorageAdapter.writable: false`: a cookie accessor without `set`, or `createRequestCookieStorage()` without `collect`), because the rotated refresh token would be lost. See [Customer accounts](https://quickbutik.dev/kit/concepts/customer-accounts.md#renew-where-cookies-can-be-written).

## ShopkitClient

**products** `ProductsResource`

See [Products, categories & shop](https://quickbutik.dev/kit/reference/products.md).

**categories** `CategoriesResource`

See [Products, categories & shop](https://quickbutik.dev/kit/reference/products.md).

**cart** `CartResource`

See [Cart](https://quickbutik.dev/kit/reference/cart.md).

**checkout** `CheckoutResource`

See [Checkout](https://quickbutik.dev/kit/reference/checkout.md).

**shop** `ShopResource`

See [Products, categories & shop](https://quickbutik.dev/kit/reference/products.md).

**customers** `CustomersResource`

Customer login, registration, password reset, logout, profile and club points. See [Customers](#customers) below.

**shopPrefix** `string`

The shop's storage prefix decoded from the key (the CDN folder its images live under). **Not** the numeric shop id the hosted checkout needs; that one is `cart.storeId`.

**shopId** `string`

Deprecated alias of `shopPrefix`.

**apiUrl** `string`

Resolved commerce API origin.

**checkoutUrl** `string`

Resolved hosted checkout origin.

**imageBaseUrl** `string | null`

Resolved image fallback base.

**storefront** `\{ id: string; surface: StorefrontSurface \} | null`

The campaign storefront binding, or `null`.

**scopes** `ScopeGuard`

**properties**

**declared** `readonly string[]`

The scopes this client was told it has.

**enforced** `boolean`

Whether the local pre-flight check is on.

**has(scope)** `boolean`

Whether a scope is covered.

**assert(scope, operation)** `void`

Throws `ShopkitScopeError` when not covered.

**currency** `string | null`

The currency the client browses in: the shopper's remembered choice, else the configured `currency`, else `null` (the shop's own). Synchronous. With an async-only cookie accessor (Next's `cookies()`) it reports the configured default; requests still read the stored choice. What prices actually came back in is on the response (`product.currency`, `cart.currency`).

**defaultCurrency** `string | null`

The configured `currency`, ignoring any choice.

**consent** `ConsentResource`

**properties**

**read()** `Promise\<ConsentState\>`

The shopper's decision from this client's cookies (the `cookies` accessor on a server, `document.cookie` in a browser), at this config's revision. Undecided when there is no cookie. Hand it to `<ShopkitProvider consent={{ initialState }}>` so the banner is right on first paint.

**enabled** `boolean`

`false` only with `consent: false` in the config.

**revision** `number`

The configured cookie-policy revision.

**cookieName** `string`

The consent cookie's name, `qb_consent` by default.

**storage** `StorageAdapter`

The resolved storage adapter.

**runtime** `ShopkitRuntimeInfo`

**properties**

**environment** `'browser' | 'server'`

**storage** `string`

The adapter kind actually in use: `cookie`, `localStorage`, `memory` or your own adapter's `kind`.

**persistent** `boolean`

`false` when storage degraded to memory, so the cart will not survive a reload.

## setCurrency

```ts theme={null}
shopkit.setCurrency(currency: string | null): Promise<void>
```

Browse in another currency: remember it (under `${storageKeyPrefix}_currency`, for a year) and notify `onCurrencyChange` subscribers. `null` forgets the choice and returns to the configured default. The cart is unchanged: it is priced per request, so the same cart reads in the new currency next time.

Throws a `ShopkitConfigError` for a value that is not a three-letter code. A well-formed code the shop does not offer is accepted and resolves to the shop's currency server-side. See [Currencies](https://quickbutik.dev/kit/concepts/currencies.md).

## onCurrencyChange

```ts theme={null}
shopkit.onCurrencyChange(listener: (currency: string | null) => void): () => void
```

Be told when `currency` changes through `setCurrency()`. Returns an unsubscribe function. The React hooks and the elements use it to refetch prices and re-read the cart. A choice written elsewhere (another tab, a server action, a second client sharing the `storageKeyPrefix`) changes the next request without firing it.

## Customers

```ts theme={null}
shopkit.customers.config(options?): Promise<CustomerAccountsConfig>
shopkit.customers.login(input: { email: string; password: string }, options?): Promise<CustomerSession>
shopkit.customers.register(input: CustomerRegisterInput, options?): Promise<CustomerRegisterResult>
shopkit.customers.requestPasswordReset(input: { email: string }, options?): Promise<void>
shopkit.customers.resetPassword(input: { email: string; code: string; password: string }, options?): Promise<CustomerSession>
shopkit.customers.logout(): Promise<void>
shopkit.customers.me(options?): Promise<Customer | null>
shopkit.customers.club.get(options?): Promise<CustomerClub | null>
shopkit.customers.setSession(input: CustomerSessionInput): Promise<void>
shopkit.customers.getAccessToken(): Promise<string | null>
shopkit.customers.onChange(listener: (state: CustomerState | null) => void): () => void
shopkit.customers.isLoggedIn   // boolean
shopkit.customers.current      // Customer | null
shopkit.customers.cacheKey     // string
```

Once a customer is logged in, every request the client makes carries their token as `X-Customer-Token` (the key keeps `Authorization`), so catalog, cart and checkout are priced for the customer's group. The kit renews the token before it expires. Every call needs the `customer:session` scope; `config()` also accepts `storefront:read`.

**config()** `Promise\<CustomerAccountsConfig\>`

The shop's settings: `login.enabled`, `login.signupAllowed`, `login.hidePricesForGuests`, `login.hideAddToCartForGuests`, `customerGroups.enabled`, `customerClub.enabled` and `customerClub.joinMethod`. Read once per client.

**login(input)** `Promise\<CustomerSession\>`

Log in and remember the session. Resolves with `{ customer, accessToken, accessTokenExpiresAt, refreshToken, refreshTokenExpiresAt }`. Throws a `ShopkitAuthError`: `invalid_credentials`, `customer_blocked`, `customer_login_disabled`, `rate_limited`. Logging in as a different customer forgets the cart.

**register(input)** `Promise\<CustomerRegisterResult\>`

Create an account (1.10.0). `{ email, password, firstName, lastName, companyName?, companyNumber?, clubOptIn? }`. Resolves with `{ status: "logged_in", ...session }` for a new email, logged in exactly like `login()`; `{ status: "verification_required" }` for the email of an earlier guest customer, where a code is emailed and `resetPassword()` finishes the registration; or, rarely, `{ status: "login_required" }` when the account was created but no session could be opened. Throws a `ShopkitAuthError`: `signup_disabled`, `email_taken`, `invalid_email`, `invalid_name`, `invalid_password`, `customer_login_disabled`, `rate_limited`. See [Registration](https://quickbutik.dev/kit/concepts/customer-accounts.md#registration).

**requestPasswordReset(input)** `Promise\<void\>`

Email a one-time reset code (1.10.0) to the account with `{ email }`. Resolves the same way whether or not the account exists. The code is valid for 30 minutes, and a new request replaces it. Throws only `customer_login_disabled` and `rate_limited`.

**resetPassword(input)** `Promise\<CustomerSession\>`

Set a new password with the emailed code and log in, exactly like `login()` (1.10.0). `{ email, code, password }`; the code ignores case, spaces and dashes. Every other session of the customer ends. Throws a `ShopkitAuthError`: `invalid_reset_code`, `invalid_password`, `customer_blocked`, `customer_login_disabled`, `rate_limited`, or `password_changed_login_required` when the password was changed but no session could be opened. See [Password reset](https://quickbutik.dev/kit/concepts/customer-accounts.md#password-reset).

**logout()** `Promise\<void\>`

Revoke the session on the platform (best effort), then always forget it locally, with the cart id and the checkout session handle. Never throws.

**me()** `Promise\<Customer | null\>`

The profile and `group`. `null` for a guest (no request is made), or when the session ended or changed hands during the read. Concurrent calls share one request.

**club.get()** `Promise\<CustomerClub | null\>`

`{ member, active, points: { balance, lifetime }, reward: { targetPoints, remaining }, earning: { pointsPerUnit, currency } }`, or `null` for a guest.

**setSession(input)** `Promise\<void\>`

Adopt a session minted elsewhere: `{ accessToken, refreshToken?, accessTokenExpiresAt?, refreshTokenExpiresAt? }`. Without `accessTokenExpiresAt`, the token's own `exp` is used. Rejects with a `ShopkitConfigError` for an empty token or an unparseable expiry.

**getAccessToken()** `Promise\<string | null\>`

A valid access token, renewed first when it expires within 30 seconds; `null` for a guest or when the session could not be renewed. Also the way to read the session explicitly from async-only storage.

**onChange(listener)** `() =\> void`

Called with `{ customerId, customer }` on login and on a newly read profile, and with `null` on logout or when the session ends. In a browser the same change is dispatched on `document` as `qb:customer`, with `{ customerId }` only.

**isLoggedIn** `boolean`

Synchronous. With an async-only adapter (Next's `cookies()`) it is `false` until the session has been read.

**current** `Customer | null`

The profile last returned by `login()`, `register()`, `resetPassword()` or `me()` in this client.

**cacheKey** `string`

Who the client's requests are made for, changing on every login and logout. Key your own caches of customer-priced data on it.

See [Customer accounts](https://quickbutik.dev/kit/concepts/customer-accounts.md).

## withStorage

```ts theme={null}
shopkit.withStorage(storage: StorageAdapter): ShopkitClient
```

Returns a copy of the client bound to different storage. The copy drops any `cookies` accessor, so the adapter you pass is the one used. This is the idiomatic way to reuse one configuration across many server requests:

```ts theme={null}
import { createShopkitClient, createRequestCookieStorage } from "@quickbutik/kit"

const base = { publishableKey: process.env.QUICKBUTIK_PUBLISHABLE_KEY! }

export function shopkitFor(request: Request, setCookies: string[]) {
  return createShopkitClient(base).withStorage(
    createRequestCookieStorage(request, { collect: setCookies, attributes: { secure: true } }),
  )
}
```

## Configuration helpers

| Export | Signature | Notes |
| - | - | - |
| `DEFAULT_API_URL` | `"https://commerce.quickbutik.com"` | |
| `DEFAULT_CHECKOUT_URL` | `"https://pay.quickbutik.com"` | |
| `resolveConfig` | `(config: ShopkitConfig) => ResolvedShopkitConfig` | Resolves a config exactly as the client does (defaults, `shopPrefix`, storefront binding, storage prefix). |
| `normalizeApiUrl` | `(url: string) => string` | Strips trailing slashes and a trailing `/v2`. |
| `PUBLISHABLE_KEY_PREFIX` | `"qb_pk_"` | |
| `parsePublishableKey` | `(key: string) => { key, shopPrefix }` | Throws `ShopkitConfigError` for anything that is not a publishable key. |
| `redactKey` | `(key: string) => string` | `"qb_pk_abc123_supersecret"` becomes `"qb_pk_abc123_••••"`. The shop prefix is kept, since it is not secret. |
| `SHOPKIT_SCOPES` | `Record<ShopkitScope, string>` | Every scope a storefront key can carry, with a description. |
| `DEFAULT_SHOPKIT_SCOPES` | `readonly ShopkitScope[]` | Every scope above except `storefront:read`. Includes `customer:session` from 1.9.0. |
| `CUSTOMER_EVENT` | `"qb:customer"` | The DOM event dispatched on `document` on every login, logout and session end. |
| `CUSTOMER_TOKEN_HEADER` | `"X-Customer-Token"` | The header the customer's access token travels in. |
| `createScopeGuard` | `(scopes: readonly string[] \| null \| undefined) => ScopeGuard` | The pre-flight checker the client uses. |
| `STOREFRONT_SURFACES` | `["hosted", "link", "embed", "shopkit", "agentic"]` | |
| `DEFAULT_STOREFRONT_SURFACE` | `"shopkit"` | |
| `STOREFRONT_ID_PATTERN` | `RegExp` | `sf_` plus 26 Crockford base32 characters, case-insensitive. |
| `isStorefrontId` / `isStorefrontSurface` | `(value: unknown) => boolean` | Type guards. |
| `normalizeCurrency` | `(value: string \| null \| undefined, context?: string) => string \| null` | Upper-cases a three-letter code; `null` for empty. Throws `ShopkitConfigError` for anything else. Useful for validating a currency cookie you read yourself. |
| `describeCurrency` | `(shop, selected) => CurrencyInfo` | Resolves a currency choice against `shop.currencies` the way the platform does. See [Utilities](https://quickbutik.dev/kit/reference/utilities.md#currencies). |

## Key rotation

```ts theme={null}
createShopkitClient({
  publishableKey: currentKey,
  onUnauthorized: async () => fetchFreshKeyFromMyBackend(),
})
```

A 401 calls the handler, adopts the returned key and retries the request once. This is outside the normal retry budget: a 401 is a stale credential, not a transient failure.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.