Skip to main content
Learn how to integrate LlamaIndex.TS with Next.js for building production-ready AI applications.

Overview

LlamaIndex.TS works seamlessly with Next.js in multiple runtime environments:
  • Node.js Runtime - Full feature support with server actions and API routes
  • Edge Runtime - Optimized for Vercel Edge Functions
  • Server Actions - Direct LlamaIndex operations in React Server Components
  • API Routes - RESTful endpoints for LlamaIndex functionality

Next.js Configuration

Use the withLlamaIndex wrapper for proper bundling:
next.config.mjs
This ensures:
  • Proper webpack configuration
  • Correct polyfills for edge environments
  • Optimized bundling for LlamaIndex packages

Server Actions Example

Use LlamaIndex directly in server actions:
src/actions/openai.ts

Using Server Actions in Components

src/app/page.tsx

API Routes Example

Create RESTful endpoints for LlamaIndex operations:
src/app/api/chat/route.ts

Streaming API Route

src/app/api/chat-stream/route.ts

Edge Runtime Example

Optimize for Vercel Edge Functions:
src/app/api/edge-chat/route.ts
Edge runtime has limitations. Not all LlamaIndex features work in edge environments. Stick to basic LLM operations and avoid file system operations.

Client-Side Integration

React Hook for Chat

src/hooks/useChat.ts

Chat Component

src/components/Chat.tsx

Environment Variables

Configure API keys in .env.local:
.env.local
Access in server-side code:
Never expose API keys to the client. Only use NEXT_PUBLIC_ prefix for non-sensitive values.

Deployment Considerations

Vercel Deployment

  1. Install dependencies:
  1. Configure environment variables in Vercel dashboard
  2. Deploy:

Caching Strategies

Cache expensive operations:

Using External Vector Stores

For production, use managed vector stores:

Complete Example Structure

Best Practices

1. Separate Server and Client Code

  • Keep LlamaIndex operations in server actions/API routes
  • Use client components only for UI
  • Never import LlamaIndex in client components

2. Error Handling

3. Loading States

4. Type Safety

Next Steps

Server Actions

Learn about Next.js server actions

API Routes

Next.js API route documentation

Edge Runtime

Edge and Node.js runtimes

Vector Stores

Production vector store integration