Next.js

01 Prep

Prepare a Next.js App Router project for Anvia server routes.

Use this path when Anvia will run behind Next.js App Router route handlers.

1. Create or Open an App Router Project

pnpm create next-app@latest anvia-next --ts --app
cd anvia-next

If you already have a Next.js app, use the App Router app/ directory. The route examples in this guide use app/api/.../route.ts.

2. Install Anvia

pnpm add @anvia/core @anvia/openai zod

Install other provider packages when you need them:

pnpm add @anvia/anthropic @anvia/gemini @anvia/mistral

3. Add Environment Variables

Anvia clients use explicit constructor options and do not read environment variables by themselves.

OPENAI_API_KEY=sk_...

Read the value only in server-side files:

const apiKey = process.env.OPENAI_API_KEY;

if (!apiKey) {
  throw new Error("OPENAI_API_KEY is required");
}

4. Choose Runtime Boundaries

Keep these files server-only:

FilePurpose
app/ai/support-agent.tsProvider client, model, tools, and reusable agent
app/api/support/route.tsNon-streaming prompt endpoint
app/api/support/stream/route.tsStreaming prompt endpoint

Next.js route handlers use the Web Request and Response APIs, so Anvia readableStream() can be returned directly.

Next

Build the reusable agent in Setup Anvia. For the SDK model, read How Anvia Works.