Skip to main content

Next.js with AI SDK

Learn how to build AI-powered Next.js applications using the AI SDK with the App Router.

Why Next.js?

Next.js is the ideal framework for AI applications:
  • Server Actions: Call AI functions directly from components
  • Route Handlers: Create streaming API endpoints
  • React Server Components: Optimize initial page loads
  • Edge Runtime: Deploy AI features globally
  • Streaming: Native support for streaming responses

Prerequisites

  • Node.js 18+
  • Basic knowledge of React and Next.js
  • Vercel AI Gateway API key

Quick Start

Create a new Next.js application:
Install AI SDK packages:
Configure your API key:

Core Patterns

1. Text Generation

Generate text on-demand with a button click. Client Component:
API Route:

2. Streaming Chat

Build a real-time chat interface with the useChat hook. Client Component:
API Route:

3. Structured Output

Generate structured data with type safety. Client Component:
API Route:

4. Tool Calling

Extend AI capabilities with custom tools.

5. Multi-Modal Input

Handle images and files in chat.

6. Server Actions

Call AI functions directly from Server Components.

Advanced Patterns

Rate Limiting

Implement rate limiting with Upstash:

Caching Responses

Authentication

Protect routes with authentication:

Deployment

Environment Variables

Set in Vercel Dashboard or .env.local:

Deploy to Vercel

Edge Runtime

Optimize for global performance:

Best Practices

  1. Use maxDuration: Set timeout for API routes
  2. Handle Errors: Provide user-friendly error messages
  3. Type Safety: Use TypeScript for better DX
  4. Loading States: Show feedback during generation
  5. Streaming: Use streaming for better UX

Examples

Resources