Node SDK reference

On this page

@tenthbilling/node is Tenth's server SDK. Use it to check access, spend credits, give grants, manage Stripe subscriptions, read the event feed, verify webhooks and mint customer tokens. It has no runtime dependencies. For other languages, call the REST API directly.

Use it only on your server. It takes a secret key, which can act for every customer of its app. Publishable keys belong in apps, with @tenthbilling/expo.

Install

Terminal
npm install @tenthbilling/node

TypeScript
import { Tenth } from '@tenthbilling/node';

const tenth = new Tenth({ secretKey: process.env.TENTH_SECRET_KEY! });

Load the key from your secret store or environment, never from source code.

Runtimes

The package is ESM only. It uses the global fetch (or one you pass in) and Node's node:crypto and Buffer.

RuntimeStatus
Node 24 or laterSupported and tested.
Deno 2, including Supabase Edge FunctionsWorks through Deno's Node compatibility. Import it as npm:@tenthbilling/node.
Bun, Cloudflare Workers and othersNot tested. Runtimes that provide node:crypto and Buffer should work.

The package's engines field only names Node, because npm's engines can't describe other runtimes. Deno ignores it.

Deno and new releases: recent Deno versions refuse npm versions published less than 24 hours ago, by default ("blocked by the minimum dependency age policy"). To install a release on its first day, pass --minimum-dependency-age=0, or wait a day.

Options

OptionTypeDefaultDescription
secretKeystringrequiredtenth_test_sk_... or tenth_live_sk_.... A publishable key throws publishable_key_not_allowed; anything else malformed throws invalid_config.
baseUrlstringhttps://api.tenthbilling.comThe API origin. Must be https, except plain http to localhost, 127.0.0.1 or [::1]. No path, query or credentials.
timeoutMsnumber10000Timeout for each attempt, in milliseconds.
maxRetriesnumber2Retries after the first attempt. 0 turns retries off.
fetchfunctionthe global fetchA custom fetch implementation.

The client keeps the key in a private field, so it doesn't show up in console.log, util.inspect or JSON.stringify.

Per-call options

Every method takes an optional RequestOptions object as its last argument:

OptionDescription
idempotencyKeySent as Idempotency-Key on mutating requests. See Idempotency and retries.
timeoutMsOverrides the client's per-attempt timeout.
maxRetriesOverrides the client's retry count.
signalAn AbortSignal. Aborting throws TenthError with code aborted.

Customers and access

Customers are identified by their app_user_id: your user ID, the one your app's sign-in tokens carry (the token's sub claim, unless you chose another claim). See Customer identity.

TypeScript
// Gate a feature
if (await tenth.hasEntitlement(userId, 'pro')) {
  // ...
}

// Full state: entitlements, credit balances, subscriptions
const state = await tenth.customers.get(userId);

MethodReturnsDescription
hasEntitlement(appUserId, entitlement)booleanTrue when the entitlement is active now. An unknown customer returns false, not an error.
customers.get(appUserId)CustomerStateEntitlements, credit balances and subscriptions.
customers.entitlements(appUserId){ entitlements }Just the entitlements. The fastest way to check access.
customers.alias(appUserId, body){ outcome, customer }Makes body.alias (another app user ID) resolve to this customer.
customers.update(appUserId, body)CustomerStateSets email and merges attributes.
customers.delete(appUserId)voidDeletes the customer's personal data. Financial records stay.

CustomerState has customer, entitlements (a record by entitlement key), credits (a record of { balance, available } by credit type) and subscriptions. The Expo SDK reference lists every field.

customers.alias body: alias (string, required) and merge_policy ('transfer_purchases', 'keep_existing' or 'reject'). outcome is 'added', 'already_aliased', 'merged' or 'kept_existing'.

hasEntitlement and unknown customers: a customer Tenth has never seen has no entitlements, so hasEntitlement returns false when the API answers 404 not_found. You don't need your own 404 handling for it. Every other error (a bad key, a network failure) still throws. customers.get and customers.entitlements do throw not_found for an unknown customer.

customers.update body: email (string up to 320 characters, or null to clear it) and attributes, which are merged into the customer's stored attributes:

  • keys are 1 to 100 characters, with no control characters and no leading or trailing spaces;
  • values are a string (up to 1,000 characters), a number, a boolean, or null, which removes that attribute;
  • at most 50 attributes per call.

Attributes can only be set with a secret key, from your server. They're for your own records: they aren't returned in CustomerState or webhooks, and they appear only in the customer's data export (GET /v1/customers/{id}/export). Apps can't set them, because anything an app sends can be changed by its user. To bill a team or workspace rather than a person, see Billing a team or workspace.

Credits

TypeScript
const { balance, replayed } = await tenth.credits.debit(userId, 'ai_tokens', {
  amount: 25,
  idempotency_key: `job-${jobId}`,
});

MethodReturnsDescription
credits.get(appUserId, query?){ balances, transactions }Balances and recent transactions. Query: credit_type, before (page back), limit.
credits.debit(appUserId, creditType, body)CreditDebitResultSpends credits.
credits.reserve(appUserId, creditType, body)CreditHoldHolds credits for long-running work.
credits.commit(appUserId, creditType, holdId, body?)CreditDebitResultSpends a hold. Committing less than the hold releases the rest.
credits.release(appUserId, creditType, holdId)CreditHoldReleases a hold without spending.

debit body: amount (required), idempotency_key and metadata (a record of string, number, boolean or null).

reserve body: amount (required), idempotency_key and ttl_seconds (how long the hold lasts; the API's default is 900).

commit body: amount (optional; leave it out to spend the whole hold).

CreditDebitResult is { credit_type, amount, balance, available, replayed, transactions }. replayed is true when the idempotency key was used before, so nothing new was spent. CreditHold is { id, credit_type, amount, status, expires_at, created_at }, where status is 'held', 'committed', 'released' or 'expired'.

When the balance is too low, the call throws TenthError with code insufficient_credits (unless the credit type allows a negative balance).

Reserve, then commit

Use a hold when the work takes a while and its cost isn't known up front:

TypeScript
const hold = await tenth.credits.reserve(userId, 'ai_tokens', {
  amount: 100,
  idempotency_key: `reserve-${jobId}`,
});
try {
  const used = await runJob();
  await tenth.credits.commit(userId, 'ai_tokens', hold.id, { amount: used });
} catch (err) {
  await tenth.credits.release(userId, 'ai_tokens', hold.id);
  throw err;
}

Grants

Grants give an entitlement or credits without a payment, such as for beta testers or support. A grant creates the customer if they're new.

TypeScript
const grant = await tenth.grants.create(userId, {
  entitlement: 'pro',
  reason: 'Beta tester',
  expires_at: '2027-01-01T00:00:00Z',
});

await tenth.grants.revoke(grant.id);

MethodReturnsDescription
grants.create(appUserId, body)GrantGives an entitlement or credits.
grants.revoke(grantId)GrantRevokes a grant. Unspent granted credits are removed.

create body:

FieldDescription
reasonRequired. Why you gave it.
entitlementThe entitlement to give.
credit_typeThe credit type to give.
amountCredits to give (credit grants only).
starts_atISO 8601. Entitlement grants can start later; credits are granted now.
expires_atISO 8601. Leave it out for no expiry.

Grant is { id, customer_id, entitlement, credit_type, amount, starts_at, expires_at, reason, created_by, revoked_at, created_at }.

Events and revenue

The event feed lists everything that happened to your customers, oldest first. Each entry's payload is the same body a webhook delivers.

TypeScript
for await (const event of tenth.events.listAll({ after: lastProcessedId })) {
  await handle(event.payload);
  await saveCursor(event.id);
}

MethodReturnsDescription
events.list(query?){ data, has_more }One page of events. Query: after (an event ID), limit, type, customer (an app_user_id).
events.listAll(query?)async iterator of FeedEventEvery event after query.after, page by page.
revenueTransactions.list(query?){ data, has_more }One page of revenue transactions. Query: after, limit, from and to (by occurred_at).
revenueTransactions.listAll(query?)async iterator of RevenueTransactionEvery revenue transaction matching query.

A FeedEvent is { id, type, created_at, payload }.

A RevenueTransaction has provider (stripe, apple or google), platform (ios, android or web), type (purchase, renewal, refund, refund_reversal, chargeback or chargeback_reversal), and the IDs of the customer, subscription, purchase and product it belongs to.

Stripe subscriptions and refunds

These work on Stripe subscriptions and purchases only. App Store and Google Play subscriptions are managed in the store. Subscription IDs come from CustomerState.subscriptions[].id.

MethodReturnsDescription
subscriptions.change(id, body)CustomerStateMoves the subscription to another product.
subscriptions.cancel(id, body?)CustomerStateCancels, at the end of the period by default.
subscriptions.resume(id)CustomerStateResumes a subscription.
subscriptions.anchor(id, body)CustomerStateMoves the subscription to a fixed billing day.
purchases.refund(id, body?)CustomerStateRefunds a Stripe one-time purchase.

change body: product (required), timing ('immediately' or 'period_end'; defaults to the new product's setting) and proration ('create_prorations', 'none' or 'always_invoice').

cancel body: at_period_end (default true).

anchor body: day (required), first_period (required: 'prorate', 'free_until_anchor' or 'full_then_anchor'), month, timezone and minimum_first_period_days.

TypeScript
// Bill on the 10th from now on, prorating the first period
await tenth.subscriptions.anchor(subscriptionId, { day: 10, first_period: 'prorate' });

refund body: amount in minor units (cents for USD). Leave it out to refund the full amount.

Purchase IDs for purchases.refund are Tenth's own IDs, not Stripe's. CustomerState lists subscriptions but not one-time purchases, so get the ID from one of these:

  • purchase_id on a revenue transaction (revenueTransactions.list);
  • data.subject.id on a purchase.completed event, from a webhook or the event feed.

Checkout, payment intents and receipts

These start payments or submit store purchases for a customer from your server. Each body takes an app_user_id naming the customer.

MethodReturnsDescription
checkoutSessions.create(body){ id, url }Starts a hosted Stripe Checkout. Send the customer to url.
paymentIntents.create(body){ id, form, client_secret, publishable_key, stripe_account }Starts an embedded Stripe payment, for Stripe's Payment Element or PaymentSheet.
receipts.submit(body){ provisional, customer }Submits an App Store or Google Play purchase.

checkoutSessions.create body: app_user_id, product (a catalog key), and either both success_url and cancel_url (any https URLs), or return: 'app' to return to the app through its URL scheme instead. Send one or the other: return: 'app' with either URL fails with validation_failed, and so does leaving out a URL without return: 'app'.

TypeScript
// Back to your site
const { url } = await tenth.checkoutSessions.create({
  app_user_id: userId,
  product: 'pro_yearly',
  success_url: 'https://example.com/billing/done',
  cancel_url: 'https://example.com/billing',
});

// Back to the app, through the URL scheme set in Settings → Web
const session = await tenth.checkoutSessions.create({
  app_user_id: userId,
  product: 'pro_yearly',
  return: 'app',
});

paymentIntents.create body: app_user_id, product, form ('elements', the default, or 'payment_sheet') and return_url (where redirect-based payment methods return, for elements). Pass stripe_account to Stripe.js when it isn't null.

receipts.submit body:

  • App Store: { app_user_id, platform: 'ios', signed_transaction }, where signed_transaction is StoreKit 2's signed transaction: the JWS string from Transaction.jwsRepresentation (or the signedTransactionInfo of a verified App Store Server API response), at most 32 KB. Tenth checks Apple's signature and certificate chain, the bundle ID and the environment, then reads the transaction from Apple.
  • Google Play: { app_user_id, platform: 'android', purchase_token, product_id, type }, where type is 'subscription' or 'one_time' and product_id is the Play product ID (for subscriptions, the subscription ID).

provisional is true when Tenth granted access from the verified transaction while Apple couldn't be reached.

The Expo SDK already does all of this for purchases made in your app. Use these only when your server drives the payment itself.

Idempotency and retries

Every mutating request (anything but a GET) carries an Idempotency-Key header. It's the idempotencyKey you pass in the last argument, or a random UUID. The SDK reuses the same key on every retry, so a retry after a dropped connection can't apply twice.

To make your own retries safe too (a job that runs again, say), pass a key that's stable for that piece of work:

TypeScript
await tenth.grants.create(
  userId,
  { entitlement: 'pro', reason: 'Referral reward' },
  { idempotencyKey: `referral-${referralId}` },
);

Keys are 1 to 255 printable ASCII characters.

Credit spends (credits.debit and credits.reserve) also take an idempotency_key in the body. The same key never spends twice. If you pass only one of idempotency_key and idempotencyKey, the SDK uses it for both. If you pass neither, it generates one, which protects the SDK's own retries but not yours.

Retries:

  • Network errors, timeouts, HTTP 429 and 5xx are retried, up to maxRetries times (2 by default).
  • Waits use exponential backoff with jitter: 50 to 100% of 0.5 s × 2^attempt, at most 8 s.
  • A Retry-After header is honored, up to 30 seconds.
  • Other 4xx responses are never retried.
  • Each attempt has its own timeoutMs.

Errors

Failed calls throw TenthError:

FieldTypeDescription
codestringTenth's stable error code, such as insufficient_credits, or one of the SDK's own.
messagestringA readable description.
statusnumber | nullThe HTTP status, or null when no response arrived.
detailstring | undefinedThe API's explanation.
requestIdstring | undefinedThe API's request ID, for support.
errorsunknownField-level validation issues from a 422.
retryAfterSecondsnumber | undefinedFrom a Retry-After header.
TypeScript
import { TenthError } from '@tenthbilling/node';

try {
  await tenth.credits.debit(userId, 'ai_tokens', { amount: 25, idempotency_key: `job-${jobId}` });
} catch (err) {
  if (err instanceof TenthError && err.code === 'insufficient_credits') {
    return res.status(402).json({ error: 'Not enough credits' });
  }
  throw err;
}

Codes the SDK raises itself:

CodeMeaning
invalid_configA bad secretKey, baseUrl, timeoutMs or maxRetries, or no fetch.
publishable_key_not_allowedA publishable key was passed as secretKey.
invalid_argumentA bad ID (empty, over 255 characters, . or ..), idempotency key, or other argument.
network_errorThe API couldn't be reached.
timeoutThe last attempt timed out.
abortedYour signal aborted the request.
invalid_responseThe API returned a success that isn't JSON.

An error response without a code gets http_<status>, such as http_502. Some codes from the API: not_found, insufficient_credits, receipt_invalid, receipt_belongs_to_other_customer, store_unavailable. Errors lists every code the API returns, with what to do about each.

Errors never contain your key, request headers or tokens, and the SDK never writes to the console.

Webhooks

Tenth sends signed webhooks for every change to your customers. The webhooks page lists the event types and the payload.

Verify each delivery with verifyWebhook against the raw request body. A parsed and re-serialized body won't match the signature. verifyWebhook checks the Tenth-Signature header in constant time, rejects timestamps more than 5 minutes off, and only then parses the event.

TypeScript
verifyWebhook({ payload, header, secret, toleranceSeconds }): WebhookEvent

InputDescription
payloadThe raw body, as a string, Buffer, Uint8Array or ArrayBuffer. A parsed object throws payload_not_raw.
headerThe Tenth-Signature header.
secretThe endpoint's signing secret (tenth_whsec_...), or an array of secrets while rotating.
toleranceSecondsThe largest allowed clock difference, either way. Default 300.

It returns the event, or throws TenthWebhookError with a reason:

reasonMeaning
missing_headerNo Tenth-Signature header.
malformed_headerThe header couldn't be parsed.
timestamp_too_oldThe timestamp is older than the tolerance.
timestamp_in_futureThe timestamp is further ahead than the tolerance.
signature_mismatchNo signature matched any secret.
payload_not_rawpayload isn't a string, Buffer, Uint8Array or ArrayBuffer.
invalid_payloadThe body isn't a JSON object.

TenthWebhookError extends TenthError, and its code equals its reason. The header name is exported as SIGNATURE_HEADER ('tenth-signature').

Express

TypeScript
import express from 'express';
import { verifyWebhook, TenthWebhookError } from '@tenthbilling/node';

const app = express();

app.post('/webhooks/tenth', express.raw({ type: 'application/json' }), async (req, res) => {
  let event;
  try {
    event = verifyWebhook({
      payload: req.body, // a Buffer, thanks to express.raw
      header: req.headers['tenth-signature'],
      secret: process.env.TENTH_WEBHOOK_SECRET!,
    });
  } catch (err) {
    if (err instanceof TenthWebhookError) return res.sendStatus(400);
    throw err;
  }
  await handle(event); // dedupe on event.id
  res.sendStatus(200);
});

Register the webhook route before any global express.json() middleware, or the body arrives already parsed.

Fastify

TypeScript
import Fastify from 'fastify';
import { verifyWebhook, TenthWebhookError } from '@tenthbilling/node';

const fastify = Fastify();

fastify.register(async (scope) => {
  // Keep the raw body for this route only.
  scope.addContentTypeParser('application/json', { parseAs: 'buffer' }, (_req, body, done) =>
    done(null, body),
  );
  scope.post('/webhooks/tenth', async (request, reply) => {
    let event;
    try {
      event = verifyWebhook({
        payload: request.body as Buffer,
        header: request.headers['tenth-signature'],
        secret: process.env.TENTH_WEBHOOK_SECRET!,
      });
    } catch (err) {
      if (err instanceof TenthWebhookError) return reply.code(400).send();
      throw err;
    }
    await handle(event); // dedupe on event.id
    return reply.code(200).send();
  });
});

Web-standard runtimes (Deno, Supabase Edge)

Read the body once, as text or bytes, and pass it as is:

TypeScript
import { verifyWebhook, TenthWebhookError } from '@tenthbilling/node';

Deno.serve(async (req) => {
  const payload = await req.text(); // or new Uint8Array(await req.arrayBuffer())
  let event;
  try {
    event = verifyWebhook({
      payload,
      header: req.headers.get('tenth-signature') ?? undefined,
      secret: Deno.env.get('TENTH_WEBHOOK_SECRET')!,
    });
  } catch (err) {
    if (err instanceof TenthWebhookError) return new Response(null, { status: 400 });
    throw err;
  }
  await handle(event); // dedupe on event.id
  return new Response(null, { status: 200 });
});

Check the environment

Every event carries environment, 'test' or 'live'. Each environment has its own endpoints and signing secrets, so a correctly configured endpoint only gets its own. Still, check it in code, so a test endpoint pointed at your production handler can't change production records:

TypeScript
const expected = process.env.TENTH_SECRET_KEY!.startsWith('tenth_live_') ? 'live' : 'test';
if (event.environment !== expected) return res.sendStatus(200); // acknowledge, but ignore

Rotating the secret

While you rotate an endpoint's secret, pass both, and deliveries signed with either pass:

TypeScript
verifyWebhook({ payload, header, secret: [newSecret, oldSecret] });

Customer tokens

If your app doesn't use Clerk or another identity provider, your server can mint short-lived customer tokens. The app passes the token to TenthProvider's getCustomerToken, alongside its publishable key.

Create the token secret on the app's Identity page in the dashboard (Server-minted tokens → Create or rotate secret). There's one per app and environment, it's shown only once, and rotating it makes tokens minted with the old one stop working.

This Express example assumes your own sign-in middleware, here called requireSignedIn, which rejects anonymous requests and sets req.user to the authenticated user. Replace it with whatever your server uses (a session, your own JWT check).

TypeScript
import express from 'express';
import { mintCustomerToken } from '@tenthbilling/node';
import { requireSignedIn } from './auth'; // yours: rejects signed-out requests, sets req.user

const app = express();

app.get('/tenth-token', requireSignedIn, (req, res) => {
  const token = mintCustomerToken({
    tokenSecret: process.env.TENTH_CUSTOMER_TOKEN_SECRET!,
    appId: process.env.TENTH_APP_ID!,
    environment: 'live',
    appUserId: req.user.id, // the user your middleware authenticated
    ttlSeconds: 3600,
  });
  res.json({ token });
});

InputDescription
tokenSecretThe app environment's customer token secret. Keep it on your server.
appIdYour Tenth app's ID.
environment'test' or 'live', matching the publishable key the app uses.
appUserIdThe customer's ID: 1 to 255 characters, no control characters or surrounding spaces.
ttlSecondsLifetime, from 1 to 86400 (24 hours). Default 3600.

The token is an HS256 JWT with issuer https://api.tenthbilling.com (exported as TENTH_TOKEN_ISSUER), audience tenth:<appId>:<environment> and subject appUserId. MAX_CUSTOMER_TOKEN_TTL_SECONDS is 86400. Bad input throws TenthError with code invalid_argument.

Mint a token only for the user your server has authenticated. Whoever holds it can read and buy as that customer.

In the app:

TSX
<TenthProvider
  apiKey="tenth_live_pk_..."
  getCustomerToken={async () => (signedIn ? await fetchTenthTokenFromYourServer() : null)}
>

Other exports

  • WEBHOOK_EVENT_TYPES: the known webhook event types, as a constant array.
  • SDK_VERSION: the SDK's version, sent in the User-Agent header.
  • Types: TenthOptions, RequestOptions, FetchLike, TenthErrorInit, ClientErrorCode, WebhookErrorReason, VerifyWebhookInput, MintCustomerTokenInput, WebhookEvent, WebhookEventType, CustomerState, EntitlementState, CreditBalance, CreditTransaction, CreditHold, SubscriptionSummary, Grant, RevenueTransaction, FeedEvent, and the request and response types for each method.