Integrate Mastra in your Express project
Mastra integrates with Express, making it easy to:
- Build flexible APIs to serve AI-powered features
- Maintain full control over your server logic and routing
- Scale your backend independently of your frontend
Use this guide to scaffold and integrate Mastra with your Express project.
This setup is compatible with the following package versions:
express
: 4.x@types/express
: 4.x
Type compatibility in 5.x can be inconsistent while express
and @types/express
evolve toward alignment.
Install Mastra
Install the required Mastra packages:
npm
npm install mastra@latest @mastra/core@latest @mastra/libsql@latest
Integrate Mastra
To integrate Mastra in 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 --default
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": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "mastra dev",
"build": "mastra build"
}
}
If your project already uses
dev
andbuild
scripts, we recommend using:dev:mastra
andbuild:mastra
.
Initialize TypeScript
Create a tsconfig.json
file in your project root with the following configuration:
{
"compilerOptions": {
"target": "ES2022",
"module": "ES2022",
"moduleResolution": "bundler",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true,
"outDir": "dist"
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist", ".mastra"]
}
This TypeScript configuration is optimized for Mastra projects, using modern module resolution and strict type checking.
Set Up API Key
OPENAI_API_KEY=<your-api-key>
Each llm provider uses a different env var. See Model Capabilities for more information.
Start the Mastra Dev Server
Start the Mastra dev server to expose your agents as REST endpoints:
npm
npm run dev
Once running, your agents are available locally. See Local Development Environment for more information.
Example Express App
This example creates an /api/weather
endpoint that expects a city
query parameter.
import "dotenv/config";
import express, { Request, Response } from "express";
import { mastra } from "./mastra";
const app = express();
const port = process.env.PORT ?? 3000;
app.get("/api/weather", async (req: Request, res: Response) => {
const { city } = req.query as { city?: string };
if (!city) {
return res.status(400).send("Missing 'city' query parameter");
}
const agent = mastra.getAgent("weatherAgent");
try {
const result = await agent.generate(`What's the weather like in ${city}?`);
res.send(result.text);
} catch (error) {
console.error("Agent error:", error);
res.status(500).send('An error occurred while processing your request');
}
});
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
With the Mastra dev server running, start your Express app separately. For example:
npx tsx --watch src/server.ts --watch-dir src
You can now make a request to the endpoint using one of the following:
http
http://localhost:3000/api/weather?city=London
You should see output similar to the below:
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!