Next.js Route Handler
easy10 minapp/api/chat/route.ts
You want a streaming chat endpoint in a Next.js App Router project.
What it shows
- Export
createChatHandler()asPOSTfrom a route file - Authenticate in
beforeRunand log usage inafterRun
The code
app/api/chat/route.ts
import { Agent, Cogitator, calculator } from '@cogitator-ai/core';
import { createChatHandler } from '@cogitator-ai/next';
const cogitator = new Cogitator({
llm: { providers: { google: { apiKey: process.env.GOOGLE_API_KEY ?? '' } } },
memory: { adapter: 'memory' },
});
const agent = new Agent({
name: 'assistant',
model: 'google/gemini-3.5-flash-lite',
instructions: 'You are a helpful assistant. Use tools when appropriate. Be concise.',
tools: [calculator],
temperature: 0.3,
});
export const POST = createChatHandler(cogitator, agent, {
beforeRun: async (req) => {
const auth = req.headers.get('authorization');
if (!auth) throw new Error('Unauthorized');
return { userId: auth };
},
afterRun: async (result) => {
console.log(`Tokens used: ${result.usage.totalTokens}`);
},
});Run it
install · bash
pnpm add @cogitator-ai/core @cogitator-ai/nextEnvironment
GOOGLE_API_KEYrun · bash
pnpm next dev # GOOGLE_API_KEY in .env.localThe repo file is a reference for a Next.js project, not a script you run on its own.