Integrate Mastra in your Astro project
Mastra integrates with Astro, 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 Astro's built-in Actions or Server Endpoints for efficient server-client workflows
Use this guide to scaffold and integrate Mastra with your Astro project.
- Actions
- Server Endpoints
This guide assumes you're using Astro's Actions with React and the Vercel adapter.
Install the required Mastra packages:
- npm
- yarn
- pnpm
- bun
npm install mastra@latest @mastra/core@latest @mastra/libsql@latestyarn add mastra@latest @mastra/core@latest @mastra/libsql@latestpnpm add mastra@latest @mastra/core@latest @mastra/libsql@latestbun add mastra@latest @mastra/core@latest @mastra/libsql@latestTo integrate Mastra into your project, you have two options:
-
Use the One-Liner
Run the following command to quickly scaffold the default Weather agent with sensible defaults:
npx mastra@latest init --defaultSee mastra init for more information.
-
Use the Interactive CLI
If you prefer to customize the setup, run the
initcommand and choose from the options when prompted:npx mastra@latest init
Add the
devandbuildscripts topackage.json:package.json{
"scripts": {
...
"dev:mastra": "mastra dev",
"build:mastra": "mastra build"
}
}-
Modify the
tsconfig.jsonfile in your project root:tsconfig.json{
...
"exclude": ["dist", ".mastra"]
}Setup your API key in a
.envfile:.envOPENAI_API_KEY=<your-api-key>Add
.mastraand.vercelto your.gitignorefile:.gitignore.mastra
.vercelAstro uses Vite, which accesses environment variables via
import.meta.envrather thanprocess.env. As a result, the model constructor must explicitly receive theapiKeyfrom the Vite environment like this:src/mastra/agents/weather-agent.ts- import { openai } from "@ai-sdk/openai";
+ import { createOpenAI } from "@ai-sdk/openai";
+ const openai = createOpenAI({
+ apiKey: import.meta.env?.OPENAI_API_KEY,
+ compatibility: "strict"
+ });More configuration details are available in the AI SDK docs. See Provider Instance for more information.
Start the Mastra Dev Server to expose your agents as REST endpoints:
- npm
- CLI
npm run dev:mastramastra dev:mastraOnce running, your agents are available locally. See Local Development Environment for more information.
With the Mastra Dev Server running, you can start your Astro site in the usual way.
Create an
actionsdirectory:mkdir src/actionsCreate a new Action, and add the example code:
touch src/actions/index.tssrc/actions/index.tsimport { defineAction } from "astro:actions";
import { z } from "astro:schema";
import { mastra } from "../mastra";
export const server = {
getWeatherInfo: defineAction({
input: z.object({
city: z.string(),
}),
handler: async (input) => {
const city = input.city;
const agent = mastra.getAgent("weatherAgent");
const result = await agent.generate(
`What's the weather like in ${city}?`,
);
return result.text;
},
}),
};Create a new Form component, and add the example code:
touch src/components/form.tsxsrc/components/form.tsximport { actions } from "astro:actions";
import { useState } from "react";
export const Form = () => {
const [result, setResult] = useState<string | null>(null);
async function handleSubmit(formData: FormData) {
const city = formData.get("city")!.toString();
const { data } = await actions.getWeatherInfo({ city });
setResult(data || null);
}
return (
<>
<form action={handleSubmit}>
<input name="city" placeholder="Enter city" required />
<button type="submit">Get Weather</button>
</form>
{result && <pre>{result}</pre>}
</>
);
};Create a new Page, and add the example code:
touch src/pages/test.astrosrc/pages/test.astro---
import { Form } from '../components/form'
---
<h1>Test</h1>
<Form client:load />You can now navigate to
/testin 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!
This guide assumes you're using Astro's Endpoints with React and the Vercel adapter, and your output is set to server.
Prerequisites
Before proceeding, ensure your Astro project is configured as follows:
- Astro React integration: @astrojs/react
- Vercel adapter: @astrojs/vercel
astro.config.mjsis set tooutput: "server"
Install the required Mastra packages:
- npm
- yarn
- pnpm
- bun
npm install mastra@latest @mastra/core@latest @mastra/libsql@latestyarn add mastra@latest @mastra/core@latest @mastra/libsql@latestpnpm add mastra@latest @mastra/core@latest @mastra/libsql@latestbun add mastra@latest @mastra/core@latest @mastra/libsql@latestTo integrate Mastra into your project, you have two options:
-
Use the One-Liner
Run the following command to quickly scaffold the default Weather agent with sensible defaults:
npx mastra@latest init --defaultSee mastra init for more information.
-
Use the Interactive CLI
If you prefer to customize the setup, run the
initcommand and choose from the options when prompted:npx mastra@latest init
Add the
devandbuildscripts topackage.json:package.json{
"scripts": {
...
"dev:mastra": "mastra dev",
"build:mastra": "mastra build"
}
}-
Modify the
tsconfig.jsonfile in your project root:tsconfig.json{
...
"exclude": ["dist", ".mastra"]
}Setup your API key in a
.envfile:.envOPENAI_API_KEY=<your-api-key>Add
.mastrato your.gitignorefile:.gitignore.mastra
.vercelAstro uses Vite, which accesses environment variables via
import.meta.envrather thanprocess.env. As a result, the model constructor must explicitly receive theapiKeyfrom the Vite environment like this:src/mastra/agents/weather-agent.ts- import { openai } from "@ai-sdk/openai";
+ import { createOpenAI } from "@ai-sdk/openai";
+ const openai = createOpenAI({
+ apiKey: import.meta.env?.OPENAI_API_KEY,
+ compatibility: "strict"
+ });More configuration details are available in the AI SDK docs. See Provider Instance for more information.
Start the Mastra Dev Server to expose your agents as REST endpoints:
- npm
- CLI
npm run dev:mastramastra dev:mastraOnce running, your agents are available locally. See Local Development Environment for more information.
With the Mastra Dev Server running, you can start your Astro site in the usual way.
Create an
apidirectory:mkdir src/pages/apiCreate a new Endpoint, and add the example code:
touch src/pages/api/test.tssrc/pages/api/test.tsimport type { APIRoute } from "astro";
import { mastra } from "../../mastra";
export const POST: APIRoute = async ({ request }) => {
const { city } = await new Response(request.body).json();
const agent = mastra.getAgent("weatherAgent");
const result = await agent.generate(`What's the weather like in ${city}?`);
return new Response(JSON.stringify(result.text));
};Create a new Form component, and add the example code:
touch src/components/form.tsxsrc/components/form.tsximport { useState } from "react";
export const Form = () => {
const [result, setResult] = useState<string | null>(null);
async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault();
const formData = new FormData(event.currentTarget);
const city = formData.get("city")?.toString();
const response = await fetch("/api/test", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ city })
});
const text = await response.json();
setResult(text);
}
return (
<>
<form onSubmit={handleSubmit}>
<input name="city" placeholder="Enter city" required />
<button type="submit">Get Weather</button>
</form>
{result && <pre>{result}</pre>}
</>
);
};Create a new Page, and add the example code:
touch src/pages/test.astrosrc/pages/test.astro---
import { Form } from '../components/form'
---
<h1>Test</h1>
<Form client:load />You can now navigate to
/testin 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!