Skip to content

SDK reference ​

Everything @eldrajs/sdk does, in detail. New to the kit? Start with the Quickstart and Getting started.

You need one thing from your Eldra organisation: its organisation id. It is on the General settings page in Studio. Everything a storefront reads is public data for that organisation, so there is no API key.

bash
pnpm add @eldrajs/sdk
ts
import { createEldraClient } from '@eldrajs/sdk';

const eldra = createEldraClient({ orgId: process.env.ELDRA_ORG_ID! });

const { data: products } = await eldra.catalog.listProducts();
const product = await eldra.catalog.getProduct(products![0].id);

The client is plain fetch. It runs in a browser, in Node, in a server-rendered request, in an edge function. Create it once per app, or once per request on the server — it holds no state beyond its options.

Several websites in one organisation ​

An organisation can run more than one website, each with its own pages and settings. Name the one you read with siteId (its id is in Studio under the site's settings; a theme build Eldra runs gets it as ELDRA_SITE_ID, beside ELDRA_ORG_ID):

ts
const eldra = createEldraClient({
  orgId: process.env.ELDRA_ORG_ID!,
  siteId: process.env.ELDRA_SITE_ID,
});

The client sends it as the siteId query parameter on the reads whose answer is one site's — the CMS reads by schema (cms.list, cms.get, cms.getEntryByUniqueField), forms.get and forms.submit, and the site reads /site/v1/theme-messages, /design-tokens, /site-icons, /seo, /crawl, /site-profile and /redirects through request — and on no other route. Left out (or given env without ELDRA_SITE_ID), nothing is sent: an organisation with one site answers as it always has, and one with several refuses those reads with 400 CMS_SITE_REQUIRED (CMS) or 400 SITE_REQUIRED (site reads).

Where it points ​

By default at https://web.eldra.app/api. For staging or local development pass apiBaseUrl:

ts
createEldraClient({ orgId, apiBaseUrl: 'https://web.staging.eu.eldra.app/api' });

That one setting also decides where checkout lives: checkout.url() reads it from the gateway the client points at, so a staging cart is handed to the staging checkout with nothing else to set.

Every option can also be a function, so a server-rendered app can read environment at request time:

ts
createEldraClient({ orgId: () => useRuntimeConfig().public.eldraOrgId });

Preview mode ​

Pass previewToken to read CMS content using a preview token. It accepts a string or a callback resolved for each request. For a server-side client:

ts
const eldra = createEldraClient({
  orgId: process.env.ELDRA_ORG_ID,
  previewToken: () => process.env.ELDRA_PREVIEW_TOKEN,
});

A non-empty token sets X-Preview-Token on SDK requests, overriding that header in client or request-context headers. Returning undefined or an empty string stops setting the header; without a custom preview header, requests use the normal published-content behavior. Explicit custom headers are preserved when previewToken is unset. The SDK does not discover a preview token from environment variables automatically.

The Vite plugin accepts the same option separately:

ts
eldra({
  orgId: process.env.ELDRA_ORG_ID,
  previewToken: () => process.env.ELDRA_PREVIEW_TOKEN,
});

It sends the header when fetching both CMS types and the gateway contract. It does not put the token in request URLs or generated files, and configuring it on the plugin does not configure runtime clients. Keep preview tokens in the preview session or server configuration, rather than public environment variables or committed generated code. See the type-checked preview example.

Browsers and origins ​

A browser may read anything from any address: products, content, carts and orders. Only requests that spend something are tied to the organisation's own addresses: every cart change, applying or removing a discount, placing an order, a sales order, a booking and a form submission. From an address the organisation has not registered they fail with 403 ORIGIN_NOT_REGISTERED. Analytics events from such an address are dropped. Register addresses in Studio under Settings → General → Site addresses: the storefront address, plus Other sites for previews, staging and http://localhost:3000 (or whichever port) while developing. A registered https://shop.is also covers https://www.shop.is. Calls from a server send no Origin and are not subject to this.

Forms without a theme ​

Site forms work for a headless app that has no theme and no page builder:

  • Switch on the FORMS feature. Forms have their own organisation feature, separate from PAGE_BUILDER; a platform admin enables it for the organisation. Without it the form read and submit answer 403 with errorId: FEATURE_DISABLED (an EldraHttpError). The organisation's site, which forms hang off, is created the first time a form is created in Studio.
  • Register your app's origin in Studio, under Settings → General → Site addresses, as above; a browser read or submit from any other origin is refused.
  • Render it with SiteForm. @eldrajs/ui's SiteForm draws any definition and does everything below for you: <SiteForm :definition="form" :client="eldra" locale="is-IS" /> (see packages/ui/README.md, "Site forms"). The rest of this list is what it does, for an app that draws its own.
  • Call the SDK. eldra.forms.get(key) returns the definition to render, and eldra.forms.submit(key, { values, locale, pagePath, turnstileToken?, hp? }) posts a submission (a 422 resolves as field-keyed errors). Render the honeypot field the definition names off-screen and send it as hp. When the definition carries a Turnstile site key, your app must render the Cloudflare Turnstile widget and send its token as turnstileToken; the SDK does not render it.
  • Consent for a subscribing form. The definition's consentText (a sentence per locale, the shop name already filled in; only on a form that subscribes) is the wording the visitor agrees to. Show it next to the submit button as plain text; your app sends no extra field. The platform stores that sentence in the locale you send, followed by the label of each ticked consent field, a SHA-256 of it, the form key and name, and pagePath (the page the submission came from, supplied by your app, so send location.pathname). IP addresses and user agents are deliberately not stored (data minimisation).

confirm(token) and unsubscribe(token) finish a subscriber's emailed links. You do not need to build pages or proxy routes for them: the confirm and unsubscribe links in form mails point straight at the web gateway's own page (<web-gateway origin>/api/site/v1/forms/subscriptions/confirm?token=… and …/unsubscribe?token=…), never at your storefront's domain. The page asks the subscriber to press a button, which posts the token back, so a mail scanner that prefetches the link changes nothing. Call confirm/unsubscribe yourself only if you want to host that step in your own UI.

Analytics tracker ​

A Nuxt theme on @eldrajs/theme-nuxt needs none of this: the module loads the tracker on production builds by itself (see Built-in analytics). Everything below is for a site that is not a theme-nuxt theme.

The tracker is a script tag served by the same gateway the client reads from. Build it from the client's configuration so the two can never point at different environments:

ts
// nuxt.config.ts or app.vue
import { analyticsTrackerScript } from '@eldrajs/sdk';

const tracker = analyticsTrackerScript({ orgId: process.env.ELDRA_ORG_ID, apiBaseUrl });
useHead({ script: tracker ? [tracker] : [] });

It returns undefined when no organisation id is configured, so a preview or development build that should not report simply leaves the id unset. Events are only counted from a registered storefront origin (see above); an unregistered one is silently ignored. Pass eventOrigin when the script and the event endpoint are proxied through the storefront's own domain.

What the client covers ​

GroupMethods
cataloglistProducts, getProduct, listCategories, listCollections, getCollection, listCollectionProducts, listBrands, getBrand, search
cmslist, get, getEntryByUniqueField, resolveEntryList — typed by the generator below
cartaddItem (creates the cart when there is none), get, updateItem, removeItem, applyDiscount, removeDiscount, removeDiscountEntry, applyCode, applyGiftCard, removeGiftCard, removeGiftCardEntry
checkouturl({ cartId, locale }) — the platform-hosted checkout takes it from there
ordersget(orderId, { accessToken }), recover(token)
inventoryavailability
featuresthe organisation's enabled features
platformconfig() — the platform's public settings, cached per client; today the checkout URL
formsget(key), submit(key, { values, locale, pagePath }) (a 422 resolves as field errors), confirm(token), unsubscribe(token)

Totals come from the server. The cart's totals are the truth; never sum lines in the storefront.

Handing the cart to checkout ​

The checkout page is the platform's, not yours: await eldra.checkout.url({ cartId, locale }) reads where it lives from GET /platform/v1/config (public, cached for the life of the client) and returns {checkoutUrl}/checkout/{orgId}/{cartId}. Resolve it whenever you have a cart id and show your Check out control once it does; it rejects — rather than returning a half-built link — when the platform published no checkout URL, when the read failed, and when the published value is not an absolute http(s) URL, with a distinct message for each. A storefront that keeps the control hidden in that case stays usable either way. The read takes no organisation header (the route is organisation-independent) and is shared by every caller of one client, so its only per-call option is a signal that abandons your own wait.

Eldra's emails link into your storefront: a campaign may link to a product, collection, category or page, and its product cards link to each product. Eldra builds those links from the storefront address set in Studio (Settings, Your sites) and this convention, so serve these routes:

ItemPath
Product/products/<slug>
Collection/collections/<slug>
Category/categories/<path>: the slugs from the top category down, /categories/men/jackets
Page/<slug>, after its parents' slugs when it has a parent: /about, /about/team

A page is an entry of the organisation's page content type: its slug, and its parent when it has one. A site deployed through Eldra as a theme follows its route templates instead (themes).

Generated types ​

The SDK ships with no response types. They come from your gateway, generated into your project by the Vite plugin on every dev start and build:

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

export default defineConfig({
  plugins: [eldra({ orgId: process.env.ELDRA_ORG_ID })],
});

It writes .eldra/web-studio/:

  • cms-types.ts — your organisation's CMS schemas, so eldra.cms.list('page') knows the fields of page.
  • contract.ts — the gateway's own API (cart, orders, catalog, checkout, inventory), from /api/public/openapi.json. It fills the SDK's EldraContract in, so every method — cart.get, catalog.listProducts, orders.recover — is typed against exactly the gateway you point at. Staging gives you staging's contract; production, production's.
  • client.ts and index.ts — a WebStudioClient wrapper with the CMS types applied.

The folder is written beside the nearest package.json — the project root, even where the Vite root is a subfolder, as it is in Nuxt (app/). A relative outDir is resolved against the same place.

Commit the folder. It then exists without a running gateway: CI type-checks against what was last generated and reviewed, and when the backend changes the diff shows in the pull request. A fetch that fails at dev start leaves the previous file in place and shows as a build warning saying what was skipped and why — a wrong URL or an unknown organisation id is a warning, never an error. Keep the folder whole: index.ts re-exports the other files, so delete all of it or none.

Nuxt ​

Nuxt copies typescript.tsConfig.include entries verbatim into .nuxt/tsconfig*.json, so the path is relative to .nuxt/, not to the project:

ts
// nuxt.config.ts
export default defineNuxtConfig({
  vite: { plugins: [eldra({ orgId: process.env.ELDRA_ORG_ID })] },
  typescript: { tsConfig: { include: ['../.eldra/**/*.ts'] } },
});

Without that include the generated contract.ts is not in the type-check program, nothing augments EldraContract, and every response is unknown — the same as having no plugin at all, which is what makes it easy to miss. Importing anything from .eldra/web-studio also pulls it in.

Without the plugin — a Node script, a framework the plugin does not cover yet — responses are unknown and you name the type at the call site:

ts
const products = await eldra.catalog.listProducts<{ data: { title: string }[] | null }>();

For any path the client does not wrap by name, once generated:

ts
import type { EldraContractResponse } from '@eldrajs/sdk';
type Categories = EldraContractResponse<'/catalog/v1/categories', 'get'>;

The gateway's contract is versioned by semver — a minor bump adds, a major bump changes or removes — and the generated ELDRA_CONTRACT_VERSION says which one you built against.

Rich text ​

CMS rich text fields hold a TipTap document. Render it with RichText from @eldrajs/vue, or to an HTML string with toHtml from @eldrajs/rich-text in any framework. See rich-text.md.

Images ​

A media URL from the API serves an 800 px copy, which is soft anywhere wider. Use responsiveImage from the SDK, or EldraImage from @eldrajs/vue, so the browser picks a size:

vue
<EldraImage
  :src="product.thumbnail"
  :alt="product.thumbnail?.altText || product.title"
  sizes="(min-width: 1024px) 25vw, 50vw"
  :aspect-ratio="4 / 5"
/>

docs/images.md has the variants, how to choose sizes, and the hero and banner cases.

Persisting the cart ​

createCartSession() keeps the cart id in localStorage, createOrderAccessTokens() keeps order tokens in sessionStorage; both take an injectable storage and never throw where storage is unavailable. The server may forget a cart; when a request fails with errorId CART_NOT_FOUND, drop the stored id and start a new cart.

Campaign attribution ​

Call captureCampaignAttribution() in the browser on the first page and after every navigation, and grantCampaignAttributionConsent() / withdrawCampaignAttributionConsent() from your consent tool. Once the visitor agrees, the kit keeps a campaign landing's utm_source, utm_medium, utm_campaign and utm_id for 30 days, and cart.addItem sends them with every add so the order is credited to the campaign. Without consent nothing is kept. Campaign tags only, nothing about the visitor, and nothing on a server. A theme on @eldrajs/theme-nuxt captures without code and takes the consent answer from the window. Details in packages/sdk/README.md.

Errors ​

Every failed request throws EldraHttpError with status, code and errorId from the gateway's problem body. code is the category, such as NOT_FOUND or CONFLICT; errorId is the specific reason, such as CART_NOT_FOUND, CART_INSUFFICIENT_STOCK or CART_DISCOUNT_EXHAUSTED, and equals code when the gateway has nothing more specific to say. Branch on errorId, not on the message; the node script example prints both. A refusal that says more carries it in errors, the problem's errors object: a discount code refused with CART_DISCOUNT_NOT_COMBINABLE names the code on the cart that blocks it in errors.blockingCode ("cannot be combined with SUMMER10"), and CART_DISCOUNT_CODES_LIMIT_REACHED the limit in errors.limit.

Applying a discount code adds it to the cart's codes (contract 6.9.0): the cart's discountCodes lists each as {code, amount}, removeDiscountEntry(cartId, code) takes one off and removeDiscount(cartId) takes them all off.

Eldra