TypeScript: Shipping agents inside Node and Next.js APIs
Expose an agent safely in a Next.js App Router route
Never put LLM API keys in client-side React components. Run your PraisonAI Agent inside a server-side API route, validate the request payload, and return clean JSON.
Example
// app/api/ask/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { Agent } from 'praisonai';
export async function POST(req: NextRequest) {
const { question } = await req.json();
if (!question || typeof question !== 'string' || question.length > 1000) {
return NextResponse.json({ error: 'Invalid question' }, { status: 400 });
}
const agent = new Agent({
name: 'WebSupport',
instructions: 'Answer product questions concisely in plain text.',
llm: 'gpt-4o-mini',
});
const answer = await agent.start(question);
return NextResponse.json({ answer });
}Example explained
- app/api/ask/route.ts — Keeps OPENAI_API_KEY strictly on the server, never exposed to browser bundles.
- question.length > 1000 — Caps input size before calling the LLM to prevent token-flooding abuse.
Protect production routes with timeouts and per-user limits
Browser requests can time out after 30–60 seconds on serverless platforms. Set explicit AbortController timeouts, enforce rate limits by user/IP, and stream responses for multi-step agents.
Common pitfall: sharing one mutable Agent instance across concurrent users
Create a fresh Agent (or isolate session_id per request) inside each HTTP handler so User A's conversation history never leaks into User B's reply.
Reference: documentation