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:
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:
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.
eldra.cart.addItem(input: {
productId: string;
variantId: string;
quantity: number;
cartId?: string;
attributes?: Record<string, string>;
}, context?): Promise<EldraCart>| Name | Type | Required | What it does |
|---|---|---|---|
input.productId | string | yes | The product the variant belongs to. |
input.variantId | string | yes | The variant to add: the size or colour the shopper picked. |
input.quantity | number | yes | How many to add. |
input.cartId | string | no | The cart to add to. Leave it out to create a new cart. |
input.attributes | Record<string, string> | no | Your own key-value notes on the line. |
input.attribution | object | no | Campaign 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:
| Field | What it is |
|---|---|
id | The cart id. Keep it with createCartSession. |
currency | ISO 4217 code, such as ISK. |
items | The lines: id, productId, variantId, title, quantity, price, thumbnail, productSlug. |
totals | subtotal, discount, taxAmount and total, worked out by the server. |
amountDue | What is still to pay after the gift cards on the cart. |
discountCodes | The codes on the cart, each { code, amount }, in the order added. |
giftCards | The gift cards on the cart, each { entryId, last4, balance, applied, amountDue }. |
expiresAt | When 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 withoutcartId.CART_CUSTOMER_MISMATCH,CART_SIGN_IN_REQUIRED(409) andCART_PRICES_UNAVAILABLE(503): a business customer's cart; see Customer prices.
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.
eldra.cart.get(cartId: string, options?: { locale?: string }, context?): Promise<EldraCart>| Name | Type | Required | What it does |
|---|---|---|---|
cartId | string | yes | The cart to read. |
options.locale | string | no | The 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.
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.
eldra.cart.updateItem(cartId: string, itemId: string, input: { quantity: number }, context?): Promise<EldraCart>| Name | Type | Required | What it does |
|---|---|---|---|
cartId | string | yes | The cart. |
itemId | string | yes | The line to change: an id from cart.items. |
input.quantity | number | yes | The 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.
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.
eldra.cart.removeItem(cartId: string, itemId: string, context?): Promise<EldraCart>| Name | Type | Required | What it does |
|---|---|---|---|
cartId | string | yes | The cart. |
itemId | string | yes | The 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.
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.
eldra.cart.setCurrency(cartId: string, currency: string, context?): Promise<EldraCart>| Name | Type | Required | What it does |
|---|---|---|---|
cartId | string | yes | The cart. |
currency | string | yes | ISO 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: falseand 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.
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.
eldra.cart.applyDiscount(cartId: string, code: string, options?: { locale?: string }, context?):
Promise<{ cart: EldraCart; applied: boolean }>| Name | Type | Required | What it does |
|---|---|---|---|
cartId | string | yes | The cart. |
code | string | yes | The code the shopper typed. Spaces around it are trimmed. |
options.locale | string | no | The 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
| errorId | Status | What it means |
|---|---|---|
CART_DISCOUNT_NOT_USABLE | 404 | The code cannot be used. |
CART_DISCOUNT_EXHAUSTED | 409 | The code has been fully used. |
CART_DISCOUNT_ALREADY_APPLIED | 409 | The cart already holds this code. |
CART_DISCOUNT_NOT_COMBINABLE | 409 | It cannot be used with a code on the cart; errors.blockingCode names that code. |
CART_DISCOUNT_CODES_LIMIT_REACHED | 409 | The cart already holds errors.limit codes (6). |
CART_DISCOUNT_TOO_MANY_ATTEMPTS | 429 | Too many tries on this cart. Gift cards share the same budget. |
CART_DISCOUNT_NOT_FOR_CUSTOMER_PRICES | 409 | A business customer's cart: codes do not combine with their prices. |
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.
eldra.cart.removeDiscount(cartId: string, options?: { locale?: string }, context?): Promise<EldraCart>| Name | Type | Required | What it does |
|---|---|---|---|
cartId | string | yes | The cart. |
options.locale | string | no | The 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.
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.
eldra.cart.removeDiscountEntry(cartId: string, code: string, options?: { locale?: string }, context?): Promise<EldraCart>| Name | Type | Required | What it does |
|---|---|---|---|
cartId | string | yes | The cart. |
code | string | yes | A discountCodes[].code from the cart, in any case. |
options.locale | string | no | The 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.
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.
eldra.cart.applyGiftCard(cartId: string, code: string, options?: { locale?: string }, context?): Promise<EldraCart>| Name | Type | Required | What it does |
|---|---|---|---|
cartId | string | yes | The cart. |
code | string | yes | The gift card code. Spaces around it are trimmed. |
options.locale | string | no | The 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
| errorId | Status | What it means |
|---|---|---|
CART_GIFT_CARD_INVALID | 404 | The code cannot be used. |
CART_GIFT_CARD_EXHAUSTED | 409 | The card has nothing left. |
CART_GIFT_CARD_ALREADY_APPLIED | 409 | The cart already holds this card. |
CART_DISCOUNT_TOO_MANY_ATTEMPTS | 429 | Too many tries; shared with discount codes. |
CART_GIFT_CARD_UNAVAILABLE | 503 | Gift cards cannot be checked now. Try again. |
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 paycart.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.
eldra.cart.applyCode(cartId: string, code: string, options?: { locale?: string }, context?):
Promise<EldraCart & { appliedAs: 'DISCOUNT' | 'GIFT_CARD' }>| Name | Type | Required | What it does |
|---|---|---|---|
cartId | string | yes | The cart. |
code | string | yes | The code the shopper typed. Spaces around it are trimmed. |
options.locale | string | no | The 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
| errorId | Status | What it means |
|---|---|---|
CART_CODE_REQUIRED | 400 | The code was blank. |
CART_CODE_INVALID | 404 | Neither a gift card nor a discount code. |
CART_GIFT_CARD_EXHAUSTED | 409 | The gift card has nothing left. |
CART_GIFT_CARD_ALREADY_APPLIED | 409 | The cart already holds this card. |
CART_DISCOUNT_EXHAUSTED | 409 | The discount code has been fully used. |
CART_DISCOUNT_ALREADY_APPLIED | 409 | The cart already holds this code. |
CART_DISCOUNT_NOT_COMBINABLE | 409 | errors.blockingCode names the code on the cart that blocks it. |
CART_DISCOUNT_CODES_LIMIT_REACHED | 409 | The cart already holds errors.limit codes. |
CART_DISCOUNT_TOO_MANY_ATTEMPTS | 429 | Too many tries on this cart. |
CART_GIFT_CARD_UNAVAILABLE | 503 | Gift cards cannot be checked now, and it is not a discount code. |
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.
eldra.cart.removeGiftCard(cartId: string, options?: { locale?: string }, context?): Promise<EldraCart>| Name | Type | Required | What it does |
|---|---|---|---|
cartId | string | yes | The cart. |
options.locale | string | no | The locale to answer in. |
Returns the cart with an empty giftCards.
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.
eldra.cart.removeGiftCardEntry(cartId: string, entryId: string, options?: { locale?: string }, context?): Promise<EldraCart>| Name | Type | Required | What it does |
|---|---|---|---|
cartId | string | yes | The cart. |
entryId | string | yes | The card's giftCards[].entryId. Not the card's code. |
options.locale | string | no | The 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.
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.
eldra.checkout.url(options: { cartId: string; locale?: string; orgId?: string }, readOptions?: { signal?: AbortSignal }): Promise<string>| Name | Type | Required | What it does |
|---|---|---|---|
options.cartId | string | yes | The cart to check out. |
options.locale | string | no | The checkout's language, sent as lang, such as is-IS. |
options.orgId | string | no | Another organisation than the client's own. |
readOptions.signal | AbortSignal | no | Stops 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".
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.
eldra.orders.get(orderId: string, options?: { accessToken?: string }, context?): Promise<EldraOrder>| Name | Type | Required | What it does |
|---|---|---|---|
orderId | string | yes | The order. |
options.accessToken | string | no | The 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:
| Field | What it is |
|---|---|
id, orderNumber | The order's id and the number the shopper sees. |
status | The order's status. |
createdAt | When it was placed. |
currency | ISO 4217 code. |
orderLines | productName, variantName, quantity, unitPrice, totalPrice, imageUrl. |
subtotalAmount, discountAmount, shippingAmount, taxAmount, totalAmount | The order's totals. |
amountDue | What is left to pay. |
discountCodes | Each code that reduced the order, as { code, amount }. |
contactEmail | Masked 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.
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.
eldra.orders.recover(token: string, context?): Promise<EldraRecoveredBasket>| Name | Type | Required | What it does |
|---|---|---|---|
token | string | yes | The token from the recovery link. Spaces around it are trimmed. |
Returns the recovered basket:
| Field | What it is |
|---|---|
orderId | The abandoned order the link came from. |
cartId | A cart with the lines the shop still sells. Absent when none could be added. |
items | The lines put back, each { productId, variantId, quantity }. |
unavailable | The lines the shop no longer sells, in the same shape. |
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.
eldra.inventory.availability(items: { variantId: string; locationId?: string }[], context?): Promise<EldraStockAvailability>| Name | Type | Required | What it does |
|---|---|---|---|
items[].variantId | string | yes | The variant to check. |
items[].locationId | string | no | The stock location. Left out, the organisation's default location answers. |
Returns { items }, one entry per variant in the order you asked:
| Field | What it is |
|---|---|
variantId | The variant. |
locationId | The location that answered. |
available | Whether it can be bought now. This is what checkout honours. |
availableQuantity | How many are available. |
allowBackorder | Whether it can be ordered when out of stock. |
tracked | Whether the shop tracks stock for it at all. |
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
- SDK reference: creating the client, origins and errors.
- Customer prices: a business customer's cart.
- Sales orders: ordering on account instead of checkout.