The client
@eldrajs/sdk talks to Eldra's public storefront API. It is plain fetch, so it runs in a browser, in Node, in a server render and at the edge. This page covers creating the client, its options, the options every call takes, typed responses and errors.
pnpm add @eldrajs/sdkCreate a client
Call createEldraClient with your organisation id. The id is on the API & tracking settings page in Studio. A storefront reads public data, so there is no API key.
import { createEldraClient } from '@eldrajs/sdk';
const eldra = createEldraClient({ orgId: process.env.ELDRA_ORG_ID! });
const { data: sweaters } = await eldra.catalog.listProducts();The client holds nothing but its options. Create it once per app in a browser. On a server you can create one per request, or share one and pass per-request values as functions (see below).
The client groups its methods by area: catalog, cms, cart, checkout, orders, inventory, features, platform, forms, customer and salesOrders. Each area has its own page; see More SDK pages.
One shared client
initEldraClient(options) creates a client and keeps it as the app's default. getEldraClient() returns that default anywhere else in your code. It throws when initEldraClient has not run yet.
import { getEldraClient, initEldraClient } from '@eldrajs/sdk';
initEldraClient({ orgId: import.meta.env.VITE_ELDRA_ORG_ID });
// Later, in another module:
const product = await getEldraClient().catalog.getProduct(productId);Options
Every option is optional. The options marked "or a function" also take a function that returns the value. The client calls it on every request, so a server can read config at request time.
| Option | Type | Default | What it does |
|---|---|---|---|
orgId | string, or a function | read from env | Your organisation. Sent as the X-Org-Id header on every organisation read. |
siteId | string, or a function | read from env | The website to read, when the organisation runs several. Sent as the siteId query parameter on the CMS reads by schema, forms.get, forms.submit and the site reads. A siteId in a call's own query wins. |
apiBaseUrl | string, or a function | read from env, else https://web.eldra.app/api | The gateway to call. Set it for staging or local development. |
previewToken | string, or a function | — | Sent as X-Preview-Token, so CMS reads return draft content. Overrides the same header in headers and in a call's context. Empty or undefined sends nothing. |
buildToken | string, or a function | — | A read-only build token (eldra_bld_…) sent as X-Eldra-Build-Token. Build reads then count against the build's own rate limit instead of the machine's address. |
env | Record<string, string | boolean | number | undefined>, or a function | — | Where to look for orgId, siteId and apiBaseUrl when they are not given. Pass process.env or import.meta.env. |
headers | HeadersInit, or a function | — | Headers sent on every request. A call's own headers override these. |
fetch | typeof fetch | the global fetch | The fetch the client uses. Pass one in a runtime without a global fetch, or to add a timeout. |
retry | { attempts?, baseDelayMs?, maxDelayMs? } | { attempts: 5, baseDelayMs: 250, maxDelayMs: 5000 } | How the client tries again after a 429, a 503 or a dropped connection. See Retries. |
httpClient | (request) => Promise<T> | the built-in fetch transport | Replaces the transport completely. fetch and retry are then ignored. |
campaignAttribution | { storage } or false | browser localStorage | Where cart.addItem reads the campaign landing it sends as attribution. false sends none. See Campaign attribution. |
env is searched for each value under five spellings, first match wins:
| Value | Keys, in order |
|---|---|
orgId | ELDRA_ORG_ID, VITE_ELDRA_ORG_ID, NEXT_PUBLIC_ELDRA_ORG_ID, NUXT_PUBLIC_ELDRA_ORG_ID, PUBLIC_ELDRA_ORG_ID |
siteId | ELDRA_SITE_ID, VITE_ELDRA_SITE_ID, NEXT_PUBLIC_ELDRA_SITE_ID, NUXT_PUBLIC_ELDRA_SITE_ID, PUBLIC_ELDRA_SITE_ID |
apiBaseUrl | ELDRA_API_BASE_URL, VITE_ELDRA_API_BASE_URL, NEXT_PUBLIC_ELDRA_API_BASE_URL, NUXT_PUBLIC_ELDRA_API_BASE_URL, PUBLIC_ELDRA_API_BASE_URL |
The default base URL is exported as DEFAULT_ELDRA_API_BASE_URL.
// A server render: config is read on every request.
const eldra = createEldraClient({
env: process.env, // reads ELDRA_ORG_ID, ELDRA_SITE_ID and ELDRA_API_BASE_URL
previewToken: () => process.env.ELDRA_PREVIEW_TOKEN,
});Keep the build token on the server
buildToken belongs in a build or a server only. Never pass it from code that runs in a browser, and never put it in public config. Never pass a site deploy token here.
Preview mode, several sites and browser origins are covered in more depth in the SDK reference.
Retries
The gateway limits how many requests one address makes per minute. A static build meets that limit often. So the client tries again on a 429, on a 503 and on a dropped connection:
- Only
GET,HEADandOPTIONSare repeated. APOSTthat timed out may already have been applied. - It honours the gateway's
Retry-After, up to one minute. - Otherwise it waits
baseDelayMs, doubling each attempt, capped atmaxDelayMs. - Any other status, such as
404or422, fails on the first answer. - An aborted
signalstops it at once, even mid-wait.
// One request, no waiting:
createEldraClient({ orgId, retry: { attempts: 0 } });attempts counts the first try, so 0 and 1 both mean no retry.
Per-call context
Most methods take an optional last argument, the request context. Use it for what differs between calls: a signed-in customer's token, a timeout, another organisation.
| Field | Type | What it does |
|---|---|---|
orgId | string | The organisation for this call only, overriding the client's orgId. |
headers | HeadersInit | Extra headers for this call. They override the client's headers of the same name. |
signal | AbortSignal | Cancels the call, and any retry wait. |
import { customerHeaders } from '@eldrajs/sdk';
const cart = await eldra.cart.get(
cartId,
{ locale: 'is-IS' },
{
headers: customerHeaders(session.accessToken, session.customerId),
signal: AbortSignal.timeout(5000),
}
);The client always sets X-Org-Id, X-Preview-Token and X-Eldra-Build-Token itself, after your headers. To change one of those, use the matching option, not a header.
platform.config() is the one exception. It takes { signal } only, because its answer is the same for every caller and is cached for the life of the client.
Calling a route without a method
request calls any gateway route the client has no named method for. It adds the same headers, siteId, retries and errors as every other method.
eldra.request<T>(options: {
path: string;
method?: string;
query?: object;
body?: unknown;
orgId?: string;
headers?: HeadersInit;
signal?: AbortSignal;
}): Promise<T>| Option | Type | Default | What it does |
|---|---|---|---|
path | string | — | The route, relative to apiBaseUrl, such as /site/v1/seo. |
method | string | GET, or POST when body is set | The HTTP method. |
query | object | — | Query parameters. Empty values are skipped. Arrays are joined with commas, except filter, categoryId, collectionId, option and ext, which repeat the key. |
body | unknown | — | Sent as JSON. A string, FormData, URLSearchParams, Blob or ArrayBuffer is sent as it is. |
orgId, headers, signal | — | The same as the per-call context. |
Returns the parsed JSON body, the text for a non-JSON answer, or undefined for a 204.
interface SiteSeo {
title?: string;
description?: string;
}
const seo = await eldra.request<SiteSeo>({ path: '/site/v1/seo' });Typed responses
The package ships no response types. They come from the gateway you point at, through the Vite plugin. On every dev start and build it writes .eldra/web-studio/:
cms-types.ts: your CMS schemas as types.contract.ts: the gateway's API as types. Every client method is then typed against it.client.tsandindex.ts:createWebStudioClient,initWebStudioClientandgetWebStudioClient, the same three functions with your CMS types applied.
Without the plugin, responses are unknown and you name the type at the call site.
// vite.config.ts
import { defineConfig } from 'vite';
import { eldra } from '@eldrajs/sdk/vite';
export default defineConfig({
plugins: [eldra({ orgId: process.env.ELDRA_ORG_ID })],
});import { createWebStudioClient } from './.eldra/web-studio';
const eldra = createWebStudioClient({ orgId: import.meta.env.VITE_ELDRA_ORG_ID });
const cart = await eldra.cart.get(cartId); // typed as your gateway's cartCommit the folder. CI then type-checks without a running gateway, and an API change shows up as a diff in the pull request. A fetch that fails leaves the previous files in place and logs a build warning.
Plugin options
The plugin reads orgId and apiBaseUrl from the same environment keys as the client. It looks in your .env files for the current Vite mode, then process.env, then its own env option.
| Option | Type | Default | What it does |
|---|---|---|---|
orgId | string, or a function | read from env | The organisation whose schemas and contract to fetch. Required, unless skipOnMissingConfig is set. |
apiBaseUrl | string, or a function | read from env, else https://web.eldra.app/api | The gateway to fetch from. |
previewToken | string, or a function | — | Sent as X-Preview-Token while fetching. Never written into the generated files. |
env | object, or a function | — | Extra environment values, read last. |
headers | HeadersInit, or a function | — | Headers sent while fetching. |
schemas | string[] | all schemas | Generate types for these CMS schema API ids only. |
maxDepth | number | — | How deep related entries are typed. Left out, the gateway decides. |
moduleName | string | EldraCMS | The name the CMS types are generated under. |
outDir | string | .eldra/web-studio | Where the files go, relative to the nearest package.json. |
typesFileName | string | cms-types.ts | The CMS types file. |
contract | boolean | true | false skips the gateway contract. CMS types are still generated. |
contractFileName | string | contract.ts | The contract file. |
clientFileName | string | client.ts | The typed client wrapper file. |
indexFileName | string | index.ts | The file that re-exports the others. |
sdkImport | string | @eldrajs/sdk | The specifier the generated files import the SDK from. |
fetch | typeof fetch | the global fetch | The fetch used while generating. |
skipOnMissingConfig | boolean | false | With no orgId, skip generation with a warning instead of failing the build. |
The plugin does not configure the client
The plugin's orgId and previewToken are only for fetching types. Pass them to createEldraClient too.
@eldrajs/sdk/vite also exports generateEldraFiles(root, options, mode?), the same generation without Vite. It resolves to { written, skipped }: the paths it wrote, and what it skipped and why. createContractSource and retargetSdkAugmentation are the lower-level steps it uses.
More on generated types, including Nuxt and product extensions, is in the SDK reference.
Errors
A request the gateway refuses throws EldraHttpError. Branch on errorId, never on the message.
| Field | Type | What it holds |
|---|---|---|
status | number | The HTTP status, such as 409. |
statusText | string | The HTTP status text. |
code | string | undefined | The class of failure, such as CONFLICT or NOT_FOUND. Several different refusals share one. |
errorId | string | undefined | The specific failure, such as CART_INSUFFICIENT_STOCK. Equals code when there is nothing more specific. |
errors | Record<string, unknown> | undefined | Extra detail, which depends on the errorId. For example errors.blockingCode on CART_DISCOUNT_NOT_COMBINABLE. |
body | unknown | The whole response body. |
message | string | Web Studio request failed with <status> <statusText>. For logs only. |
isEldraError(error, errorId) checks the class and the errorId in one step. For known ids it also types errors.
import { EldraHttpError, isEldraError } from '@eldrajs/sdk';
try {
await eldra.cart.addItem({ cartId, productId: lopiSweater, variantId: greyMedium, quantity: 2 });
} catch (error) {
if (isEldraError(error, 'CART_INSUFFICIENT_STOCK')) {
showMessage('Only a few of this sweater are left. Try a smaller quantity.');
} else if (isEldraError(error, 'CART_NOT_FOUND')) {
cartSession.forget(); // the server dropped the cart: start a new one
} else if (error instanceof EldraHttpError) {
console.error(error.status, error.errorId);
showMessage('Something went wrong. Please try again.');
} else {
throw error; // network failure or abort
}
}Other things a call can throw:
- A
TypeErrorfromfetchwhen the network fails after every retry, or an abort error when yoursignalfires. EldraIdempotencyKeyErrorfromsalesOrders.create, before anything is sent, when the idempotency key is missing or invalid. It is a bug in the calling code: fix it, never retry.- A plain
Errorfrom thefeaturesreads when noorgIdis set anywhere.
Catch EldraIdempotencyKeyError by class
It extends TypeError, like a lost connection does. A lost connection may follow a placed sales order, so retry that one with the same key. Never treat every TypeError the same.
More SDK pages
- Catalog: products, categories, collections, brands and search.
- Content: CMS entries, entry lists and forms.
- Cart and checkout: the cart, discount codes, gift cards, checkout and orders.
- Shop: business customers, customer prices and sales orders.
- Helpers: storage, images, analytics, attribution, formatting and more.