View as Markdown

Node and React SDK

@globaly-inc/mint-sdk: customers, entitlements, usage, credits, subscriptions, invoices, checkout and verified webhooks, with no runtime dependencies.

Two entry points

  • @globaly-inc/mint-sdk runs on your server and needs a secret key.
  • @globaly-inc/mint-sdk/react runs in the browser and never holds a key. Your server passes it a snapshot.

It uses the global fetch and Web Crypto, so it runs on Node 18.17 and later, Next.js (Node and edge runtimes), Bun, Deno and Cloudflare Workers. It ships ESM, CommonJS and type declarations.

Create a client

lib/mint.ts
import { Mint } from '@globaly-inc/mint-sdk'
 
export const mint = new Mint({
  secretKey: process.env.MINT_SECRET_KEY!, // the mode comes from the key
})
OptionDefaultMeaning
secretKeyrequiredA gpy_ key. A publishable pk_ key is refused.
baseUrlhttps://globalymint.com
timeoutMs30000Per attempt.
maxRetries2For requests that are safe to repeat.
entitlements{ ttlMs: 60000, maxEntries: 1000 }The entitlements cache. Pass cache to use your own store.
usage{ flushIntervalMs: 2000, batchSize: 100, maxRetries: 5 }Usage batching. batchSize is at most 1000.

Sync a customer

customer.ts
await mint.customers.upsert({ externalId: org.id, email: org.billingEmail, name: org.name })

Keyed by your own id. Safe to call on every sign-in.

Gate features and limits

Ask GlobalyMint what a customer may use, instead of hard-coding plans.

gate.ts
import { PlanLimitError } from '@globaly-inc/mint-sdk'
 
const ent = await mint.entitlements.get(org.id) // cached for 60 s, refreshed by webhooks
 
if (!ent.has('api.access')) return forbidden('Upgrade to use the API')
 
// Throws PlanLimitError when one more would pass the limit.
ent.assert('envelopes.monthly', { used: await countEnvelopesThisMonth(org.id) })
CallReturns
ent.has(feature)Whether the plan includes the feature.
ent.limit(key)The limit. null means unlimited, 0 means not granted.
ent.allows(key, { used, amount })Whether amount more fits under the limit.
ent.assert(key, { used, amount })The same check, throwing PlanLimitError (key, limit, used, plan).
ent.credits(pool){ granted, used, remaining }
ent.usage(key){ used, included, overage }, or null.
ent.plan, ent.status, ent.seats, ent.periodEnd, ent.subscriptionId, ent.versionThe plan behind the snapshot.

The cache is never moved backwards: a response or webhook with a lower version than the cached one is ignored. Use get(id, { fresh: true }) straight after a change you made yourself.

Report usage

usage.ts
mint.usage.report({ externalId: org.id, meter: 'envelope.sent', id: envelope.id })

report() queues the event and never throws. Events are sent every 2 seconds, or as soon as 100 are waiting. Each event carries its own id, so a repeated send is harmless.

On serverless, flush before the response ends:

serverless.ts
mint.usage.report({ externalId: org.id, meter: 'ai.tokens', id: run.id, quantity: run.tokens })
await mint.usage.flush()

Use mint.usage.send(events) when you need to know the events were recorded before you go on. It throws on failure.

Credits

credits.ts
await mint.credits.consume({ externalId: org.id, pool: 'ai', amount: 10, id: run.id })
await mint.credits.grant({ externalId: org.id, pool: 'ai', amount: 1000, id: purchase.id, reason: 'purchase' })

id is your own id for the movement. Repeating it does nothing and returns duplicate: true. consume throws InsufficientCreditsError when the pool cannot cover the amount.

Subscriptions and invoices

billing.ts
const sub = await mint.subscriptions.create(
  { customerExternalId: org.id, planCode: 'team', quantity: 5 },
  { idempotencyKey: `signup-${org.id}` },
)
 
await mint.subscriptions.setSeats(sub.id, members.length)
await mint.subscriptions.changePlan(sub.id, { planCode: 'business' }, { idempotencyKey: `plan-${sub.id}-business` })
await mint.subscriptions.cancel(sub.id, { atPeriodEnd: true })
 
const page = await mint.invoices.list({ customerExternalId: org.id, status: 'finalized' })

Calls that move money need an idempotencyKey from you and refuse to run without one: subscriptions.create, subscriptions.changePlan, invoices.createOneOff and invoices.recordPayment. See Idempotency.

Setting seats is safe to repeat because the number is absolute: sending the same count twice changes nothing.

Checkout and portal

sessions.ts
const { url } = await mint.checkout.create({
  customerExternalId: org.id,
  planCode: 'team',
  seats: 5,
  successUrl: 'https://app.example.com/billing?ok=1',
  cancelUrl: 'https://app.example.com/billing',
})
 
const portal = await mint.portal.create({ customerExternalId: org.id, returnUrl: 'https://app.example.com/settings' })

See Hosted checkout and Customer portal.

Webhooks

app/api/mint/webhooks/route.ts
export const POST = mint.webhooks.handler({
  secret: process.env.MINT_WEBHOOK_SECRET!,
  on: {
    'invoice.payment_failed': async (event) => notifyOwner(event.data),
  },
})

The handler verifies the signature, refreshes the entitlements cache from entitlements.updated, then calls your function. See Verify signatures.

React

Fetch the snapshot on the server and pass it down. The gate in the browser is for display; enforce on the server too.

layout.tsx
const ent = await mint.entitlements.get(org.id)
return <MintEntitlementsProvider value={ent.raw}>{children}</MintEntitlementsProvider>
billing-ui.tsx
'use client'
import { Gate, useEntitlements } from '@globaly-inc/mint-sdk/react'
 
<Gate feature="api.access" fallback={<UpgradeButton />}>
  <ApiKeys />
</Gate>

Retries

The SDK retries only what is safe to repeat: GET, PUT, a POST that carries an Idempotency-Key, and a POST whose body carries its own id. It retries on network errors, timeouts, 408, 429, 5xx and 409 idempotency_in_progress.

By default it retries twice, so a call is tried at most three times. Set maxRetries on the client or on one call to change that. Between tries it waits a random time that doubles each try: 0.25 to 0.5 s before the first retry, 0.5 to 1 s before the second, and so on up to 4 to 8 s. When the server sends Retry-After, it waits exactly that long instead.

Errors

Every error extends MintError. The classes are listed under Errors.

On this page