Skip to content

Open source CapCut alternative.

TypeScript
9.5 KB
Raw Blame

Backend API Guide

Backend APIs are the Next.js route handlers under the site project. They serve the site's own client views, signed in with a session cookie.

The one rule: every route handler is wrapped in withDonkeyAuth. A public endpoint is a deliberate exception with a product reason — today Better Auth's routes, the signature-verified Stripe webhook, the HMAC-token email unsubscribe and promotion redirect, the token-authorized share viewers, the ChatGPT MCP endpoint and its OAuth endpoints, the Meta page view beacon, authenticated cron jobs, and a health check. Ship a handler without the wrapper and the endpoint is open to anyone.

Authentication

withDonkeyAuth puts the caller in request.donkey; its method distinguishes session cookies from the dev bypass.

withSuperUser(handler) enforces the super-user role before a handler runs.

Better Auth serves /api/auth/[...all]. Google OAuth returns to ${BETTER_AUTH_URL}/api/auth/callback/google. Adding ?method=email to /sign-in or /sign-up opens email/password authentication for anyone; the default pages show Google. Password recovery remains unavailable.

Sign-out is everywhere. Each browser holds its own session, so signing out on any surface revokes every session for that user (Better Auth's revoke-sessions), not just the current one. Other tabs pick it up when they refetch the session on focus.

The hosted deploy needs BETTER_AUTH_URL, BETTER_AUTH_SECRET, GOOGLE_CLIENT_ID, and GOOGLE_CLIENT_SECRET. Never commit real OAuth credentials.

The ChatGPT app uses scoped OAuth tokens for its MCP transport. Its consent submission requires the existing Donkey Cut session and a browser-bound challenge. OAuth tokens authorize only the tools exposed by that adapter.

Handler Rules

  • Validate every request body, search param, and route param with Zod before using it.
  • Check resource ownership before reading or mutating scoped data.
  • Return an explicit NextResponse.json(...) with the status you mean.
  • For an access-control failure — missing session, missing or inactive subscription — return a plain 401 via unauthorizedResponse; for a missing resource, a plain 404 via notFoundResponse. Don't hand-write per-case auth or not-found messages. Save distinct codes for genuinely different outcomes: 402 over quota, 429 rate-limited.
  • Don't wrap a handler in try/catch unless it can recover and return a different intentional response. Let unexpected errors surface to the framework.
  • What a handler imports is what its serverless function downloads before it can answer anything. Import the narrow module that holds what you need, and when a module reads files from the public folder, keep those bytes out of every other function with outputFileTracingExcludes in the Next config.
  • process.env holds secrets only: API keys, credentials, and other sensitive deploy values. Configuration is code: a constant, or a settings registry entry for a lever su runs. An env-var fallback like process.env.SOME_MODEL ?? "default" ships the feature dormant and hides the real value from readers.

Database

  • Reach Prisma only through the server-only client.
  • Put table and model definitions in grouped sibling .prisma files, not in schema.prisma — it holds only generator and datasource config.
  • Use Prisma's default table names for new models; don't add @@map. A few older tables predate this and keep their mapped snake_case names.
  • Add @@index only for a column a query actually filters or joins on.
  • Functions run in pdx1, beside the database; keep a polled read to one parallel round of selects.
  • Don't run database migrations as part of API work.

Inference Gateway

The inference gateway is the client-facing boundary for remote model calls and asset generation. Everything a client and the backend share — routes, schemas, the stateless provider calls — stays provider-neutral. Provider names live only inside private adapters, as configuration and data.

Every inference route requires the x-donkey-client-id header. Provider request mapping lives behind the provider registry, so handlers import the registry and the neutral schemas, never an individual adapter.

A caller that ships separately from the site — the editor page, the turn worker — names a model role (chat, review, fastDecision) and the responses route resolves it to the registry's current id. An id baked into their bundles would outlive a registry bump and fail pricing the moment the site deploys; a role never goes stale. A lint rule keeps the ids out of the page and worker source.

State stays on the client. The backend can create or refresh a provider job and hand back job IDs, generation IDs, polling URLs, and output references, but it never persists prompts, generation records, provider output references, or generated assets in Postgres.

Media never rides the request body. The routes run as serverless functions behind a request-body limit the platform enforces at the edge, and an oversized body is refused before a handler runs — the caller sees a dropped connection, not an error anyone can act on. So a client with pictures or sound to send uploads the bytes straight to object storage and puts a placeholder in the body naming the object and the field the bytes belong in. The route swaps the bytes back in before the provider call, where the request is server-to-server and only the model's own limit applies.

Two rules follow. A placeholder is scoped to the account that uploaded it, so a route reads an object only under the caller's own prefix. And storage is how a large request succeeds, never why a small one fails: a client that can't reach storage sends the bytes inline, as it always could.

Gemini adapter

The Gemini adapter uses the official @google/genai SDK. It runs on Vertex AI's global endpoint only when GOOGLE_APPLICATION_CREDENTIALS_JSON carries a project_id; without one, the provider is unavailable. Set that JSON as a hosted-deploy secret.

Model choice is code (see Handler Rules on process.env):

Call Model
Gate-judged simple chat turns, fast structured decisions gemini-3.1-flash-lite
General chat, non-decision structured calls gemini-3.8-flash
Hosted transcription gemini-3.5-transcribe-preview

Structured requests normalize their JSON schema for Gemini and retry without a provider-enforced schema when Vertex rejects the schema parameters.

Hosted Model Credits

Hosted inference is metered per signed-in user, and the backend owns the meter: it checks credits, knows the rates, debits, and writes the audit rows. Balances are USD micros; people see 1,000 credits per dollar, and a price sheet shows each flat-priced generation's cost before it runs.

A provider-invoking route checks credits before it calls the model and charges after the provider succeeds. If the provider or runtime fails after a successful preflight, the route records a zero-cost failed-usage event with a sanitized error code.

How much the preflight can check depends on how the model bills. A token-metered call clears on any positive balance, because its cost is unknown until the model has run; whatever it overshoots the balance by is written off, and the write-off is booked as a ledger row so the leakage stays countable. A generation that bills a flat amount — video, images, music — is held to that amount, so a clip priced above the balance never starts. That check needs the model that will actually be charged, and asset callers routinely omit the model and let the adapter pick one, so an asset provider reports its billed model for a request and the route resolves it before the preflight.

Both refusals answer 402 with the same message. They carry different codes: a balance short of one flat-priced generation also returns the price it could not cover, and that account can still run chat and the other metered calls, so a client knows to keep the rest of the surface working.

Credit given by hand is an offer emailed as a claim link; the grant and its ledger entry are written when the person claims, with the credit's lifetime counted from that moment.

Known OpenAI, Gemini, and ElevenLabs models fall back to backend-owned prices unless a database rate overrides them. The fallbacks mirror current public provider prices, mark them up by the supported margin, and round up to the nearest credit micro. Token models charge per million provider tokens; hidden reasoning or output tokens are billed as output when the provider's totalTokens exceeds visible input plus output. Speech bills by the provider's returned units; a music render bills flat per generated clip, since the render is a fixed-length interaction that carries no per-second usage. Keep rate overrides and per-user limits in backend-owned data, not the Mac app.

Usage rows store units, never content. They may keep sanitized provider usage metadata and normalized billable units. They must not keep prompts, request bodies, screenshots, generated assets, provider output, output references, or any other user content.

Pattern

import { NextResponse } from "next/server";

import { withDonkeyAuth } from "@/lib/donkey-api-auth";

export const GET = withDonkeyAuth((request) => {
  return NextResponse.json({
    clientId: request.donkey.clientId,
  });
});

Where It Lives

Backend handlers live under the site project's API routes; the auth wrapper, Prisma client, and inference adapters live in its lib folder, and table definitions live in the Prisma folder. Start at the auth wrapper when changing how a handler authenticates.