Gate usage-based features, sell credit packs and rollover subscriptions, and auto-refund failed runs—without building ledger tables or billing UI.
// app/api/generate/route.ts (1-file helper from /docs)
import { CreditKitClient } from '@/lib/creditkit';
export const credits = new CreditKitClient({
apiKey: process.env.CREDITKIT_SECRET_KEY!, // sk_test_... or sk_live_...
});
export async function POST(req: Request) {
const session = await getSession(req); // Clerk, Supabase, Better Auth, NextAuth
if (!session?.user?.id) return Response.json({ error: 'Unauthorized' }, { status: 401 });
const hold = await credits.withCrashProofHold(
{ req, userId: session.user.id, placementKey: 'run_action', units: 1 },
async () => await runJob() // Auto-refunds exact lots on 5xx
);
if (!hold.allowed) {
return Response.json(hold, {
status: hold.configError ? 500 : hold.refundedOnCrash ? 502 : 402,
});
}
return Response.json(hold.data);
}CreditKit.openTopUp() · GatePops up when credits hit 0 (HTTP 402). Supports packs, monthly plans, promos, and upgrades.Define what each action costs (run_action = 10 cr, export_batch = 10 cr), signed-in starter allowances (50 cr), and credit packs in the console—change pricing anytime without redeploying.
Wrap your API route or button in one call. CreditKit checks the user's balance, locks the credits while your code runs, and puts them right back if your server or upstream API fails.
When a user runs out, CreditKit opens your branded top-up modal automatically. Customers buy credit packs or subscriptions via Stripe, and payouts go straight to your bank.
Failed upstream AI, scraper, or API runs automatically restore the exact source lot.
Daily free and expiring monthly rollover credits always burn before permanent packs.
Mid-cycle upgrades grant +delta credits immediately; downgrades schedule at period end.
Signed-in HMAC identity binding plus a hard daily free-tier spend circuit breaker.
Proportional refund clawbacks, chargeback auto-freezes, and past-due subscription dunning.
Track real profit per endpoint after API/GPU cost and run 50/50 quota A/B split-tests.