Integrate Mastra in your Next.js project
Mastra integrates with Next.js, making it easy to:
- Build flexible APIs to serve AI-powered features
- Simplify deployment with a unified codebase for frontend and backend
- Take advantage of Next.js’s built-in server actions (App Router) or API Routes (Pages Router) for efficient server-client workflows
Use this guide to scaffold and integrate Mastra with your Next.js project.
App Router
This guide assumes you’re using the Next.js App Router at the root of your
project, e.g., app
rather than src/app
.
Install Mastra
Install the required Mastra packages:
npm
npm install mastra@latest @mastra/core@latest @mastra/libsql@latest
Integrate Mastra
To integrate Mastra into your project, you have two options:
1. Use the One-Liner
Run the following command to quickly scaffold the default Weather agent with sensible defaults:
npx mastra@latest init --dir . --components agents,tools --example --llm openai
See mastra init for more information.
2. Use the Interactive CLI
If you prefer to customize the setup, run the init
command and choose from the options when prompted:
npx mastra@latest init
Add the dev
and build
scripts to package.json
:
{
"scripts": {
...
"dev:mastra": "mastra dev --dir mastra",
"build:mastra": "mastra build --dir mastra"
}
}
Configure TypeScript
Modify the tsconfig.json
file in your project root:
{
...
"exclude": ["dist", ".mastra"]
}
Set Up API Key
OPENAI_API_KEY=<your-api-key>
Each LLM provider uses a different env var. See Model Capabilities for more information.
Configure Next.js
Add to your next.config.ts
:
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
serverExternalPackages: ["@mastra/*"],
};
export default nextConfig;
Update .gitignore
Add .mastra
to your .gitignore
file:
.mastra
Start the Mastra Dev Server
Start the Mastra Dev Server to expose your agents as REST endpoints:
npm
npm run dev:mastra
Once running, your agents are available locally. See Local Development Environment for more information.
Start Next.js Dev Server
With the Mastra Dev Server running, you can start your Next.js app in the usual way.
Create Test Directory
Create a new directory that will contain a Page, Action, and Form for testing purposes.
mkdir test
Create Test Action
Create a new Action, and add the example code:
touch app/test/action.ts
"use server";
import { mastra } from "../../mastra";
export async function getWeatherInfo(formData: FormData) {
const city = formData.get("city")?.toString();
const agent = mastra.getAgent("weatherAgent");
const result = await agent.generate(`What's the weather like in ${city}?`);
return result.text;
}
Create Test Form
Create a new Form component, and add the example code:
touch app/test/form.tsx
"use client";
import { useState } from "react";
import { getWeatherInfo } from "./action";
export function Form() {
const [result, setResult] = useState<string | null>(null);
async function handleSubmit(formData: FormData) {
const res = await getWeatherInfo(formData);
setResult(res);
}
return (
<>
<form action={handleSubmit}>
<input name="city" placeholder="Enter city" required />
<button type="submit">Get Weather</button>
</form>
{result && <pre>{result}</pre>}
</>
);
}
Create Test Page
Create a new Page, and add the example code:
touch app/test/page.tsx
import { Form } from "./form";
export default async function Page() {
return (
<>
<h1>Test</h1>
<Form />
</>
);
}
You can now navigate to
/test
in your browser to try it out.
Submitting London as the city would return a result similar to:
Agent response: The current weather in London is as follows:
- **Temperature:** 12.9°C (Feels like 9.7°C)
- **Humidity:** 63%
- **Wind Speed:** 14.7 km/h
- **Wind Gusts:** 32.4 km/h
- **Conditions:** Overcast
Let me know if you need more information!