Skip to Content

Next.jsプロジェクトにMastraを統合する

MastraをNext.jsアプリケーションに統合する主な方法は2つあります:別個のバックエンドサービスとして、またはNext.jsアプリに直接統合する方法です。

1. バックエンドの個別統合

以下を実現したい大規模プロジェクトに最適:

  • AIバックエンドを独立してスケーリング
  • 明確な関心の分離を維持
  • より柔軟なデプロイメント

Mastraバックエンドの作成

CLIを使用して新しいMastraプロジェクトを作成します:

npx create-mastra@latest

詳細なセットアップ手順については、インストールガイドをご覧ください。

MastraClientのインストール

npm install @mastra/client-js@latest

MastraClientの使用

クライアントインスタンスを作成し、Next.jsアプリケーションで使用します:

lib/mastra.ts
import { MastraClient } from "@mastra/client-js"; // Initialize the client export const mastraClient = new MastraClient({ baseUrl: process.env.NEXT_PUBLIC_MASTRA_API_URL || "http://localhost:4111", });

Reactコンポーネントでの使用例:

app/components/SimpleWeather.tsx
'use client' import { mastraClient } from '@/lib/mastra' export function SimpleWeather() { async function handleSubmit(formData: FormData) { const city = formData.get('city') const agent = mastraClient.getAgent('weatherAgent') try { const response = await agent.generate({ messages: [{ role: 'user', content: `What's the weather like in ${city}?` }], }) // Handle the response console.log(response.text) } catch (error) { console.error('Error:', error) } } return ( <form action={handleSubmit}> <input name="city" placeholder="Enter city name" /> <button type="submit">Get Weather</button> </form> ) }

デプロイメント

デプロイの準備ができたら、プラットフォーム固有のデプロイヤー(Vercel、Netlify、Cloudflare)を使用するか、任意のNode.jsホスティングプラットフォームにデプロイできます。詳細な手順については、デプロイメントガイドをご確認ください。

2. 直接統合

小規模なプロジェクトやプロトタイプに適しています。このアプローチではMastraをNext.jsアプリケーションに直接バンドルします。

Next.jsのルートでMastraを初期化する

まず、Next.jsプロジェクトのルートに移動し、Mastraを初期化します:

cd your-nextjs-app

次に初期化コマンドを実行します:

npx mastra@latest init

これによりNext.jsプロジェクトにMastraがセットアップされます。初期化やその他の設定オプションの詳細については、mastra init リファレンスをご覧ください。

Next.jsの設定

next.config.jsに以下を追加します:

next.config.js
/** @type {import('next').NextConfig} */ const nextConfig = { serverExternalPackages: ["@mastra/*"], // ... その他のNext.js設定 }; module.exports = nextConfig;

サーバーアクションの例

app/actions.ts
"use server"; import { mastra } from "@/mastra"; export async function getWeatherInfo(city: string) { const agent = mastra.getAgent("weatherAgent"); const result = await agent.generate(`What's the weather like in ${city}?`); return result; }

コンポーネントでの使用方法:

app/components/Weather.tsx
'use client' import { getWeatherInfo } from '../actions' export function Weather() { async function handleSubmit(formData: FormData) { const city = formData.get('city') as string const result = await getWeatherInfo(city) // 結果を処理する console.log(result) } return ( <form action={handleSubmit}> <input name="city" placeholder="Enter city name" /> <button type="submit">Get Weather</button> </form> ) }

APIルートの例

app/api/chat/route.ts
import { mastra } from "@/mastra"; import { NextResponse } from "next/server"; export async function POST(req: Request) { const { city } = await req.json(); const agent = mastra.getAgent("weatherAgent"); const result = await agent.stream(`What's the weather like in ${city}?`); return result.toDataStreamResponse(); }

デプロイメント

直接統合を使用する場合、MastraインスタンスはNext.jsアプリケーションと一緒にデプロイされます。以下を確認してください:

  • デプロイメントプラットフォームでLLM APIキーの環境変数を設定する
  • 本番環境での適切なエラーハンドリングを実装する
  • AIエージェントのパフォーマンスとコストを監視する

オブザーバビリティ

Mastra は、AI オペレーションの監視、デバッグ、最適化を支援するための組み込みオブザーバビリティ機能を提供します。これには以下が含まれます:

  • AI オペレーションとそのパフォーマンスのトレーシング
  • プロンプト、コンプリーション、エラーのロギング
  • Langfuse や LangSmith などのオブザーバビリティプラットフォームとの統合

Next.js のローカル開発に特化した詳細なセットアップ手順や設定オプションについては、Next.js オブザーバビリティ設定ガイドをご覧ください。