# Quickstart: Next.js API Routes

Integrate CostHQ into your Next.js application to automatically track the AI costs generated by each user or specific API routes.

## 1. Install

```bash
npm install costhq
```

## 2. Wrap Your API Route

Use the `trackedGPT` functional wrapper to track specific API calls inside your Next.js App Router or Pages Router. We will group the costs under a session named after the API route or user ID.

```typescript
// app/api/chat/route.ts
import { NextResponse } from 'next/server';
import OpenAI from 'openai';
import { trackedGPT } from 'costhq/wrappers';
import { AgentSession } from 'costhq/agents';

const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

export async function POST(req: Request) {
  const { prompt, userId } = await req.json();

  // Create a session to group costs (e.g., by User ID or Route)
  const session = new AgentSession(`Chat Route - User ${userId}`, {
    budget: 2.00 // Optional: Set a $2 limit per user session!
  });
  session.start();

  try {
    // Wrap the OpenAI call. Tokens and cost are logged automatically.
    const response = await trackedGPT(openai, {
      model: 'gpt-4o',
      messages: [{ role: 'user', content: prompt }],
    });

    // End the session to finalize the cost summary
    session.end();

    return NextResponse.json({ result: response.choices[0].message.content });

  } catch (error) {
    if (error.name === 'BudgetExceededError') {
      return NextResponse.json({ error: "User budget exceeded." }, { status: 429 });
    }
    return NextResponse.json({ error: "Internal Error" }, { status: 500 });
  }
}
```

## 3. View Your Spend

Run the CostHQ dashboard locally to monitor your API routes:

```bash
cs dashboard
```
