Docs menu: Charge on your server (Node.js)

Charge on your server (Node.js)

Charge for AI calls, scraping or other paid work on your server, where users can't skip the charge, and give the credits back automatically when the work fails.

How a charge works

1) Set aside: before your code runs, CreditKit puts the credits on hold (credits that expire soonest are used first). 2) Charge or give back: if your code finishes, the hold is charged; if it throws, the same credits go back to the user.

1. Install @creditkit/node

Works in Next.js, Node.js 18+, Bun, Express, Hono, and Cloudflare Workers (nodejs_compat), with no dependencies of its own:

Terminal
npm install @creditkit/node
lib/creditkit.ts
import { CreditKitClient } from '@creditkit/node';

export const credits = new CreditKitClient({
  baseUrl: process.env.CREDITKIT_URL || 'https://creditkit.dev',
  apiKey: process.env.CREDITKIT_SECRET_KEY!, // sk_test_... locally, sk_live_... in production
  publicKey: process.env.NEXT_PUBLIC_CREDITKIT_KEY, // pk_test_... / pk_live_... (needed for getMobileTopUpUrl)
  webhookSecret: process.env.CREDITKIT_WEBHOOK_SECRET, // whsec_..., only needed if you receive webhooks
});

2. Connect your auth

Your routes charge the signed-in user, so add a getCurrentUser() for your login library:

CreditKit works with any auth system — just pass your own user ID string. Pick a copy-paste example:

Example uses: @clerk/nextjs with clerkMiddleware() and <ClerkProvider> already set up.

lib/current-user.ts
// lib/current-user.ts
import { auth } from '@clerk/nextjs/server';

export async function getCurrentUser(): Promise<{ id: string; email?: string } | null> {
  const { userId } = await auth();
  return userId ? { id: userId } : null;
}
Optional: does signing out reload the page?

If it does, you're done: the balance clears on the next page load. If your sign-out doesn't reload or refresh the page, add this. Works with Clerk's prebuilt <UserButton /> and with your own signOut() calls.

components/CreditKitAuthSync.tsx (render once in app/layout.tsx, inside <ClerkProvider>)
'use client';
import { useEffect, useRef } from 'react';
import { useAuth } from '@clerk/nextjs';
import { useCreditKit } from '@creditkit/react';

// Clears the CreditKit wallet when the user signs out, including from Clerk's <UserButton />.
export function CreditKitAuthSync() {
  const { isLoaded, isSignedIn } = useAuth();
  const { logout } = useCreditKit();
  const wasSignedIn = useRef(false);
  useEffect(() => {
    if (!isLoaded) return;
    if (wasSignedIn.current && !isSignedIn) void logout();
    wasSignedIn.current = Boolean(isSignedIn);
  }, [isLoaded, isSignedIn, logout]);
  return null;
}
  • auth() reads the session locally; avoid currentUser() in the layout, since it calls Clerk's API (rate-limited) on every request. Email is optional for CreditKit.
  • Clerk user ids (user_...) are stable, so they are the right thing to pass as userId.

3. Wrap your route handler

app/api/generate/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { credits } from '@/lib/creditkit';
import { getCurrentUser } from '@/lib/current-user'; // your auth recipe

export async function POST(req: NextRequest) {
  const user = await getCurrentUser();
  if (!user) {
    return NextResponse.json({ error: 'Sign in first' }, { status: 401 });
  }

  const hold = await credits.withCrashProofHold(
    {
      req,
      userId: user.id,
      email: user.email,
      action: 'run_action',
      units: 1,
    },
    async ({ remaining }) => {
      // Run OpenAI / Anthropic / Replicate / GPU job here.
      // Any thrown error automatically releases the hold!
      return { outputUrl: 'https://cdn.example.com/result.png', remaining };
    }
  );

  if (hold.outcome === 'insufficient_credits') return NextResponse.json(hold, { status: 402 }); // opens the paywall
  if (hold.outcome !== 'ok') {
    console.error('[CreditKit]', hold); // your code threw (credits refunded) or a setup problem: details stay in your logs
    return NextResponse.json({ error: "Something went wrong. You weren't charged." }, { status: 500 });
  }

  return NextResponse.json(hold.data);
}

4. Charge by actual usage (tokens, seconds, rows)

When the cost isn't known up front, price the action per unit (say 1 credit per 1,000 tokens), reserve your estimate or maximum, and report what the run really used. Unused credits go back to the user; anything over is charged from their balance:

app/api/chat/route.ts
import { credits } from '@/lib/creditkit';

const hold = await credits.withCrashProofHold(
  { req, userId: user.id, action: 'chat_1k_tokens', units: 8 }, // reserve up to 8k tokens
  async ({ reportUsage }) => {
    const completion = await openai.chat.completions.create({ model, messages, max_tokens: 8000 });
    reportUsage({ units: Math.ceil(completion.usage!.total_tokens / 1000) }); // charge what was used
    return completion.choices[0].message;
  }
);
// hold.deducted -> credits actually charged
// hold.settle   -> { reservedCredits, settledCredits, refundedUnused, extraCharged, shortfall }

5. Show a user's balance & history on your server

app/billing/page.tsx (Server Component)
import { credits } from '@/lib/creditkit';

const balance = await credits.getBalance(user.id);
const history = await credits.listTransactions(user.id, { limit: 20 });
if (balance.ok && history.ok) {
  // balance.balance, balance.subscription
  // history.items: [{ type: 'charge' | 'refund' | 'usage_adjustment' | 'purchase' | 'grant' | ..., action, credits, createdAt }]
  // history.nextCursor -> pass as { cursor } for the next page
}