Skip to content

SDK reference

@tesseraloyalty/sdk wraps /v1 and owns the error-prone plumbing — bearer auth, HMAC request signing, idempotency, cursor pagination, retries with backoff, and a typed error taxonomy — so your backend can drive the whole member journey in a handful of lines. This page is the canonical reference for the SDK’s surface; for a walkthrough, start with Getting started.

It runs anywhere the Web fetch standard exists — Node 20+, edge/Workers, Deno, Bun — ships ESM + CommonJS with bundled types, and has zero runtime dependencies.

Terminal window
npm i @tesseraloyalty/sdk
# or: pnpm add @tesseraloyalty/sdk / yarn add @tesseraloyalty/sdk / bun add @tesseraloyalty/sdk
import { TesseraClient } from '@tesseraloyalty/sdk';

TesseraClient takes exactly one API key plus optional transport and channel settings.

const tessera = new TesseraClient({
secretKey: process.env.TESSERA_SECRET_KEY, // unlocks every operation (server-side only)
signingSecret: process.env.TESSERA_SIGNING_SECRET, // SEPARATE connector secret, for events.ingest
channel: 'shopify', // the channel bound to every member operation
});
OptionTypeDefaultPurpose
secretKeystring—The bearer key that unlocks every operation. Provide exactly one of secretKey / publishableKey.
publishableKeystring—A bearer key for public reads only — the calls it may make are rewards.list(), tiers.list() and programs.get(ref). Any secret-scope call fails fast, pre-network, with PublishableKeyForbiddenError.
signingSecretstring—The per-tenant connector HMAC secret (whsec_…) used to sign events.ingest. A separate credential from the API key; see Request signing.
channelstring'api'The channel bound to every member-scoped operation. Must be a member of channels when that allowlist is set.
channelsreadonly string[]—An optional channel allowlist, enforced at runtime (an out-of-list channel throws pre-network) and, via as const, at compile time.
programstring—The programme the client acts in: a handle ('vv') or a lower-case id. Sent on the programme-scoped calls; a malformed value throws pre-network. See Programmes.
environment'production' | 'sandbox''production'The hosted environment. Picks the base URL from a preset. Ignored when baseUrl is set.
baseUrlstringenvironment presetThe /v1 base URL. Overrides environment — use for local Docker / CI / self-hosted.
timeoutMsnumber30000Per-request timeout. A timeout is terminal (not retried).
maxRetriesnumber2Retries on retriable failures (network / 5xx / 429), with exponential backoff honoring Retry-After.
fetch(input, init) => Promise<Response>globalThis.fetchA custom fetch implementation (tests, proxies, older runtimes).

A secretKey client can call everything; a publishableKey client can only call rewards.list(), tiers.list() and programs.get(ref).

A member operation never takes a per-call channel — it’s bound once on the client, so a 'shopify'-here / 'shoify'-there typo can’t silently split a customer’s identity and ledger.

const tessera = new TesseraClient({
secretKey: process.env.TESSERA_SECRET_KEY,
channels: ['shopify', 'pos', 'api'] as const, // typed as a literal union
channel: 'shopify',
});
const pos = tessera.withChannel('pos'); // a clone bound to 'pos', sharing transport + auth
tessera.withChannel('shoify'); // ✗ compile error AND a pre-network throw

withChannel(channel) derives a channel-scoped clone for the rare legitimate multi-channel case — it shares the parent’s transport, auth, and signing secret. When channels is passed as a const array, TesseraClient is generic over that literal union, so a channel typo is a type error, not a runtime surprise.

environmentBase URL
productionhttps://api.usetessera.io/v1
sandboxhttps://sandbox.usetessera.io/v1
const tessera = new TesseraClient({ secretKey: process.env.TESSERA_SECRET_KEY, environment: 'sandbox' });
// local dev / CI — an explicit baseUrl wins, environment is ignored:
const local = new TesseraClient({ secretKey: 'sk_test_local', baseUrl: 'http://localhost:3100/v1' });

On a workspace with more than one programme, name the one a client acts in with program, or derive a client with withProgram (SDK 0.8.0):

const vv = tessera.withProgram('vv'); // a derived client; the original is untouched
await vv.rewards.list();
await vv.member('cust_5512').balance();
await vv.member('cust_5512').redeem({ requestedPoints: 500, cart });

program is sent on rewards.list, tiers.list, the member reads (balance, status, history), redemptions.place / member.redeem and discounts.evaluate, and on no other call. A value that is not a handle or a lower-case id throws a config_error before any request. With none, the request is the one 0.7.0 sent, and a workspace with several programmes answers 400 program_required. A publishable key that names a programme which is not active (not the default, and claiming no sales channel) gets 404 not_found, as for an unknown one. See Working with more than one programme.

client.cartAttributes() returns [{ key: 'tessera_program', value: handle }] for a headless cart, and [] when the client names no programme. It is pure, makes no request, and needs the handle rather than the id. client.cartAttributes({ ref }) adds tessera_redemption for a checkout redemption from client.checkoutRedemptions.place; see Redeem points on a headless cart.

Every resource maps camelCase inputs/outputs to the wire’s snake_case for you — you never touch snake_case when using the SDK.

const { pointsLabel, data: rewards } = await tessera.rewards.list();

list() is one of the three calls a publishable key may make (the others are tiers.list() and programs.get(ref)). See Enroll members onward for the full catalogue → redeem journey.

const { program, data: tiers } = await tessera.tiers.list(); // the client's programme
const reserve = await tessera.tiers.list({ program: 'reserve' }); // or name one for this call

list() returns the programme’s tier rules (program, or null when it has no tier programme) and its ladder (data, by displayOrder, ascending): each tier’s qualifyThreshold, holdThreshold, earnMultiplier, lifetimeThreshold and the rewardEligibility ids from rewards.list(). It reads no member, so a publishable key may call it. For one member’s tier and progress, use member(id).status(). A per-call program overrides the client’s and is checked before any request. See Reading balances.

const club = await tessera.programs.get('copperline-cellar'); // a handle or a lower-case id; a publishable key may call it
const all = await tessera.programs.list(); // secret key only; inactive programmes included

Each is a read-only Program: id, handle, name (null until the merchant sets one), pointsLabel, active and isDefault, with tiers.list(), rewards.list(), discounts.evaluate(), earn.preview(), member(id) (balance, status, history, redeem) and cartAttributes() bound to that programme’s id. Neither call sends the client’s program, and a Program ignores it. programs.get checks ref before any request (config_error) and throws invalid_response if the answer is not the programme asked for. A Program is a snapshot, so fetch one per request. See Working with more than one programme.

Secret-scope only. Create-or-update, partial-update, decrypted PII reads, and manual channel linking:

const customer = await tessera.customers.upsert({
externalId: 'cust_5512',
email: 'ada@example.com',
name: 'Ada Lovelace',
}); // { customerUuid, channel, externalId, created, updatedAt }
await tessera.customers.update(customer.customerUuid, { birthday: '1990-05-01' });
await tessera.customers.getPii(customer.customerUuid);
await tessera.customers.linkChannel(customer.customerUuid, { channel: 'pos', externalId: 'pos-8841' });
await tessera.customers.unlinkChannel(customer.customerUuid, 'pos', 'pos-8841');

A null profile field clears it server-side; an absent field is left untouched. See Enroll members for the wire-level detail and error codes.

Secret-scope, and requires signingSecret — both checked pre-network. ingest HMAC-signs the exact bytes it sends and posts them; you never construct the signature yourself:

const event = await tessera.events.ingest({
type: 'purchase',
channel: 'shopify',
externalId: 'cust_5512',
sourceRef: 'ord_9001',
idempotencyKey: 'shopify:ord_9001-purchase',
occurredAt: new Date(),
trigger: 'payment_captured',
amount: { netOfTaxShipping: 4200, currency: 'USD' }, // minor units
});
console.log(event.status); // 'accepted' (first sighting) | 'duplicate' (deduped redelivery)

Pass items when the program has rules that reason about what was bought rather than only how much was spent — product_is, product_in_collection, or an item_subtotal / item_quantity earning base. Only productId is required; omit the rest and the server applies its defaults:

await tessera.events.ingest({
type: 'purchase',
channel: 'shopify',
externalId: 'cust_5512',
sourceRef: 'ord_9002',
idempotencyKey: 'shopify:ord_9002-purchase',
occurredAt: new Date(),
trigger: 'payment_captured',
amount: { netOfTaxShipping: 6000, currency: 'USD' },
items: [
{
productId: 'gid://shopify/Product/8801',
collectionIds: ['gid://shopify/Collection/311'],
quantity: 2,
unitPriceCents: 2500,
},
{ productId: 'gid://shopify/Product/8815', unitPriceCents: 1000 },
],
});

Omitting items sends no items key at all, so an integration that does not use item-scoped rules needs no change.

See Earning events and Request signing.

earn.preview(event) shows what a purchase will earn, from the programme’s own rules, rather than copying its arithmetic into your app. It takes the same object events.ingest takes (here every field is optional, and the booking fields — sourceRef, idempotencyKey, orderRef, email, phone — are accepted and not sent), evaluates the published programme and books nothing. Send at least one of amount, items or units.

A flight search for a logged-out visitor (a publishable key is enough) and a signed-in checkout that previews the exact event before booking it:

// flight search, logged out (publishable key): the programme's generic answer
const { points } = await tessera.earn.preview({ units: [{ unit: 'km', value: flight.distanceKm }] });
// checkout, signed in (secret key): preview the exact event, then book it
const event = buildBookingEvent(user, flight); // your existing IngestEventInput
const quote = await tessera.earn.preview(event); // includes the member's tier multiplier and status (qualifying) points
await tessera.events.ingest(event);
  • Generic or personal. Without externalId the answer is the programme’s generic one (personalised: false, tierKey: null), which a publishable key may ask for. With externalId (on channel, else the client’s bound channel) it is that member’s, with their tier multiplier and cap headroom (personalised: true) and needs a secret key; a publishable key throws PublishableKeyForbiddenError before any request.
  • The result is camelCase: points.spendable and points.qualifying, the rules that applied (rules[].ruleId, name, trigger, campaign, spendable, qualifying, capped), the rules it could not judge (skipped[], each with the input it needs: amount, items or units), programId, tierKey and evaluatedAt (an ISO string).
  • accruesAsSent is false when booking this exact event would be refused, stuck or credited differently, and is expected for a product-page estimate. Without a trigger the preview evaluates the programme’s rules for every trigger they hook and adds them up, which is what a fully-signalled order earns over its life. Booking an event with no channel (ingest requires one, so send channel, or name a member, who carries theirs), with no trigger, or with a rule’s input missing (skipped is not empty), would not accrue as sent; nor would one for a member who has not joined an opt-in programme, one whose named programme is not where ingest would route it (another programme’s claimed channel, or the default programme when no programme claims the channel), or one where a publishable key’s occurredAt was ignored. A generic preview (no member) assumes the booker can earn: under opt_in enrollment, that they have joined. true is not a promise of the exact figure: an order already pinned to another programme, a concurrent earn against a cap, an already-booked sourceRef (or an opt-in skip marker) and, on shopify with catalog enrichment, collection rules on items sent without collectionIds (resolved only when the order is booked) can still make the booked amount differ, or leave the event stuck.
  • Caps. A rule’s cap lowers the figure (capped: true): for a member by what they have left of it, and for a generic preview or a member new to the programme by the whole cap, which is what a first booking would be credited.
  • occurredAt judges the rules (a campaign’s dates, say) at that instant, and is honoured only for a secret key. A publishable key is always evaluated at the time of the request, and its accruesAsSent is false when it sent one.
  • Channels. Unlike events.ingest, client.earn.preview checks an explicit channel against the client’s channels allowlist, so an event on an unlisted channel is refused locally with config_error instead of being sent.
  • Publishable keys. A publishable key is for a generic preview; call it from your server or edge.
  • Collection rules (product_in_collection) need collectionIds on each item, as on an ingested event; without them the rule does not match, and the preview does not guess.
  • Rule names may be shown to customers, so write them as you would write them on a product page.
  • Programmes. client.earn.preview does not send the client’s program: the API routes the programme as it does for events.ingest. program.earn.preview(event) on a Program (see programs) names that programme’s id.
  • Errors. 404 program_not_published throws NotFoundError (the programme has no published version); 422 preview_input_required (an overwrite campaign the input cannot decide, so answering could misstate it), event_type_not_earnable (a type other than purchase) and a malformed value (amount_not_integer, item_price_missing, …) throw ValidationError; sending none of amount, items or units is 400 invalid_request (also ValidationError). A rule whose input is merely missing (amount_missing, items_missing, unit_missing) is never an error: it is listed in skipped; an answer the SDK cannot use throws invalid_response.

The ergonomic read + redeem surface, bound to (channel, externalId) — opts.channel overrides the client’s bound channel for just this handle (still validated against channels):

const member = tessera.member('cust_5512', { channel: 'shopify' });
const balance = await member.balance(); // MemberBalance
const status = await member.status(); // MemberStatus (all fields null with no tier program)
const profile = await member.get(); // MemberProfile — pseudonymous, no PII

member.history(opts?) returns a HistoryPager — both awaitable (resolves the first page) and async-iterable (auto-follows the cursor):

for await (const entry of member.history({ types: ['earn', 'burn'] })) {
console.log(entry.type, entry.currency, entry.amount, entry.sourceRef);
}
// …or just the first page:
const page = await member.history({ limit: 50 });
console.log(page.data.length, 'entries; more?', page.page.hasMore);

member.redeem(input, opts?) is sugar over redemptions.place(...) with the handle’s externalId/channel already supplied — see below.

Secret-scope; the burn-hold lifecycle (place → finalize or release):

const redemption = await member.redeem({ optionId: rewards.find((r) => r.kind === 'points_value')?.id, requestedPoints: 500, cart: { channel: 'api', lines: [{ lineId: 'l1', productId: 'sku_42', quantity: 1, lineSubtotalCents: 4200 }] } });
// …order is placed…
await redemption.finalize({ sourceChannel: 'shopify', sourceRef: 'ord_9001' });
// …or, on an abandoned cart: await redemption.release();

redemption here is a RedemptionHandle — the placed-hold fields plus .finalize()/.release() bound to its id, so the storefront flow chains without threading the id back through tessera.redemptions. Calling tessera.redemptions.place(...) directly needs an explicit externalId/channel instead of a bound handle. place requires an Idempotency-Key; when you omit opts.idempotencyKey the SDK generates a UUID and holds it constant across that call’s own retries. See Redemptions & holds and Idempotency.

Every failure is a TesseraError (or a subclass) carrying the stable, snake_case code from the API envelope, plus status, requestId (the X-Request-Id, for support), and structured details. Catch by type — never string-match code yourself:

import { InsufficientBalanceError, TierGatedError, TesseraError } from '@tesseraloyalty/sdk';
try {
const r = await member.redeem({ requestedPoints: 500, cart: { channel: 'api', lines: [{ lineId: 'l1', productId: 'sku_42', quantity: 1, lineSubtotalCents: 4200 }] } });
await r.finalize({ sourceChannel: 'shopify', sourceRef: 'ord_9001' });
} catch (err) {
if (err instanceof InsufficientBalanceError) {
console.log('short by', err.shortfall); // number | undefined, from details.shortfall
} else if (err instanceof TierGatedError) {
// option requires a higher tier than the member holds
} else if (err instanceof TesseraError) {
console.log(err.code, err.status, err.requestId); // any other code, including an unrecognized one
}
}

A new server code never crashes an old SDK: an unrecognized code resolves to the base TesseraError (its code preserved), never a throw. errorFromEnvelope is the factory that builds the right subclass; CODE_TO_ERROR exports the full map.

Error classWire codeExtra field
ValidationErrorinvalid_request; the earn preview’s preview_input_required, event_type_not_earnable, amount_not_integer, amount_missing, items_missing, item_price_missing, unit_missing
UnauthorizedErrorunauthorized
SignatureInvalidErrorsignature_invalid
ReplayDetectedErrorreplay_detected
ForbiddenErrorforbidden
TierGatedErrortier_gated
PublishableKeyForbiddenErrorpublishable_key_forbidden
NotFoundErrornot_found / program_not_published
CustomerNotFoundErrorcustomer_not_found
RedemptionNotFoundErrorredemption_not_found
ConflictErrorconflict
IdempotencyConflictErroridempotency_key_conflict / idempotency_key_reuse
VersionConflictErrorversion_conflict
CapReachedErrorcap_reached
NotStackableErrornot_stackable
HoldAlreadyReleasedErrorhold_already_released
CustomerErasedErrorcustomer_erased
PayloadTooLargeErrorpayload_too_large
InsufficientBalanceErrorinsufficient_balance.shortfall: number | undefined
OptionNotEligibleErroroption_not_eligible
InvalidPayloadErrorinvalid_payload
UnsupportedEventTypeErrorunsupported_event_type
ProfileValidationErrorprofile_validation_error.field: string | undefined
RateLimitedErrorrate_limited
InternalErrorinternal_error
NotImplementedErrornot_implemented

Pre-network failures (bad config, an out-of-allowlist channel, a missing signing secret) throw a base TesseraError with the SDK-local code config_error and no status. An API answer the SDK cannot use (today: programs.get answering with a programme other than the one asked for, or either call answering with a malformed programme) throws the SDK-local code invalid_response. See Errors & the envelope for what each code means on the wire, and Error handling for retry patterns.

@tesseraloyalty/sdk is a loyalty-operations client for an already-provisioned tenant under a per-tenant API key. It deliberately does not cover merchant signup/provisioning, or program configuration — your programme’s rules, tiers, reward options, points label, branding. Those are managed in the merchant console, not the SDK.

VERSION (exported from the package) is the SDK’s own semver; API_VERSION names the operations API version it targets (currently 'v1'). See Changelog & versioning for the compatibility policy. The package is published on npm under the MIT license.