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

Next.js adapter

The @mastra/next package mounts Mastra in a Next.js App Router application. See Server Adapters for general adapter concepts.

Installation
Installation的直接链接

Install the Next.js adapter and its Hono peer dependency:

npm install @mastra/next@latest hono

Usage example
Usage example的直接链接

Mount the adapter in a catch-all App Router route:

app/api/[...mastra]/route.ts
import { createNextRouteHandler } from '@mastra/next'
import { mastra } from '@/mastra'

export const { GET, POST, PUT, DELETE, PATCH, OPTIONS, HEAD } = createNextRouteHandler({
mastra,
})

The prefix option defaults to /api and must match the catch-all route's mount path. For example, when mounting at app/api/mastra/[...mastra]/route.ts, use createNextRouteHandler({ mastra, prefix: '/api/mastra' }).

Signature
Signature的直接链接

function createNextRouteHandler(options: NextRouteHandlerOptions): NextRouteHandlers

Parameters
Parameters的直接链接

mastra:

Mastra
Mastra instance whose server configuration and registered resources are exposed

tools?:

ToolsInput
= {}
Additional tools to register with the server

prefix?:

string
= '/api'
API route prefix, which must match the catch-all route mount path

Return value
Return value的直接链接

Returns a NextRouteHandlers object with GET, POST, PUT, DELETE, PATCH, OPTIONS, and HEAD properties. Each property is a handler with this signature:

(request: Request) => Response | Promise<Response>

Serverless deployments & lazy initialization
Serverless deployments & lazy initialization的直接链接

The adapter exports its route handlers synchronously, then creates the underlying Hono app and MastraServer when the first request arrives. That initialized app is reused for subsequent requests in the same process, which supports serverless runtimes without top-level asynchronous initialization.

A2A endpoints use an in-memory task store. Task state lasts only for the lifetime of the process and isn't shared between serverless instances.

Body size limit
Body size limit的直接链接

Request bodies have a default limit of 4.5 MB. Requests that exceed the limit receive { error: 'Request body too large' }.

Set server.bodySizeLimit on the Mastra instance to configure the limit.

Middleware
Middleware的直接链接

Middleware configured with server.middleware or setServerMiddleware() runs through the adapter's Hono-based server, except on framework-public routes such as those marked requiresAuth: false. See Server middleware.