# Next.js quickstart

Send usage events from route handlers or server actions after the response, with the key kept on the server.

AI Spendbook documentation, Your app's data. Web page: https://www.aispendbook.com/docs/quickstart-nextjs

Send one event per model call from your Next.js server code to the [ingestion API](https://www.aispendbook.com/docs/ingestion-api). Post from a route handler or a server action, never from the browser: the ingestion key would be visible to anyone who opens the page. If you would rather wrap the OpenAI, Anthropic or Gemini client, or use the Vercel AI SDK middleware, see the [Node.js SDK](https://www.aispendbook.com/docs/node-sdk); the steps below need no package.

## 1. Key and endpoint

Create an ingestion key in **Integrations** under **SDK / HTTP ingestion**. It starts with `afk_` and is shown once. Keep it in your server environment.

```bash
# .env on the server only. No NEXT_PUBLIC_ prefix, so neither value reaches the browser bundle.
SPENDBOOK_API_KEY=afk_your_key        # ingestion key, shown once
SPENDBOOK_ENDPOINT=https://www.aispendbook.com
```

## 2. A server-only helper

```typescript
// lib/spendbook.ts
import "server-only"; // fails the build if a client component imports this file

export type UsageEvent = {
  event_id: string; // unique per model call; reuse it if you retry
  occurred_at: string; // ISO-8601 with a time zone
  provider: string;
  model: string;
  input_tokens: number; // uncached input
  output_tokens: number;
  cache_read_tokens?: number;
  cache_write_tokens?: number;
  request_id?: string;
  latency_ms?: number;
  status?: "success" | "error" | "cancelled";
  customer_id?: string;
  feature?: string;
  environment?: string; // production, staging, ...
  run_id?: string; // groups the calls of one agent run or job
};

/** Posts up to 500 events. Never throws: a failed post is logged and your request is unaffected. */
export async function recordAiUsage(events: UsageEvent[]): Promise<void> {
  try {
    const res = await fetch(`${process.env.SPENDBOOK_ENDPOINT}/api/v1/ingest/batch`, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${process.env.SPENDBOOK_API_KEY}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ events }),
    });
    if (!res.ok) console.warn("AI Spendbook ingest failed", res.status);
  } catch (err) {
    console.warn("AI Spendbook ingest failed", err);
  }
}
```

- `server-only` is an npm package. Install it, or leave the line out and keep the file out of client components yourself.
- Token counts come from the provider's usage object. Input tokens are uncached input. Never estimate them.

## 3. Record from a route handler

```typescript
// app/api/answer/route.ts
import { randomUUID } from "node:crypto";
import Anthropic from "@anthropic-ai/sdk";
import { after } from "next/server";
import { recordAiUsage } from "@/lib/spendbook";

const anthropic = new Anthropic(); // ANTHROPIC_API_KEY

export async function POST(req: Request) {
  const { question } = await req.json();
  const customerId = req.headers.get("x-customer-id") ?? undefined; // take it from your session in production
  const started = new Date();
  const msg = await anthropic.messages.create({
    model: process.env.ANTHROPIC_MODEL!,
    max_tokens: 512,
    messages: [{ role: "user", content: question }],
  });

  // Runs after the response has been sent, so the user never waits for it.
  after(() =>
    recordAiUsage([{
      event_id: randomUUID(),
      occurred_at: started.toISOString(),
      provider: "anthropic",
      model: msg.model,
      request_id: msg._request_id ?? undefined,
      input_tokens: msg.usage.input_tokens, // Anthropic input is already uncached
      output_tokens: msg.usage.output_tokens,
      cache_read_tokens: msg.usage.cache_read_input_tokens ?? 0,
      cache_write_tokens: msg.usage.cache_creation_input_tokens ?? 0,
      latency_ms: Date.now() - started.getTime(),
      status: "success",
      customer_id: customerId,
      feature: "answer",
    }]),
  );

  return Response.json({ answer: msg.content });
}
```

- Don't `await` the post before you answer the user. `after()` from `next/server` runs it once the response is sent, and the platform keeps the function alive until it finishes. A plain call without `await` can be cut off when a serverless function ends.
- Under heavy traffic, collect events and send them in batches of up to 500 with the same helper, or put them on your own queue.
- The route reads the model from `ANTHROPIC_MODEL` and the customer from a header to keep the example short. Use your session for the customer.

## Or from a server action

```typescript
// app/actions.ts
"use server";
import { randomUUID } from "node:crypto";
import { after } from "next/server";
import { recordAiUsage } from "@/lib/spendbook";

export async function summarize(text: string) {
  const started = new Date();
  const result = await callYourModel(text); // your provider call
  after(() =>
    recordAiUsage([{
      event_id: randomUUID(),
      occurred_at: started.toISOString(),
      provider: result.provider,
      model: result.model,
      input_tokens: result.inputTokens,
      output_tokens: result.outputTokens,
      feature: "summarize",
    }]),
  );
  return result.text;
}
```

## Check it works

1. In the app, open **Integrations**. Under **Add a source**, find **SDK / HTTP ingestion** and choose **Set up**.
2. Go to the **Test event** step. Use the key you just created, or paste the one your service uses, and choose **Send test event**.
3. Wait for the **Test event received** notice. It means the key and the ingestion API work. If you see **Accepted, but not visible yet**, choose **Send again** after a minute. The test event has zero tokens, so it adds no cost, and it carries the feature `spendbook-connection-test` so you can filter it out.
4. Then make one AI call through your own code and open **Usage Explorer**, filtered to the feature `answer`. During onboarding, the SDK step shows **Last event received** once events arrive.

The field list is on the [ingestion API](https://www.aispendbook.com/docs/ingestion-api) page. Python services can use the [Python SDK](https://www.aispendbook.com/docs/python-sdk) instead.
