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
npm install @tenthbilling/node
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.
| Runtime | Status |
|---|---|
| Node 24 or later | Supported and tested. |
| Deno 2, including Supabase Edge Functions | Works through Deno's Node compatibility. Import it as npm:@tenthbilling/node. |
| Bun, Cloudflare Workers and others | Not 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
| Option | Type | Default | Description |
|---|---|---|---|
secretKey | string | required | tenth_test_sk_... or tenth_live_sk_.... A publishable key throws publishable_key_not_allowed; anything else malformed throws invalid_config. |
baseUrl | string | https://api.tenthbilling.com | The API origin. Must be https, except plain http to localhost, 127.0.0.1 or [::1]. No path, query or credentials. |
timeoutMs | number | 10000 | Timeout for each attempt, in milliseconds. |
maxRetries | number | 2 | Retries after the first attempt. 0 turns retries off. |
fetch | function | the global fetch | A 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:
| Option | Description |
|---|---|
idempotencyKey | Sent as Idempotency-Key on mutating requests. See Idempotency and retries. |
timeoutMs | Overrides the client's per-attempt timeout. |
maxRetries | Overrides the client's retry count. |
signal | An 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.
// Gate a feature
if (await tenth.hasEntitlement(userId, 'pro')) {
// ...
}
// Full state: entitlements, credit balances, subscriptions
const state = await tenth.customers.get(userId);
| Method | Returns | Description |
|---|---|---|
hasEntitlement(appUserId, entitlement) | boolean | True when the entitlement is active now. An unknown customer returns false, not an error. |
customers.get(appUserId) | CustomerState | Entitlements, 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) | CustomerState | Sets email and merges attributes. |
customers.delete(appUserId) | void | Deletes 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
const { balance, replayed } = await tenth.credits.debit(userId, 'ai_tokens', {
amount: 25,
idempotency_key: `job-${jobId}`,
});
| Method | Returns | Description |
|---|---|---|
credits.get(appUserId, query?) | { balances, transactions } | Balances and recent transactions. Query: credit_type, before (page back), limit. |
credits.debit(appUserId, creditType, body) | CreditDebitResult | Spends credits. |
credits.reserve(appUserId, creditType, body) | CreditHold | Holds credits for long-running work. |
credits.commit(appUserId, creditType, holdId, body?) | CreditDebitResult | Spends a hold. Committing less than the hold releases the rest. |
credits.release(appUserId, creditType, holdId) | CreditHold | Releases 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:
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.
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);
| Method | Returns | Description |
|---|---|---|
grants.create(appUserId, body) | Grant | Gives an entitlement or credits. |
grants.revoke(grantId) | Grant | Revokes a grant. Unspent granted credits are removed. |
create body:
| Field | Description |
|---|---|
reason | Required. Why you gave it. |
entitlement | The entitlement to give. |
credit_type | The credit type to give. |
amount | Credits to give (credit grants only). |
starts_at | ISO 8601. Entitlement grants can start later; credits are granted now. |
expires_at | ISO 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.
for await (const event of tenth.events.listAll({ after: lastProcessedId })) {
await handle(event.payload);
await saveCursor(event.id);
}
| Method | Returns | Description |
|---|---|---|
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 FeedEvent | Every 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 RevenueTransaction | Every 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.
| Method | Returns | Description |
|---|---|---|
subscriptions.change(id, body) | CustomerState | Moves the subscription to another product. |
subscriptions.cancel(id, body?) | CustomerState | Cancels, at the end of the period by default. |
subscriptions.resume(id) | CustomerState | Resumes a subscription. |
subscriptions.anchor(id, body) | CustomerState | Moves the subscription to a fixed billing day. |
purchases.refund(id, body?) | CustomerState | Refunds 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.
// 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_idon a revenue transaction (revenueTransactions.list);data.subject.idon apurchase.completedevent, 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.
| Method | Returns | Description |
|---|---|---|
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'.
// 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 }, wheresigned_transactionis StoreKit 2's signed transaction: the JWS string fromTransaction.jwsRepresentation(or thesignedTransactionInfoof 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 }, wheretypeis'subscription'or'one_time'andproduct_idis 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:
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
maxRetriestimes (2 by default). - Waits use exponential backoff with jitter: 50 to 100% of 0.5 s × 2^attempt, at most 8 s.
- A
Retry-Afterheader is honored, up to 30 seconds. - Other 4xx responses are never retried.
- Each attempt has its own
timeoutMs.
Errors
Failed calls throw TenthError:
| Field | Type | Description |
|---|---|---|
code | string | Tenth's stable error code, such as insufficient_credits, or one of the SDK's own. |
message | string | A readable description. |
status | number | null | The HTTP status, or null when no response arrived. |
detail | string | undefined | The API's explanation. |
requestId | string | undefined | The API's request ID, for support. |
errors | unknown | Field-level validation issues from a 422. |
retryAfterSeconds | number | undefined | From a Retry-After header. |
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:
| Code | Meaning |
|---|---|
invalid_config | A bad secretKey, baseUrl, timeoutMs or maxRetries, or no fetch. |
publishable_key_not_allowed | A publishable key was passed as secretKey. |
invalid_argument | A bad ID (empty, over 255 characters, . or ..), idempotency key, or other argument. |
network_error | The API couldn't be reached. |
timeout | The last attempt timed out. |
aborted | Your signal aborted the request. |
invalid_response | The 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.
verifyWebhook({ payload, header, secret, toleranceSeconds }): WebhookEvent
| Input | Description |
|---|---|
payload | The raw body, as a string, Buffer, Uint8Array or ArrayBuffer. A parsed object throws payload_not_raw. |
header | The Tenth-Signature header. |
secret | The endpoint's signing secret (tenth_whsec_...), or an array of secrets while rotating. |
toleranceSeconds | The largest allowed clock difference, either way. Default 300. |
It returns the event, or throws TenthWebhookError with a reason:
reason | Meaning |
|---|---|
missing_header | No Tenth-Signature header. |
malformed_header | The header couldn't be parsed. |
timestamp_too_old | The timestamp is older than the tolerance. |
timestamp_in_future | The timestamp is further ahead than the tolerance. |
signature_mismatch | No signature matched any secret. |
payload_not_raw | payload isn't a string, Buffer, Uint8Array or ArrayBuffer. |
invalid_payload | The 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
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
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:
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:
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:
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).
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 });
});
| Input | Description |
|---|---|
tokenSecret | The app environment's customer token secret. Keep it on your server. |
appId | Your Tenth app's ID. |
environment | 'test' or 'live', matching the publishable key the app uses. |
appUserId | The customer's ID: 1 to 255 characters, no control characters or surrounding spaces. |
ttlSeconds | Lifetime, 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:
<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 theUser-Agentheader.- 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.