Creating A Mastra Server
While developing or when you deploy a Mastra application, it runs as an HTTP server that exposes your agents, workflows, and other functionality as API endpoints. This page explains how to configure and customize the server behavior.
Server Architecture
Mastra uses Hono as its underlying HTTP server framework. When you build a Mastra application using mastra build
, it generates a Hono-based HTTP server in the .mastra
directory.
The server provides:
- API endpoints for all registered agents
- API endpoints for all registered workflows
- Custom api route supports
- Custom middleware support
- Configuration of timeout
- Configuration of port
Server configuration
You can configure server port
and timeout
in the Mastra instance.
import { Mastra } from "@mastra/core";
export const mastra = new Mastra({
server: {
port: 3000, // Defaults to 4111
timeout: 10000, // Defaults to 30000 (30s)
},
});
Custom API Routes
Mastra provides a list of api routes that are automatically generated based on the registered agents and workflows. You can also define custom api routes on the Mastra instance.
These routes can live in the same file as the Mastra instance or in a separate file. We recommend keeping them in a separate file to keep the Mastra instance clean.
import { Mastra } from "@mastra/core";
import { registerApiRoute } from "@mastra/core/server";
export const mastra = new Mastra({
server: {
apiRoutes: [
registerApiRoute("/my-custom-route", {
method: "GET",
handler: async (c) => {
// you have access to mastra instance here
const mastra = c.get("mastra");
// you can use the mastra instance to get agents, workflows, etc.
const agents = await mastra.getAgent("my-agent");
return c.json({ message: "Hello, world!" });
},
}),
],
},
// Other configuration options
});
Custom CORS Config
Mastra allows you to configure CORS (Cross-Origin Resource Sharing) settings for your server.
import { Mastra } from '@mastra/core';
export const mastra = new Mastra({
server: {
cors: {
origin: ['https://example.com'], // Allow specific origins or '*' for all
allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowHeaders: ['Content-Type', 'Authorization'],
credentials: false,
}
}
});
Middleware
Mastra allows you to configure custom middleware functions that will be applied to API routes. This is useful for adding authentication, logging, CORS, or other HTTP-level functionality to your API endpoints.
import { Mastra } from '@mastra/core';
export const mastra = new Mastra({
// Other configuration options
server: {
middleware: [
{
handler: async (c, next) => {
// Example: Add authentication check
const authHeader = c.req.header('Authorization');
if (!authHeader) {
return new Response('Unauthorized', { status: 401 });
}
// Continue to the next middleware or route handler
await next();
},
path: '/api/*'
},
// add middleware to all routes
async (c, next) => {
// Example: Add request logging
console.log(`${c.req.method} ${c.req.url}`);
await next();
},
]
});
if you want to add a middleware to a single route, you can also specify that in the registerApiRoute using registerApiRoute
.
registerApiRoute("/my-custom-route", {
method: "GET",
middleware: [
async (c, next) => {
// Example: Add request logging
console.log(`${c.req.method} ${c.req.url}`);
await next();
},
],
handler: async (c) => {
// you have access to mastra instance here
const mastra = c.get("mastra");
// you can use the mastra instance to get agents, workflows, etc.
const agents = await mastra.getAgent("my-agent");
return c.json({ message: "Hello, world!" });
},
});
Middleware Behavior
Each middleware function:
- Receives a Hono context object (
c
) and anext
function - Can return a
Response
to short-circuit the request handling - Can call
next()
to continue to the next middleware or route handler - Can optionally specify a path pattern (defaults to ‘/api/*’)
- Inject request specific data for agent tool calling or workflows
Common Middleware Use Cases
Authentication
{
handler: async (c, next) => {
const authHeader = c.req.header('Authorization');
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return new Response('Unauthorized', { status: 401 });
}
const token = authHeader.split(' ')[1];
// Validate token here
await next();
},
path: '/api/*',
}
CORS Support
{
handler: async (c, next) => {
// Add CORS headers
c.header("Access-Control-Allow-Origin", "*");
c.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
c.header("Access-Control-Allow-Headers", "Content-Type, Authorization");
// Handle preflight requests
if (c.req.method === "OPTIONS") {
return new Response(null, { status: 204 });
}
await next();
};
}
Request Logging
{
handler: async (c, next) => {
const start = Date.now();
await next();
const duration = Date.now() - start;
console.log(`${c.req.method} ${c.req.url} - ${duration}ms`);
};
}
Special Mastra Headers
When integrating with Mastra Cloud or building custom clients, there are special headers that clients send to identify themselves and enable specific features. Your server middleware can check for these headers to customize behavior:
{
handler: async (c, next) => {
// Check for Mastra-specific headers in incoming requests
const isFromMastraCloud = c.req.header("x-mastra-cloud") === "true";
const clientType = c.req.header("x-mastra-client-type"); // e.g., 'js', 'python'
const isDevPlayground = c.req.header("x-mastra-dev-playground") === "true";
// Customize behavior based on client information
if (isFromMastraCloud) {
// Special handling for Mastra Cloud requests
}
await next();
};
}
These headers have the following purposes:
x-mastra-cloud
: Indicates that the request is coming from Mastra Cloudx-mastra-client-type
: Specifies the client SDK type (e.g., ‘js’, ‘python’)x-mastra-dev-playground
: Indicates that the request is from the development playground
You can use these headers in your middleware to implement client-specific logic or enable features only for certain environments.
Deployment
Since Mastra builds to a standard Node.js server, you can deploy to any platform that runs Node.js applications:
- Cloud VMs (AWS EC2, DigitalOcean Droplets, GCP Compute Engine)
- Container platforms (Docker, Kubernetes)
- Platform as a Service (Heroku, Railway)
- Self-hosted servers
Building
Build the application:
# Build from current directory
mastra build
# Or specify a directory
mastra build --dir ./my-project
The build process:
- Locates entry file (
src/mastra/index.ts
orsrc/mastra/index.js
) - Creates
.mastra
output directory - Bundles code using Rollup with tree shaking and source maps
- Generates Hono HTTP server
See mastra build
for all options.
Running the Server
Start the HTTP server:
node .mastra/output/index.mjs
Serverless Deployment
Mastra also supports serverless deployment on Cloudflare Workers, Vercel, and Netlify.
See our Serverless Deployment guide for setup instructions.