Skip to content

Cart, checkout and orders ​

This page covers the client's cart group, the hand-off to the hosted checkout, and the order reads that come after it. It also covers inventory.availability, the stock check a product page makes before it offers Add to cart.

Before you start ​

Keep the cart id. The first cart.addItem creates the cart and answers its id. Store it with createCartSession(), which keeps it in localStorage and never throws where storage is missing:

ts
import { createCartSession, createEldraClient } from '@eldrajs/sdk';

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

Amounts. Cart and order amounts are plain numbers in the cart's currency, with decimals only where the currency has them. ISK has none, so 24900 is 24.900 kr. Format them with formatPrice from @eldrajs/sdk/format.

Errors. Every refusal throws an EldraHttpError. Branch on its errorId, never on the message. errors holds the refusal's details, and isEldraError(error, id) narrows an unknown error for you:

ts
import { isEldraError } from '@eldrajs/sdk';

try {
  await eldra.cart.get(cartId);
} catch (error) {
  if (isEldraError(error, 'CART_NOT_FOUND')) cartSession.forget();
  else throw error;
}

The server may forget a cart. When any call answers CART_NOT_FOUND, forget the stored id and start a new cart.

Business customers. A signed-in business customer gets their own prices in the cart. Your server passes their token in context.headers, and the cart is then bound to that company. The rules and the extra errorIds (CART_CUSTOMER_MISMATCH, CART_SIGN_IN_REQUIRED, CART_PRICES_UNAVAILABLE and more) are in Customer prices.

Every method takes an optional last argument, context: { headers?, signal?, orgId? }. It is left out of the tables below.

The cart ​

cart.addItem ​

Adds a variant to a cart and answers the whole cart. Leave out cartId to create a new cart.

ts
eldra.cart.addItem(input: {
  productId: string;
  variantId: string;
  quantity: number;
  cartId?: string;
  attributes?: Record<string, string>;
}, context?): Promise<EldraCart>
NameTypeRequiredWhat it does
input.productIdstringyesThe product the variant belongs to.
input.variantIdstringyesThe variant to add: the size or colour the shopper picked.
input.quantitynumberyesHow many to add.
input.cartIdstringnoThe cart to add to. Leave it out to create a new cart.
input.attributesRecord<string, string>noYour own key-value notes on the line.
input.attributionobjectnoCampaign tags. The client adds them itself; see the note below.

The client adds the campaign landing it keeps as attribution, once the visitor has consented. Name attribution yourself to send exactly that, or build the client with campaignAttribution: false to send none.

Returns the cart. These are the fields a storefront uses:

FieldWhat it is
idThe cart id. Keep it with createCartSession.
currencyISO 4217 code, such as ISK.
itemsThe lines: id, productId, variantId, title, quantity, price, thumbnail, productSlug.
totalssubtotal, discount, taxAmount and total, worked out by the server.
amountDueWhat is still to pay after the gift cards on the cart.
discountCodesThe codes on the cart, each { code, amount }, in the order added.
giftCardsThe gift cards on the cart, each { entryId, last4, balance, applied, amountDue }.
expiresAtWhen the cart expires.

A line's price is the price of one unit.

Errors worth handling

  • CART_INSUFFICIENT_STOCK (409): there is not enough stock for that quantity. Say "out of stock", not "something went wrong".
  • CART_NOT_FOUND: the stored cart is gone. Forget it and add again without cartId.
  • CART_CUSTOMER_MISMATCH, CART_SIGN_IN_REQUIRED (409) and CART_PRICES_UNAVAILABLE (503): a business customer's cart; see Customer prices.
ts
const cart = await eldra.cart.addItem({
  cartId: cartSession.read() ?? undefined,
  productId: 'prod_lopapeysa_alafoss',
  variantId: 'var_alafoss_m_grey',
  quantity: 1,
});
cartSession.remember(cart.id);

Never sum cart lines yourself

Show totals.total from the answer. Discounts, tax and rounding are applied on the server, so a sum of price × quantity will be wrong as soon as a code is on the cart.

cart.get ​

Reads a cart by id. Use it to show the cart page, or to refresh the cart after the shopper comes back.

ts
eldra.cart.get(cartId: string, options?: { locale?: string }, context?): Promise<EldraCart>
NameTypeRequiredWhat it does
cartIdstringyesThe cart to read.
options.localestringnoThe locale to answer in, such as is-IS.

Returns the cart, with the fields listed under cart.addItem.

Errors worth handling: CART_NOT_FOUND. Forget the stored id and show an empty cart.

ts
const cartId = cartSession.read();
const cart = cartId ? await eldra.cart.get(cartId, { locale: 'is-IS' }) : null;

Never cache a cart

Every cart answer is sent with Cache-Control: private, no-store. Read it per visitor, and never put it in a CDN or route cache.

cart.updateItem ​

Sets a line's quantity. Use it for the plus and minus buttons on the cart page.

ts
eldra.cart.updateItem(cartId: string, itemId: string, input: { quantity: number }, context?): Promise<EldraCart>
NameTypeRequiredWhat it does
cartIdstringyesThe cart.
itemIdstringyesThe line to change: an id from cart.items.
input.quantitynumberyesThe new quantity of the line.

Returns the updated cart.

Errors worth handling: CART_NOT_FOUND. For a business customer's cart, CART_CUSTOMER_MISMATCH, CART_SIGN_IN_REQUIRED and CART_PRICES_UNAVAILABLE.

ts
const line = cart.items![0];
const updated = await eldra.cart.updateItem(cart.id, line.id, { quantity: line.quantity + 1 });

itemId is the line's id, not the variant id.

cart.removeItem ​

Removes one line from the cart.

ts
eldra.cart.removeItem(cartId: string, itemId: string, context?): Promise<EldraCart>
NameTypeRequiredWhat it does
cartIdstringyesThe cart.
itemIdstringyesThe line to remove: an id from cart.items.

Returns the cart without the line.

Errors worth handling: CART_NOT_FOUND. For a business customer's cart, CART_CUSTOMER_MISMATCH and CART_PRICES_UNAVAILABLE. A guest may remove a line from a bound cart.

ts
const updated = await eldra.cart.removeItem(cart.id, line.id);
if (!updated.items?.length) showEmptyCart();

cart.setCurrency ​

Moves the cart to another currency and reprices every line. Call it when the shopper picks a currency the shop offers.

ts
eldra.cart.setCurrency(cartId: string, currency: string, context?): Promise<EldraCart>
NameTypeRequiredWhat it does
cartIdstringyesThe cart.
currencystringyesISO 4217 code, one of the shop's currencies.

Returns the repriced cart. Some things change with it:

  • A line with no price in the new currency stays, with soldInCurrency: false and price 0. It is left out of the totals, and checkout refuses the cart until it is removed.
  • Gift cards are removed, because a card pays only in its own currency.
  • Discount codes that cannot be used in the new currency are removed. The others stay.

Errors worth handling

  • CART_CURRENCY_NOT_SOLD (400): the shop does not offer that currency now.
  • CART_CURRENCY_CUSTOMER_ISK_ONLY (409): a business customer's cart stays in ISK.
ts
import { createCurrencyPreference } from '@eldrajs/sdk';

const currencyPreference = createCurrencyPreference();

const cart = await eldra.cart.setCurrency(cartId, 'EUR');
currencyPreference.remember('EUR');

The shop's currencies come from features.getCommerce(); see Shop settings. createCurrencyPreference() keeps the shopper's choice for their next visit.

Discount codes and gift cards ​

A cart holds several discount codes and several gift cards. Each code applies to what the codes before it left. A cart holds at most 6 discount codes, and two codes sit together only when both allow combining. A refused code leaves the cart as it was.

cart.applyDiscount ​

Adds a discount code to the cart. Use it for a field that takes discount codes only.

ts
eldra.cart.applyDiscount(cartId: string, code: string, options?: { locale?: string }, context?):
  Promise<{ cart: EldraCart; applied: boolean }>
NameTypeRequiredWhat it does
cartIdstringyesThe cart.
codestringyesThe code the shopper typed. Spaces around it are trimmed.
options.localestringnoThe locale to answer in.

Returns { cart, applied }. applied is true when the cart's discountCodes now holds the code. A code can be on the cart and still take 0, for example when nothing is left to reduce.

Errors worth handling

errorIdStatusWhat it means
CART_DISCOUNT_NOT_USABLE404The code cannot be used.
CART_DISCOUNT_EXHAUSTED409The code has been fully used.
CART_DISCOUNT_ALREADY_APPLIED409The cart already holds this code.
CART_DISCOUNT_NOT_COMBINABLE409It cannot be used with a code on the cart; errors.blockingCode names that code.
CART_DISCOUNT_CODES_LIMIT_REACHED409The cart already holds errors.limit codes (6).
CART_DISCOUNT_TOO_MANY_ATTEMPTS429Too many tries on this cart. Gift cards share the same budget.
CART_DISCOUNT_NOT_FOR_CUSTOMER_PRICES409A business customer's cart: codes do not combine with their prices.
ts
try {
  const { cart, applied } = await eldra.cart.applyDiscount(cartId, 'SUMAR10');
  if (!applied) showMessage('That code does not apply to this cart.');
} catch (error) {
  if (isEldraError(error, 'CART_DISCOUNT_NOT_COMBINABLE')) {
    showMessage(`Cannot be combined with ${String(error.errors?.blockingCode)}.`);
  } else throw error;
}

Check applied, not only for errors

A call that succeeds can still answer applied: false. The server drops a code it will not honour, so the returned cart is the verdict.

cart.removeDiscount ​

Removes every discount code from the cart. It succeeds when there is none.

ts
eldra.cart.removeDiscount(cartId: string, options?: { locale?: string }, context?): Promise<EldraCart>
NameTypeRequiredWhat it does
cartIdstringyesThe cart.
options.localestringnoThe locale to answer in.

Returns the cart with an empty discountCodes.

Errors worth handling: CART_SIGN_IN_REQUIRED (409), when a guest writes to a business customer's cart.

ts
const cart = await eldra.cart.removeDiscount(cartId);

To take off one code, use cart.removeDiscountEntry.

cart.removeDiscountEntry ​

Removes one discount code and keeps the others in order. Use it for the remove button next to each code.

ts
eldra.cart.removeDiscountEntry(cartId: string, code: string, options?: { locale?: string }, context?): Promise<EldraCart>
NameTypeRequiredWhat it does
cartIdstringyesThe cart.
codestringyesA discountCodes[].code from the cart, in any case.
options.localestringnoThe locale to answer in.

Returns the cart. A code the cart does not hold answers the cart unchanged, so a double click does not fail.

ts
const cart = await eldra.cart.removeDiscountEntry(cartId, 'SUMAR10');

To change codes after CART_DISCOUNT_NOT_COMBINABLE, remove the blocking code with this method and apply the new one again.

cart.applyGiftCard ​

Adds a gift card to the cart, after any cards already on it. Discount codes stay.

ts
eldra.cart.applyGiftCard(cartId: string, code: string, options?: { locale?: string }, context?): Promise<EldraCart>
NameTypeRequiredWhat it does
cartIdstringyesThe cart.
codestringyesThe gift card code. Spaces around it are trimmed.
options.localestringnoThe locale to answer in.

Returns the cart. Each card in giftCards has last4, its balance, what it pays now (applied) and what is still due after it (amountDue). The cart's amountDue is what is left after every card.

Errors worth handling

errorIdStatusWhat it means
CART_GIFT_CARD_INVALID404The code cannot be used.
CART_GIFT_CARD_EXHAUSTED409The card has nothing left.
CART_GIFT_CARD_ALREADY_APPLIED409The cart already holds this card.
CART_DISCOUNT_TOO_MANY_ATTEMPTS429Too many tries; shared with discount codes.
CART_GIFT_CARD_UNAVAILABLE503Gift cards cannot be checked now. Try again.
ts
const cart = await eldra.cart.applyGiftCard(cartId, 'GC-7Q4M-2KX9-PL');
const card = cart.giftCards?.at(-1);
// "Gjafakort ****" + card.last4, and cart.amountDue left to pay

cart.applyCode ​

Applies a code from one field, as a gift card or as a discount code. Use it when your cart page has a single "Code" field.

ts
eldra.cart.applyCode(cartId: string, code: string, options?: { locale?: string }, context?):
  Promise<EldraCart & { appliedAs: 'DISCOUNT' | 'GIFT_CARD' }>
NameTypeRequiredWhat it does
cartIdstringyesThe cart.
codestringyesThe code the shopper typed. Spaces around it are trimmed.
options.localestringnoThe locale to answer in.

Returns the cart with appliedAs, which says what the code was: DISCOUNT or GIFT_CARD. Applying one kind leaves the other kind on the cart.

Errors worth handling

errorIdStatusWhat it means
CART_CODE_REQUIRED400The code was blank.
CART_CODE_INVALID404Neither a gift card nor a discount code.
CART_GIFT_CARD_EXHAUSTED409The gift card has nothing left.
CART_GIFT_CARD_ALREADY_APPLIED409The cart already holds this card.
CART_DISCOUNT_EXHAUSTED409The discount code has been fully used.
CART_DISCOUNT_ALREADY_APPLIED409The cart already holds this code.
CART_DISCOUNT_NOT_COMBINABLE409errors.blockingCode names the code on the cart that blocks it.
CART_DISCOUNT_CODES_LIMIT_REACHED409The cart already holds errors.limit codes.
CART_DISCOUNT_TOO_MANY_ATTEMPTS429Too many tries on this cart.
CART_GIFT_CARD_UNAVAILABLE503Gift cards cannot be checked now, and it is not a discount code.
ts
const result = await eldra.cart.applyCode(cartId, input.value);
showMessage(result.appliedAs === 'GIFT_CARD' ? 'Gift card added.' : 'Discount applied.');

One message for an unknown code

CART_CODE_INVALID never says which kind of code was tried. Show one message, such as "This code is not valid".

cart.removeGiftCard ​

Removes every gift card from the cart. It succeeds when there is none.

ts
eldra.cart.removeGiftCard(cartId: string, options?: { locale?: string }, context?): Promise<EldraCart>
NameTypeRequiredWhat it does
cartIdstringyesThe cart.
options.localestringnoThe locale to answer in.

Returns the cart with an empty giftCards.

ts
const cart = await eldra.cart.removeGiftCard(cartId);

cart.removeGiftCardEntry ​

Removes one gift card and keeps the others in order. Use it for the remove button next to each card.

ts
eldra.cart.removeGiftCardEntry(cartId: string, entryId: string, options?: { locale?: string }, context?): Promise<EldraCart>
NameTypeRequiredWhat it does
cartIdstringyesThe cart.
entryIdstringyesThe card's giftCards[].entryId. Not the card's code.
options.localestringnoThe locale to answer in.

Returns the cart. An entryId the cart does not hold answers the cart unchanged, so a double click does not fail.

ts
for (const card of cart.giftCards ?? []) {
  // render "**** {card.last4}" with a remove button that calls:
  // eldra.cart.removeGiftCardEntry(cart.id, card.entryId)
}

Checkout ​

checkout.url ​

Answers the address of the platform's hosted checkout for a cart. Send the shopper there when they press Check out.

ts
eldra.checkout.url(options: { cartId: string; locale?: string; orgId?: string }, readOptions?: { signal?: AbortSignal }): Promise<string>
NameTypeRequiredWhat it does
options.cartIdstringyesThe cart to check out.
options.localestringnoThe checkout's language, sent as lang, such as is-IS.
options.orgIdstringnoAnother organisation than the client's own.
readOptions.signalAbortSignalnoStops your own wait. The shared read carries on for others.

Returns a URL string. The client reads the checkout's address from platform.config() once per client and reuses it.

Errors worth handling: none from the gateway. It rejects with a plain Error in three cases: the platform published no checkout URL, the read failed (the failure is the error's cause), or the published value is not an absolute http(s) URL. Treat all three as "no Check out button to show".

ts
const href = await eldra.checkout.url({ cartId: cart.id, locale: 'is-IS' }).catch(() => null);
if (href) window.location.assign(href);

Never build the checkout URL yourself

The platform decides where checkout lives, and it differs between staging and production. Always ask checkout.url().

Orders ​

orders.get ​

Reads one order. Use it on the order status page after checkout, or from the link in the confirmation mail.

ts
eldra.orders.get(orderId: string, options?: { accessToken?: string }, context?): Promise<EldraOrder>
NameTypeRequiredWhat it does
orderIdstringyesThe order.
options.accessTokenstringnoThe order's access token, sent as X-Order-Token. See below.

The access token is the one the order's creation returned (valid 7 days), or the one in the confirmation mail's link (valid 30 days). createOrderAccessTokens() keeps it in sessionStorage, so it never lands in a URL or a log.

Returns the order. These are the fields a status page uses:

FieldWhat it is
id, orderNumberThe order's id and the number the shopper sees.
statusThe order's status.
createdAtWhen it was placed.
currencyISO 4217 code.
orderLinesproductName, variantName, quantity, unitPrice, totalPrice, imageUrl.
subtotalAmount, discountAmount, shippingAmount, taxAmount, totalAmountThe order's totals.
amountDueWhat is left to pay.
discountCodesEach code that reduced the order, as { code, amount }.
contactEmailMasked when the order is read with a token.

Errors worth handling: ORDER_LINK_EXPIRED (410), when a mailed link is past its end. errors.maskedEmail names the address, so you can say where a new link would go.

ts
import { createOrderAccessTokens } from '@eldrajs/sdk';

const orderTokens = createOrderAccessTokens();
const order = await eldra.orders.get(orderId, {
  accessToken: orderTokens.read(orderId) ?? undefined,
});
// "Pöntun #" + order.orderNumber, formatPrice(order.totalAmount, order.currency, 'is-IS')

orders.recover ​

Turns the token from an abandoned-checkout recovery link into a cart again. Call it on the page the recovery link opens.

ts
eldra.orders.recover(token: string, context?): Promise<EldraRecoveredBasket>
NameTypeRequiredWhat it does
tokenstringyesThe token from the recovery link. Spaces around it are trimmed.

Returns the recovered basket:

FieldWhat it is
orderIdThe abandoned order the link came from.
cartIdA cart with the lines the shop still sells. Absent when none could be added.
itemsThe lines put back, each { productId, variantId, quantity }.
unavailableThe lines the shop no longer sells, in the same shape.
ts
const basket = await eldra.orders.recover(tokenFromLink);
if (basket.cartId) {
  cartSession.remember(basket.cartId);
  if (basket.unavailable?.length) showMessage('Some items are no longer for sale.');
  navigateTo('/cart');
}

Stock ​

inventory.availability ​

Checks stock for several variants in one call. Use it on a product page to disable sizes that are sold out.

ts
eldra.inventory.availability(items: { variantId: string; locationId?: string }[], context?): Promise<EldraStockAvailability>
NameTypeRequiredWhat it does
items[].variantIdstringyesThe variant to check.
items[].locationIdstringnoThe stock location. Left out, the organisation's default location answers.

Returns { items }, one entry per variant in the order you asked:

FieldWhat it is
variantIdThe variant.
locationIdThe location that answered.
availableWhether it can be bought now. This is what checkout honours.
availableQuantityHow many are available.
allowBackorderWhether it can be ordered when out of stock.
trackedWhether the shop tracks stock for it at all.
ts
const { items } = await eldra.inventory.availability(
  product.variants.map((variant) => ({ variantId: variant.id }))
);
const soldOut = new Set(items?.filter((item) => !item.available).map((item) => item.variantId));

Read available, not the quantity

available is what checkout honours. Base your Add to cart button on it, not on availableQuantity.

See also ​

Eldra