Building AI-Powered Apps with Next.js: Best Practices for 2026
Next.js has become the go-to framework for AI-powered web applications. Its server components, streaming support, and edge runtime make it uniquely suited for the latency patterns of LLM APIs. Here's how to build AI features in Next.js properly.
Why Next.js Works So Well for AI Apps
Three things make Next.js the right choice for AI features:
1. Server Components keep API keys safe AI API calls should never happen on the client — your keys would be exposed. Server Components let you call LLM APIs directly in your component tree, without an extra API route for simple use cases.
2. Streaming is first-class LLM responses are inherently streaming — tokens arrive one by one over 1–10 seconds. Next.js's streaming support (via React Suspense and ReadableStream) lets you show partial output to users as it arrives.
3. Edge functions reduce latency Running your AI gateway on the Edge (Vercel Edge Functions, Cloudflare Workers) puts your request closer to users globally, shaving off round-trip time before the first token arrives.
The Vercel AI SDK
The Vercel AI SDK (ai package) is the de facto standard for AI in Next.js apps. It provides:
- Unified API across OpenAI, Anthropic, Google, and 20+ other providers
- Streaming primitives (
streamText,streamObject) - React hooks (
useChat,useCompletion) for client-side UI - Structured output with Zod schema validation
npm install ai @ai-sdk/openai @ai-sdk/anthropic
Basic Streaming Chat Route
// app/api/chat/route.ts
import { streamText } from 'ai';
import { openai } from '@ai-sdk/openai';
export const runtime = 'edge';
export async function POST(req: Request) {
const { messages } = await req.json();
const result = await streamText({
model: openai('gpt-4o'),
system: 'You are a helpful assistant for Okudex, an AI development agency.',
messages,
maxTokens: 1024,
});
return result.toDataStreamResponse();
}
// components/Chat.tsx
'use client';
import { useChat } from 'ai/react';
export function Chat() {
const { messages, input, handleInputChange, handleSubmit, isLoading } = useChat();
return (
<div>
{messages.map(m => (
<div key={m.id} className={m.role === 'user' ? 'text-right' : 'text-left'}>
{m.content}
</div>
))}
<form onSubmit={handleSubmit}>
<input value={input} onChange={handleInputChange} />
<button type="submit" disabled={isLoading}>Send</button>
</form>
</div>
);
}
Structured Outputs with Zod
For AI features that need to return structured data (not free text), use generateObject:
import { generateObject } from 'ai';
import { openai } from '@ai-sdk/openai';
import { z } from 'zod';
const projectBriefSchema = z.object({
projectType: z.enum(['website', 'mobile_app', 'ai_agent', 'automation']),
estimatedBudget: z.string(),
timeline: z.string(),
keyFeatures: z.array(z.string()),
nextStep: z.string(),
});
const { object } = await generateObject({
model: openai('gpt-4o'),
schema: projectBriefSchema,
prompt: `Analyse this project inquiry and extract structured information: ${userMessage}`,
});
// object is fully typed as the Zod schema
Caching AI Responses
LLM calls are expensive. Cache aggressively where the output is deterministic or tolerates slight staleness:
// Cache AI-generated product descriptions for 24 hours
export async function GET(req: Request, { params }: { params: { id: string } }) {
return fetch(`/api/generate-description/${params.id}`, {
next: { revalidate: 86400 }, // 24 hours
});
}
For user-specific content, use a Redis cache keyed by user ID + content hash.
Handling Rate Limits and Errors
LLM APIs have rate limits. Build retry logic with exponential backoff:
import { openai } from '@ai-sdk/openai';
import { generateText } from 'ai';
async function generateWithRetry(prompt: string, maxAttempts = 3) {
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return await generateText({
model: openai('gpt-4o-mini'),
prompt,
});
} catch (error: any) {
if (error.status === 429 && attempt < maxAttempts) {
await new Promise(r => setTimeout(r, 1000 * attempt));
continue;
}
throw error;
}
}
}
Security: Preventing Prompt Injection
If user input is passed to your LLM, sanitise and validate it:
function sanitiseInput(input: string): string {
// Remove common injection patterns
return input
.replace(/ignore (previous|above|all) instructions/gi, '')
.replace(/you are now/gi, '')
.slice(0, 2000); // hard length limit
}
Always use a system prompt that defines the agent's scope and use role: 'system' to set it — it's harder to override than user-turn instructions.
Monitoring AI Features in Production
You need to know:
- How many tokens are you using per request?
- What's the p95 latency?
- How often are requests failing?
- Are users satisfied with responses?
Use LangSmith, Helicone, or a custom logging middleware that records every AI call with its inputs, outputs, latency, and token counts.
Summary
Next.js and the Vercel AI SDK give you everything you need to build production-ready AI features fast. The fundamentals are: keep API keys on the server, stream responses to users, validate outputs with Zod, cache aggressively, and log everything in production.
Building an AI-powered Next.js application? Okudex builds them every day — let's talk.
