Next.js

08 Troubleshooting

Fix common Next.js and Anvia route issues.

OPENAI_API_KEY is required

The provider client was created before the environment variable was available.

const apiKey = process.env.OPENAI_API_KEY;
if (!apiKey) throw new Error("OPENAI_API_KEY is required");

Set the variable in .env.local for development and in your deployment environment for production.

message is required

The route expects JSON with a message field.

curl -X POST http://localhost:3000/api/support \
  -H "Content-Type: application/json" \
  -d '{"message":"Hello"}'

Client Bundle Contains Server Code

The agent module was imported by a client component. Import it only from route handlers, server functions, server actions, or tests.

Streaming Works Locally But Not In Production

Check proxy buffering, function timeouts, and response headers:

return new Response(agent.prompt(message).readableStream(), {
  headers: {
    "Content-Type": "application/x-ndjson",
    "Cache-Control": "no-cache",
  },
});

Tool Can Read The Wrong User

Do not rely on model-supplied user ids for authorization. Resolve the user in the route and close over that user in scoped tools.

Provider Or Tool Fails Mid-Run

Wrap non-streaming routes in try/catch. For streaming routes, handle terminal error events on the client.

Next

Revisit Tools and Context, Readable Streams, and Tool Errors.