@nasca/sdk
v0.2.4
Published
Per-user AI cost tracking and rate limiting for indie developers
Maintainers
Readme
@nasca/sdk
AI monetisation infrastructure for indie developers. Track per-user AI spend, enforce daily/weekly/monthly limits, sell credit packs, and redirect blocked users to Stripe checkout — all in one SDK.
Works with OpenAI, Anthropic Claude, and any OpenRouter model.
Installation
npm install @nasca/sdkQuick start
1. Initialise once per project
import { Nasca } from '@nasca/sdk'
const nasca = new Nasca({
accountId: process.env.NASCA_ACCOUNT_ID!,
workerUrl: process.env.NASCA_WORKER_URL!,
apiKey: process.env.NASCA_API_KEY!,
// Return the current end-user's ID from your request context
getUserId: (ctx) => ctx.user.id,
// Optional: map users to tiers you've defined in the dashboard
getUserTier: (ctx) => ctx.user.plan, // e.g. 'free', 'pro'
// Optional: enables checkout_url on NascaBlockedError
successUrl: 'https://yourapp.com/credits/success',
cancelUrl: 'https://yourapp.com/credits/cancel',
})2. Wrap your AI function once
import OpenAI from 'openai'
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY })
const callAI = nasca.wrap(
openai.chat.completions.create.bind(openai.chat.completions)
)Works identically for Anthropic:
import Anthropic from '@anthropic-ai/sdk'
const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY })
const callAI = nasca.wrap(
anthropic.messages.create.bind(anthropic.messages)
)And for OpenRouter (via the OpenAI SDK):
const openai = new OpenAI({
apiKey: process.env.OPENROUTER_API_KEY,
baseURL: 'https://openrouter.ai/api/v1',
})
const callAI = nasca.wrap(
openai.chat.completions.create.bind(openai.chat.completions)
)3. Use it identically everywhere
const result = await callAI(
{ model: 'gpt-4o', messages: [{ role: 'user', content: 'Hello!' }] },
ctx // your request context — getUserId extracts the user from here
)Handling blocked users
When a user exceeds their limit and has no credits, the SDK throws NascaBlockedError:
import { NascaBlockedError } from '@nasca/sdk'
try {
const result = await callAI({ model: 'gpt-4o', messages }, ctx)
} catch (e) {
if (e instanceof NascaBlockedError) {
return res.status(402).json({
message: e.upgrade_message, // your custom message from the dashboard
checkout_url: e.checkout_url, // direct link to Stripe checkout (if configured)
})
}
throw e
}NascaBlockedError fields:
| Field | Type | Description |
|---|---|---|
| upgrade_message | string | The message you configured in the dashboard for this tier |
| remaining_budget | number | Always 0 when blocked |
| checkout_url | string \| null | Stripe checkout URL — populated when successUrl/cancelUrl are configured |
| credit_balance_display | number \| null | Remaining credit balance in display dollars (always null when blocked — use getUsage()) |
| credit_percent | number \| null | Remaining credit percentage (always null when blocked — use getUsage()) |
Credit packs and getUsage()
When a user has purchased credits, the SDK allows them through even if their tier limits are exceeded. Credits deplete as they make AI calls. Once credits run out, users see NascaBlockedError with a checkout_url to buy more.
Fetch the full usage snapshot to display progress to your users:
const usage = await nasca.getUsage(ctx)
// Tier allowance
console.log(usage.monthly_spend) // 1.40
console.log(usage.monthly_limit) // 2.00
console.log(usage.monthly_percent) // 70
// Daily/weekly limits (if set on the user's tier)
console.log(usage.daily_spend) // 0.04
console.log(usage.daily_limit) // 0.10
// Credit balance
console.log(usage.credit_balance_display) // 3.20 (display dollars)
console.log(usage.credit_percent) // 64 (% of pack remaining)
// State
console.log(usage.is_blocked) // false
console.log(usage.resets_at) // "2026-07-01T00:00:00.000Z"getUsage() calls the worker directly and throws if it is unreachable.
Streaming
Streaming works without changes. The SDK injects stream_options: { include_usage: true } for OpenAI automatically, and accumulates usage events for Anthropic across message_start and message_delta. Usage is logged after the stream closes.
const stream = await callAI({ model: 'gpt-4o', messages, stream: true }, ctx)
for await (const chunk of stream) {
// identical to the raw OpenAI stream
}How it works
- First call per user — registers the user against your account (once per process lifecycle, deduplicated).
- Before every AI call —
/interceptchecks Redis: blocked flag → daily limit → weekly limit → monthly limit. Each limit falls back to the user's credit balance before blocking. Under 50ms round trip. Fails open if the worker is unreachable. - After every AI call —
/logfires in the background (fire-and-forget). Increments daily, weekly, and monthly spend counters. Deducts from credits if this call was credit-covered. Sets the blocked flag if a limit is permanently exhausted.
Nasca never estimates token counts. All cost figures come from the usage object in the provider response.
Environment variables
NASCA_ACCOUNT_ID= # your account UUID from the Nasca dashboard
NASCA_WORKER_URL= # your Cloudflare Worker URL
NASCA_API_KEY= # your nsk_... API key from the dashboardAuth provider snippets
// Supabase Auth
getUserId: (ctx) => ctx.user.id
// Clerk
getUserId: (ctx) => ctx.auth.userId
// NextAuth
getUserId: (ctx) => ctx.session.user.idgetUserTier is optional. Return a tier name matching one you defined in the Nasca dashboard (e.g. "free", "pro"). New users without a matching tier are placed on your account's default tier.
