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.
Install
Section titled “Install”npm i @tesseraloyalty/sdk# or: pnpm add @tesseraloyalty/sdk / yarn add @tesseraloyalty/sdk / bun add @tesseraloyalty/sdkimport { TesseraClient } from '@tesseraloyalty/sdk';The client
Section titled “The client”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});| Option | Type | Default | Purpose |
|---|---|---|---|
secretKey | string | — | The bearer key that unlocks every operation. Provide exactly one of secretKey / publishableKey. |
publishableKey | string | — | 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. |
signingSecret | string | — | The per-tenant connector HMAC secret (whsec_…) used to sign events.ingest. A separate credential from the API key; see Request signing. |
channel | string | 'api' | The channel bound to every member-scoped operation. Must be a member of channels when that allowlist is set. |
channels | readonly string[] | — | An optional channel allowlist, enforced at runtime (an out-of-list channel throws pre-network) and, via as const, at compile time. |
program | string | — | 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. |
baseUrl | string | environment preset | The /v1 base URL. Overrides environment — use for local Docker / CI / self-hosted. |
timeoutMs | number | 30000 | Per-request timeout. A timeout is terminal (not retried). |
maxRetries | number | 2 | Retries on retriable failures (network / 5xx / 429), with exponential backoff honoring Retry-After. |
fetch | (input, init) => Promise<Response> | globalThis.fetch | A 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).
Channel binding
Section titled “Channel binding”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 + authtessera.withChannel('shoify'); // ✗ compile error AND a pre-network throwwithChannel(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.
Environments
Section titled “Environments”environment | Base URL |
|---|---|
production | https://api.usetessera.io/v1 |
sandbox | https://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' });Programmes
Section titled “Programmes”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.
Resources
Section titled “Resources”Every resource maps camelCase inputs/outputs to the wire’s snake_case for you — you never touch
snake_case when using the SDK.
rewards
Section titled “rewards”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 programmeconst reserve = await tessera.tiers.list({ program: 'reserve' }); // or name one for this calllist() 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.
programs
Section titled “programs”const club = await tessera.programs.get('copperline-cellar'); // a handle or a lower-case id; a publishable key may call itconst all = await tessera.programs.list(); // secret key only; inactive programmes includedEach 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.
customers
Section titled “customers”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.
events
Section titled “events”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.
Show what a purchase will earn
Section titled “Show what a purchase will earn”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 answerconst { points } = await tessera.earn.preview({ units: [{ unit: 'km', value: flight.distanceKm }] });
// checkout, signed in (secret key): preview the exact event, then book itconst event = buildBookingEvent(user, flight); // your existing IngestEventInputconst quote = await tessera.earn.preview(event); // includes the member's tier multiplier and status (qualifying) pointsawait tessera.events.ingest(event);- Generic or personal. Without
externalIdthe answer is the programme’s generic one (personalised: false,tierKey: null), which a publishable key may ask for. WithexternalId(onchannel, 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 throwsPublishableKeyForbiddenErrorbefore any request. - The result is camelCase:
points.spendableandpoints.qualifying, the rules that applied (rules[].ruleId,name,trigger,campaign,spendable,qualifying,capped), the rules it could not judge (skipped[], each with the input itneeds:amount,itemsorunits),programId,tierKeyandevaluatedAt(an ISO string). accruesAsSentisfalsewhen booking this exact event would be refused, stuck or credited differently, and is expected for a product-page estimate. Without atriggerthe 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 nochannel(ingest requires one, so sendchannel, or name a member, who carries theirs), with notrigger, or with a rule’s input missing (skippedis 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’soccurredAtwas ignored. A generic preview (no member) assumes the booker can earn: underopt_inenrollment, that they have joined.trueis not a promise of the exact figure: an order already pinned to another programme, a concurrent earn against a cap, an already-bookedsourceRef(or an opt-in skip marker) and, onshopifywith catalog enrichment, collection rules on items sent withoutcollectionIds(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. occurredAtjudges 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 itsaccruesAsSentisfalsewhen it sent one.- Channels. Unlike
events.ingest,client.earn.previewchecks an explicitchannelagainst the client’schannelsallowlist, so an event on an unlisted channel is refused locally withconfig_errorinstead 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) needcollectionIdson 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.previewdoes not send the client’sprogram: the API routes the programme as it does forevents.ingest.program.earn.preview(event)on aProgram(seeprograms) names that programme’s id. - Errors.
404 program_not_publishedthrowsNotFoundError(the programme has no published version);422preview_input_required(an overwrite campaign the input cannot decide, so answering could misstate it),event_type_not_earnable(atypeother thanpurchase) and a malformed value (amount_not_integer,item_price_missing, …) throwValidationError; sending none ofamount,itemsorunitsis400 invalid_request(alsoValidationError). A rule whose input is merely missing (amount_missing,items_missing,unit_missing) is never an error: it is listed inskipped; an answer the SDK cannot use throwsinvalid_response.
member(externalId, opts?)
Section titled “member(externalId, opts?)”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(); // MemberBalanceconst status = await member.status(); // MemberStatus (all fields null with no tier program)const profile = await member.get(); // MemberProfile — pseudonymous, no PIImember.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.
redemptions
Section titled “redemptions”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.
Errors
Section titled “Errors”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 class | Wire code | Extra field |
|---|---|---|
ValidationError | invalid_request; the earn preview’s preview_input_required, event_type_not_earnable, amount_not_integer, amount_missing, items_missing, item_price_missing, unit_missing | |
UnauthorizedError | unauthorized | |
SignatureInvalidError | signature_invalid | |
ReplayDetectedError | replay_detected | |
ForbiddenError | forbidden | |
TierGatedError | tier_gated | |
PublishableKeyForbiddenError | publishable_key_forbidden | |
NotFoundError | not_found / program_not_published | |
CustomerNotFoundError | customer_not_found | |
RedemptionNotFoundError | redemption_not_found | |
ConflictError | conflict | |
IdempotencyConflictError | idempotency_key_conflict / idempotency_key_reuse | |
VersionConflictError | version_conflict | |
CapReachedError | cap_reached | |
NotStackableError | not_stackable | |
HoldAlreadyReleasedError | hold_already_released | |
CustomerErasedError | customer_erased | |
PayloadTooLargeError | payload_too_large | |
InsufficientBalanceError | insufficient_balance | .shortfall: number | undefined |
OptionNotEligibleError | option_not_eligible | |
InvalidPayloadError | invalid_payload | |
UnsupportedEventTypeError | unsupported_event_type | |
ProfileValidationError | profile_validation_error | .field: string | undefined |
RateLimitedError | rate_limited | |
InternalError | internal_error | |
NotImplementedError | not_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.
What this SDK is not
Section titled “What this SDK is not”@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.
Versioning
Section titled “Versioning”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.