> ## Documentation Index
> Fetch the complete documentation index at: https://narev.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Quickstart - Humans

> Set up Narev Cloud, install the Narev SDK, meter Vercel AI SDK calls, tag customer usage, and send billable AI events to Polar.

Start with usage-based billing so you can measure usage and bill customers correctly from day one. This guide walks you through connecting a Next.js app to **Narev Cloud** using the **Narev SDK** and sending billable AI events to Polar.

<Steps>
  <Step title="Get your API keys">
    To authenticate your app, you need API keys from both Narev Cloud and your billing provider.

    1. Create a free [Narev Cloud](https://www.narev.ai/login) account.
    2. Navigate to **Settings → API Keys** and generate a new `NAREV_API_KEY`.
    3. Get your billing provider credentials. If you are using Polar, create a sandbox workspace and generate a `POLAR_ACCESS_TOKEN`.

    Add these credentials to your local environment variables:

    ```bash .env.local theme={null}
    NAREV_API_KEY=your_narev_api_key_here
    POLAR_ACCESS_TOKEN=your_polar_access_token_here
    POLAR_SERVER=sandbox
    ```

    <Info>
      This guide uses Polar because it has a concise setup flow. You can use the exact same framework pattern with Stripe, OpenMeter, Lago, or other supported destinations.
    </Info>
  </Step>

  <Step title="Install the packages">
    Install the core Narev SDK billing package, your preferred billing provider destination, and the Next.js UI components.

    <CodeGroup>
      ```bash npm theme={null}
      npm install @ai-billing/core @ai-billing/polar @ai-billing/nextjs ai @ai-sdk/openai
      ```

      ```bash pnpm theme={null}
      pnpm add @ai-billing/core @ai-billing/polar @ai-billing/nextjs ai @ai-sdk/openai
      ```

      ```bash yarn theme={null}
      yarn add @ai-billing/core @ai-billing/polar @ai-billing/nextjs ai @ai-sdk/openai
      ```

      ```bash bun theme={null}
      bun add @ai-billing/core @ai-billing/polar @ai-billing/nextjs ai @ai-sdk/openai
      ```
    </CodeGroup>
  </Step>

  <Step title="Configure your billing destination">
    Configure the destination that receives your billing events.

    Create a `lib/destinations.ts` file to configure Polar. The `externalCustomerIdKey` is critical because it tells Polar which Customer Tagging field maps the usage to a specific customer.

    <Tabs>
      <Tab title="Next.js" icon="triangle">
        ```typescript lib/destinations.ts theme={null}
        import { createPolarDestination } from '@ai-billing/polar';

        export function getBillingDestinations() {
          const accessToken = process.env.POLAR_ACCESS_TOKEN;

          if (!accessToken) return [];

          return [
            createPolarDestination({
              accessToken,
              server: process.env.POLAR_SERVER === 'production' ? 'production' : 'sandbox',
              eventName: 'llm_usage',
              externalCustomerIdKey: 'userId',
            }),
          ];
        }
        ```
      </Tab>
    </Tabs>
  </Step>

  <Step title="Add the backend middleware">
    Use the `wrapLanguageModel` function from the Vercel AI SDK to attach the Narev billing middleware to your model. This wrapper automatically tracks token usage and sends it to your billing provider.

    Create a central helper for your billed models that uses your configured destinations.

    <Tabs>
      <Tab title="Next.js" icon="triangle">
        ```typescript lib/billing.ts theme={null}
        import { wrapLanguageModel } from 'ai';
        import { openai } from '@ai-sdk/openai';
        import { createOpenAIV3Middleware } from '@ai-billing/openai';
        import { getBillingDestinations } from './destinations';

        const billingMiddleware = createOpenAIV3Middleware({
          destinations: getBillingDestinations()
        });

        // Wrap your model to automatically meter all generations
        export const billedModel = wrapLanguageModel({
          model: openai('gpt-4o'),
          middleware: billingMiddleware
        });
        ```
      </Tab>
    </Tabs>

    <Tip>
      Centralizing your model creation in one file ensures that every part of your app uses the metered instance, preventing unbilled usage leaks.
    </Tip>
  </Step>

  <Step title="Use the model in your API route">
    Pass the wrapped model into Vercel's `streamText` function. Use the `providerOptions` object to pass Customer Tagging metadata. The billing destination uses this data to know which customer to charge for the tokens consumed.

    <Tabs>
      <Tab title="Next.js" icon="triangle">
        ```typescript app/api/chat/route.ts theme={null}
        import { streamText } from 'ai';
        import { billedModel } from '@/lib/billing';

        export async function POST(req: Request) {
          const { messages } = await req.json();
          
          // Get the authenticated user ID (e.g., from your auth provider)
          const userId = 'user_123'; 
          
          const result = streamText({
            model: billedModel,
            messages,
            providerOptions: {
              // These tags are automatically forwarded to your billing destination
              'ai-billing-tags': {
                userId: userId,
                // You can add additional metadata here for deeper cost attribution
                feature: 'chat-interface'
              },
            },
          });

          return result.toDataStreamResponse();
        }
        ```
      </Tab>
    </Tabs>

    <Warning>
      Always verify that `userId` correctly maps to the corresponding customer record in your billing provider. Start in a sandbox environment before deploying to production.
    </Warning>
  </Step>

  <Step title="Add the pre-built billing components">
    Embed the pre-built React components in your Next.js frontend to show users their real-time usage and provide a native checkout experience for buying credits.

    <Tabs>
      <Tab title="Next.js" icon="triangle">
        ```tsx app/components/usage-dashboard.tsx theme={null}
        import { CreditUsagePolar, CreditTopUpPolar } from '@ai-billing/nextjs';

        export default function BillingDashboard({ userId }: { userId: string }) {
          return (
            <div className="flex flex-col gap-6 p-6 bg-white dark:bg-zinc-950 rounded-xl border border-zinc-200 dark:border-zinc-800">
              <h2 className="text-xl font-semibold text-zinc-900 dark:text-zinc-100">
                Usage & Billing
              </h2>
              
              {/* Shows current consumption and remaining budget/credits */}
              <div className="p-4 bg-zinc-50 dark:bg-zinc-900 rounded-lg">
                <CreditUsagePolar userId={userId} />
              </div>
              
              {/* Renders a checkout component to buy more credits */}
              <div className="p-4 bg-zinc-50 dark:bg-zinc-900 rounded-lg">
                <CreditTopUpPolar userId={userId} />
              </div>
            </div>
          );
        }
        ```
      </Tab>
    </Tabs>
  </Step>

  <Step title="Voila! You're ready to bill">
    Your app is now fully equipped with AI monetization, cost tracking, and a self-serve top-up dashboard.

    <Frame caption="The billing dashboard shows real-time usage">
      <img src="https://mintcdn.com/narev/vk3N1vAMCBfZgm44/images/intro-billing-usage.png?fit=max&auto=format&n=vk3N1vAMCBfZgm44&q=85&s=79bf69c15ef6d90c646b7490898093c2" alt="Billing dashboard using Narev pre-built components showing real-time usage" width="1272" height="416" data-path="images/intro-billing-usage.png" />
    </Frame>

    <Frame caption="Users can seamlessly purchase additional credits">
      <img src="https://mintcdn.com/narev/vk3N1vAMCBfZgm44/images/intro-billing-topup.png?fit=max&auto=format&n=vk3N1vAMCBfZgm44&q=85&s=86fedfaa3e921f741ccef23b090deb75" alt="Billing dashboard using Narev pre-built components showing top-up options" width="1406" height="1228" data-path="images/intro-billing-topup.png" />
    </Frame>

    <Check>
      You have successfully integrated the Narev SDK into your Next.js app.
    </Check>
  </Step>
</Steps>

## Choose your next guide

<CardGroup cols={2}>
  <Card title="Next.js billing integration" icon="triangle" href="/platform/billing/integrations/frameworks/nextjs">
    Build the full framework integration with reusable helpers and coverage checks.
  </Card>

  <Card title="Polar billing platform integration" icon="circle-dollar-sign" href="/platform/billing/integrations/billing-platforms/polar">
    Configure Polar customers, event names, and usage mapping for metered billing.
  </Card>

  <Card title="Narev SDK overview" icon="code" href="/sdk/ai-billing/index">
    Learn how provider middleware, price resolvers, and destinations work together.
  </Card>

  <Card title="Benchmarking quickstart" icon="chart-line" href="/platform/quickstart/benchmark">
    Compare model quality and cost before changing production routing.
  </Card>
</CardGroup>
