DocsFrameworksIntegrate with Next.js

Integrate Mastra in your Next.js project

There are two main ways to integrate Mastra with your Next.js application: as a separate backend service or directly integrated into your Next.js app.

1. Separate Backend Integration

Best for larger projects where you want to:

  • Scale your AI backend independently
  • Keep clear separation of concerns
  • Have more deployment flexibility

Create Mastra Backend

Create a new Mastra project using our CLI:

npx create-mastra@latest

For detailed setup instructions, see our installation guide.

Install MastraClient

npm install @mastra/client-js

Use MastraClient

Create a client instance and use it in your Next.js application:

lib/mastra.ts
import { MastraClient } from '@mastra/client-js';
 
// Initialize the client
export const mastraClient = new MastraClient({
  baseUrl: process.env.NEXT_PUBLIC_MASTRA_API_URL || 'http://localhost:4111',
});

Example usage in your React component:

app/components/SimpleWeather.tsx
'use client'
 
import { mastraClient } from '@/lib/mastra'
 
export function SimpleWeather() {
  async function handleSubmit(formData: FormData) {
    const city = formData.get('city')
    const agent = mastraClient.getAgent('weatherAgent')
    
    try {
      const response = await agent.generate({
        messages: [{ role: 'user', content: `What's the weather like in ${city}?` }],
      })
      // Handle the response
      console.log(response.text)
    } catch (error) {
      console.error('Error:', error)
    }
  }
 
  return (
    <form action={handleSubmit}>
      <input name="city" placeholder="Enter city name" />
      <button type="submit">Get Weather</button>
    </form>
  )
}

Deployment

When you’re ready to deploy, you can use any of our platform-specific deployers (Vercel, Netlify, Cloudflare) or deploy to any Node.js hosting platform. Check our deployment guide for detailed instructions.

2. Direct Integration

Better for smaller projects or prototypes. This approach bundles Mastra directly with your Next.js application.

Initialize Mastra in your Next.js Root

First, navigate to your Next.js project root and initialize Mastra:

cd your-nextjs-app

Then run the initialization command:

npx mastra@latest init

This will set up Mastra in your Next.js project. For more details about init and other configuration options, see our mastra init reference.

Configure Next.js

Add to your next.config.js:

next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  serverExternalPackages: ["@mastra/*"],
  // ... your other Next.js config
}
 
module.exports = nextConfig

Server Actions Example

app/actions.ts
'use server'
 
import { mastra } from '@/mastra'
 
export async function getWeatherInfo(city: string) {
  const agent = mastra.getAgent('weatherAgent')
  
  const result = await agent.generate(`What's the weather like in ${city}?`)
 
  return result
}

Use it in your component:

app/components/Weather.tsx
'use client'
 
import { getWeatherInfo } from '../actions'
 
export function Weather() {
  async function handleSubmit(formData: FormData) {
    const city = formData.get('city') as string
    const result = await getWeatherInfo(city)
    // Handle the result
    console.log(result)
  }
 
  return (
    <form action={handleSubmit}>
      <input name="city" placeholder="Enter city name" />
      <button type="submit">Get Weather</button>
    </form>
  )
}

API Routes Example

app/api/weather/route.ts
import { mastra } from '@/mastra'
import { NextResponse } from 'next/server'
 
export async function POST(req: Request) {
  const { city } = await req.json()
  const agent = mastra.getAgent('weatherAgent')
 
  const result = await agent.stream(`What's the weather like in ${city}?`)
 
  return result.toDataStreamResponse()
}

Deployment

When using direct integration, your Mastra instance will be deployed alongside your Next.js application. Ensure you:

  • Set up environment variables for your LLM API keys in your deployment platform
  • Implement proper error handling for production use
  • Monitor your AI agent’s performance and costs

Observability

Mastra provides built-in observability features to help you monitor, debug, and optimize your AI operations. This includes:

  • Tracing of AI operations and their performance
  • Logging of prompts, completions, and errors
  • Integration with observability platforms like Langfuse and LangSmith

For detailed setup instructions and configuration options specific to Next.js local development, see our Next.js Observability Configuration Guide.