Skip to content

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.

bash
pnpm add @eldrajs/sdk

Create 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.

ts
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.

ts
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.

OptionTypeDefaultWhat it does
orgIdstring, or a functionread from envYour organisation. Sent as the X-Org-Id header on every organisation read.
siteIdstring, or a functionread from envThe 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.
apiBaseUrlstring, or a functionread from env, else https://web.eldra.app/apiThe gateway to call. Set it for staging or local development.
previewTokenstring, 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.
buildTokenstring, 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.
envRecord<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.
headersHeadersInit, or a function—Headers sent on every request. A call's own headers override these.
fetchtypeof fetchthe global fetchThe 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 transportReplaces the transport completely. fetch and retry are then ignored.
campaignAttribution{ storage } or falsebrowser localStorageWhere 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:

ValueKeys, in order
orgIdELDRA_ORG_ID, VITE_ELDRA_ORG_ID, NEXT_PUBLIC_ELDRA_ORG_ID, NUXT_PUBLIC_ELDRA_ORG_ID, PUBLIC_ELDRA_ORG_ID
siteIdELDRA_SITE_ID, VITE_ELDRA_SITE_ID, NEXT_PUBLIC_ELDRA_SITE_ID, NUXT_PUBLIC_ELDRA_SITE_ID, PUBLIC_ELDRA_SITE_ID
apiBaseUrlELDRA_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.

ts
// 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, HEAD and OPTIONS are repeated. A POST that 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 at maxDelayMs.
  • Any other status, such as 404 or 422, fails on the first answer.
  • An aborted signal stops it at once, even mid-wait.
ts
// 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.

FieldTypeWhat it does
orgIdstringThe organisation for this call only, overriding the client's orgId.
headersHeadersInitExtra headers for this call. They override the client's headers of the same name.
signalAbortSignalCancels the call, and any retry wait.
ts
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.

ts
eldra.request<T>(options: {
  path: string;
  method?: string;
  query?: object;
  body?: unknown;
  orgId?: string;
  headers?: HeadersInit;
  signal?: AbortSignal;
}): Promise<T>
OptionTypeDefaultWhat it does
pathstring—The route, relative to apiBaseUrl, such as /site/v1/seo.
methodstringGET, or POST when body is setThe HTTP method.
queryobject—Query parameters. Empty values are skipped. Arrays are joined with commas, except filter, categoryId, collectionId, option and ext, which repeat the key.
bodyunknown—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.

ts
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.ts and index.ts: createWebStudioClient, initWebStudioClient and getWebStudioClient, the same three functions with your CMS types applied.

Without the plugin, responses are unknown and you name the type at the call site.

ts
// vite.config.ts
import { defineConfig } from 'vite';
import { eldra } from '@eldrajs/sdk/vite';

export default defineConfig({
  plugins: [eldra({ orgId: process.env.ELDRA_ORG_ID })],
});
ts
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 cart

Commit 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.

OptionTypeDefaultWhat it does
orgIdstring, or a functionread from envThe organisation whose schemas and contract to fetch. Required, unless skipOnMissingConfig is set.
apiBaseUrlstring, or a functionread from env, else https://web.eldra.app/apiThe gateway to fetch from.
previewTokenstring, or a function—Sent as X-Preview-Token while fetching. Never written into the generated files.
envobject, or a function—Extra environment values, read last.
headersHeadersInit, or a function—Headers sent while fetching.
schemasstring[]all schemasGenerate types for these CMS schema API ids only.
maxDepthnumber—How deep related entries are typed. Left out, the gateway decides.
moduleNamestringEldraCMSThe name the CMS types are generated under.
outDirstring.eldra/web-studioWhere the files go, relative to the nearest package.json.
typesFileNamestringcms-types.tsThe CMS types file.
contractbooleantruefalse skips the gateway contract. CMS types are still generated.
contractFileNamestringcontract.tsThe contract file.
clientFileNamestringclient.tsThe typed client wrapper file.
indexFileNamestringindex.tsThe file that re-exports the others.
sdkImportstring@eldrajs/sdkThe specifier the generated files import the SDK from.
fetchtypeof fetchthe global fetchThe fetch used while generating.
skipOnMissingConfigbooleanfalseWith 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.

FieldTypeWhat it holds
statusnumberThe HTTP status, such as 409.
statusTextstringThe HTTP status text.
codestring | undefinedThe class of failure, such as CONFLICT or NOT_FOUND. Several different refusals share one.
errorIdstring | undefinedThe specific failure, such as CART_INSUFFICIENT_STOCK. Equals code when there is nothing more specific.
errorsRecord<string, unknown> | undefinedExtra detail, which depends on the errorId. For example errors.blockingCode on CART_DISCOUNT_NOT_COMBINABLE.
bodyunknownThe whole response body.
messagestringWeb 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.

ts
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 TypeError from fetch when the network fails after every retry, or an abort error when your signal fires.
  • EldraIdempotencyKeyError from salesOrders.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 Error from the features reads when no orgId is 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.

Eldra