Commet
  • Pricing
Log InTry out
Templates

Balance + Margin Template

Balance-based billing with automatic cost-plus pricing. Real model cost from the AI catalog, your margin on top, automatic deduction per request.

Live DemoSource
Balance + Margin Template

Balance-based billing template for AI products. Customers prepay a balance, and each AI request automatically deducts the real cost (from the AI model catalog) plus your configured margin. Two plans (Starter, Pro) with different margins.

Stack: Next.js 16, AI SDK (Gateway), Better Auth, Drizzle ORM, PostgreSQL, Commet SDK

Quick Start

commet create my-app -t balance-ai
cd my-app
docker compose up -d
pnpm install
pnpm dev

What's Included

  • Two plans with different balances and margins (Starter 50%, Pro 30%)
  • Multi-model selector — switch between Claude, GPT, Gemini in one click
  • Automatic token tracking via tracked() middleware
  • AI model catalog pricing — real cost per model from Commet
  • Balance deduction per request (cost + margin)
  • Block on exhaustion — requests stop when balance runs out
  • AI text generation demo with streaming
  • Checkout flow with Commet-hosted payments
  • Customer billing portal

How It Works

User sends prompt → AI Gateway → Response
                        ↓
              tracked() middleware reports:
              - model, inputTokens, outputTokens
                        ↓
              Commet calculates:
              - Real cost (from catalog)
              - Margin (from plan config)
              - Total deducted from balance

Key Files

  • lib/auth/auth.ts — Better Auth + Commet plugin with usage module
  • app/api/generate/route.ts — AI endpoint with tracked() middleware
  • app/(dashboard)/dashboard/generate-form.tsx — Model selector + streaming
  • app/pricing/page.tsx — Dynamic pricing with checkout
  • app/checkout/page.tsx — Checkout session creation
  • lib/env.ts — Environment validation with t3-env
  • lib/commet.ts — SDK initialization

Learn More

  • Consumption Models — Balance model details
  • AI Token Billing
  • Customer Portal

Developers

  • Documentation
  • Templates
  • GitHub

Resources

  • Blog
  • Changelog
  • Pricing

AI

  • Agents
  • MCP Server
  • Agent Skills
  • Claude Code
  • Codex

Learn

  • Guides
  • Glossary
  • Solutions
  • Billing for AI Models
  • Comparison

Company

  • About
  • Open Source
  • Terms
  • Privacy
XLinkedInGitHub