Skip to Content

ミドルウェア

Mastraサーバーは、APIルートハンドラーが呼び出される前後にカスタムミドルウェア関数を実行できます。これは認証、ログ記録、リクエスト固有のコンテキストの注入、CORSヘッダーの追加などに役立ちます。

ミドルウェアはHonoContextc)とnext関数を受け取ります。Responseを返すと、リクエストは短絡されます。next()を呼び出すと、次のミドルウェアまたはルートハンドラーの処理が続行されます。

import { Mastra } from '@mastra/core'; export const mastra = new Mastra({ server: { middleware: [ { handler: async (c, next) => { // Example: Add authentication check const authHeader = c.req.header('Authorization'); if (!authHeader) { return new Response('Unauthorized', { status: 401 }); } await next(); }, path: '/api/*', }, // Add a global request logger async (c, next) => { console.log(`${c.req.method} ${c.req.url}`); await next(); }, ], }, });

単一のルートにミドルウェアをアタッチするには、registerApiRoutemiddlewareオプションを渡します:

registerApiRoute('/my-custom-route', { method: 'GET', middleware: [ async (c, next) => { console.log(`${c.req.method} ${c.req.url}`); await next(); }, ], handler: async (c) => { const mastra = c.get('mastra'); return c.json({ message: 'Hello, world!' }); }, });

一般的な例

認証

{ handler: async (c, next) => { const authHeader = c.req.header('Authorization'); if (!authHeader || !authHeader.startsWith('Bearer ')) { return new Response('Unauthorized', { status: 401 }); } // Validate token here await next(); }, path: '/api/*', }

CORSサポート

{ handler: async (c, next) => { 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', ); if (c.req.method === 'OPTIONS') { return new Response(null, { status: 204 }); } await next(); }, }

リクエストログ記録

{ 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`); }, }

特別なMastraヘッダー

Mastra Cloudやカスタムクライアントと統合する際、以下のヘッダーをミドルウェアで検査して動作をカスタマイズすることができます:

{ handler: async (c, next) => { const isFromMastraCloud = c.req.header('x-mastra-cloud') === 'true'; const clientType = c.req.header('x-mastra-client-type'); const isDevPlayground = c.req.header('x-mastra-dev-playground') === 'true'; if (isFromMastraCloud) { // Special handling } await next(); }, }
  • x-mastra-cloud: リクエストがMastra Cloudから発信されたことを示す
  • x-mastra-client-type: クライアントSDKを識別する(例:jspython
  • x-mastra-dev-playground: リクエストがローカルプレイグラウンドからトリガーされたことを示す