Next.jsプロジェクトにMastraを統合する
MastraはNext.jsと統合されており、以下のことが簡単にできます:
- 柔軟なAPIを構築してAI搭載機能を提供
- フロントエンドとバックエンドを統一したコードベースでデプロイを簡素化
- Next.jsの組み込みサーバーアクション(App Router)やAPI Routes(Pages Router)を活用し、効率的なサーバー・クライアントワークフローを実現
このガイドを使って、Next.jsプロジェクトにMastraをスキャフォールドし、統合しましょう。
App Router
このガイドは、プロジェクトのルートで Next.js App Router(例:app
、src/app
ではなく)を使用していることを前提としています。
Mastra をインストールする
必要な Mastra パッケージをインストールします:
npm
npm install mastra@latest @mastra/core@latest @mastra/libsql@latest
Mastra を統合する
プロジェクトに Mastra を統合するには、2 つの方法があります。
1. ワンライナーを使う
以下のコマンドを実行して、デフォルトの Weather エージェントを素早くスキャフォールドできます(適切なデフォルト設定付き):
npx mastra@latest init --dir . --components agents,tools --example --llm openai
詳細は mastra init をご覧ください。
2. 対話型 CLI を使う
セットアップをカスタマイズしたい場合は、init
コマンドを実行し、表示されるオプションから選択してください。
npx mastra@latest init
package.json
に dev
と build
スクリプトを追加します:
{
"scripts": {
...
"dev:mastra": "mastra dev --dir mastra",
"build:mastra": "mastra build --dir mastra"
}
}
TypeScript を設定する
プロジェクトのルートにある tsconfig.json
ファイルを修正します:
{
...
"exclude": ["dist", ".mastra"]
}
APIキーを設定する
OPENAI_API_KEY=<your-api-key>
各LLMプロバイダーは異なる環境変数を使用します。詳細はモデルの機能をご覧ください。
Next.js を設定する
next.config.ts
に追加してください:
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
serverExternalPackages: ["@mastra/*"],
};
export default nextConfig;
.gitignore を更新する
.gitignore
ファイルに .mastra
を追加してください:
.mastra
Mastra Dev サーバーを起動する
Mastra Dev サーバーを起動して、エージェントを REST エンドポイントとして公開します。
npm
npm run dev:mastra
サーバーが起動すると、エージェントはローカルで利用可能になります。詳細はローカル開発環境をご覧ください。
Next.js Dev Serverを開始
Mastra Dev Serverが実行されている状態で、通常の方法でNext.jsアプリを開始できます。
テストディレクトリの作成
テスト用の Page、Action、Form を格納する新しいディレクトリを作成します。
mkdir test
テスト Action の作成
新しい Action を作成し、サンプルコードを追加します。
touch app/test/action.ts
"use server";
import { mastra } from "../../mastra";
export async function getWeatherInfo(formData: FormData) {
const city = formData.get("city")?.toString();
const agent = mastra.getAgent("weatherAgent");
const result = await agent.generate(`What's the weather like in ${city}?`);
return result.text;
}
テスト Form の作成
新しい Form コンポーネントを作成し、サンプルコードを追加します。
touch app/test/form.tsx
"use client";
import { useState } from "react";
import { getWeatherInfo } from "./action";
export function Form() {
const [result, setResult] = useState<string | null>(null);
async function handleSubmit(formData: FormData) {
const res = await getWeatherInfo(formData);
setResult(res);
}
return (
<>
<form action={handleSubmit}>
<input name="city" placeholder="Enter city" required />
<button type="submit">Get Weather</button>
</form>
{result && <pre>{result}</pre>}
</>
);
}
テスト Page の作成
新しい Page を作成し、サンプルコードを追加します。
touch app/test/page.tsx
import { Form } from "./form";
export default async function Page() {
return (
<>
<h1>Test</h1>
<Form />
</>
);
}
これでブラウザで
/test
にアクセスして試すことができます。
都市名として London を送信すると、次のような結果が返されます:
Agent response: The current weather in London is as follows:
- **Temperature:** 12.9°C (Feels like 9.7°C)
- **Humidity:** 63%
- **Wind Speed:** 14.7 km/h
- **Wind Gusts:** 32.4 km/h
- **Conditions:** Overcast
Let me know if you need more information!