跳到主要内容
非官方简体中文翻译,内容版权归 Mastra 所有,遵循 Apache-2.0 许可。

Fastify adapter

The @mastra/fastify package provides a server adapter for running Mastra with Fastify. For general adapter concepts (constructor options, initialization flow, etc.), see Server Adapters.

Installation
Installation的直接链接

Install the Fastify adapter and Fastify framework:

npm install @mastra/fastify@latest fastify

Usage example
Usage example的直接链接

server.ts
import Fastify from 'fastify'
import { MastraServer } from '@mastra/fastify'
import { mastra } from './mastra'

const app = Fastify({ logger: true })
const server = new MastraServer({ app, mastra })

await server.init()

app.listen({ port: 3000 }, (err, address) => {
if (err) {
console.error(err)
process.exit(1)
}
console.log(`Server running on ${address}`)
})

init() doesn't start Mastra's background workers. To run scheduled workflows, agent schedules, or event listeners, call await mastra.startWorkers() after the server starts listening. See Start background workers.

Constructor parameters
Constructor parameters的直接链接

app:

FastifyInstance
Fastify app instance

mastra:

Mastra
Mastra instance

prefix?:

string
= '/api'
Route path prefix (e.g., /api/v2)

openapiPath?:

string
= ''
Path to serve OpenAPI spec (e.g., /openapi.json)

bodyLimitOptions?:

BodyLimitOptions
Request body size limits

streamOptions?:

StreamOptions
= { redact: true }
Stream redaction config. When true (default), redacts sensitive data (system prompts, tool definitions, API keys) from stream chunks before sending to clients.

customRouteAuthConfig?:

Map<string, boolean>
Per-route auth overrides. Keys are METHOD:PATH (e.g., GET:/api/health). Value false makes route public, true requires auth.

tools?:

ToolsInput
Available tools for the server

taskStore?:

InMemoryTaskStore
Task store for A2A (Agent-to-Agent) operations

mcpOptions?:

MCPOptions
MCP transport options, such as setRequestAuth to control what tools see as context.mcp.extra.authInfo.

Protecting raw routes
Protecting raw routes的直接链接

When you want Mastra-managed auth and route metadata such as requiresAuth, prefer registerApiRoute(). For raw Fastify routes mounted directly on the app, use createAuthMiddleware():

server.ts
import Fastify from 'fastify'
import { createAuthMiddleware, MastraServer } from '@mastra/fastify'
import { mastra } from './mastra'

const app = Fastify()
const server = new MastraServer({ app, mastra })

await server.init()

app.get('/custom/protected', { preHandler: createAuthMiddleware({ mastra }) }, async request => {
const user = request.requestContext.get('user')
return { user }
})

app.get(
'/custom/public',
{ preHandler: createAuthMiddleware({ mastra, requiresAuth: false }) },
async () => {
return { ok: true }
},
)

Manual initialization
Manual initialization的直接链接

For custom middleware ordering, call each method separately instead of init(). See manual initialization for details.

Examples
Examples的直接链接