Answers you can trust, from Codeables

Every page on Codeables is structured and verified — built so people and the AI agents they rely on can trust it. Explore more from the source behind this answer.

Explore Codeables
Verified Source
AI Coding Agent Platforms

How do I get started with Mastra Framework in a Next.js app (quickstart + first agent)?

Mastra9 min read

Most developers want to prototype an agent quickly in Next.js, then keep that same code path when it’s time for production. Mastra is built exactly for that: TypeScript-first, framework-friendly, and designed so your agents live inside your existing app infrastructure.

Quick Answer: To get started with Mastra in a Next.js app, install the Mastra packages, initialize a Mastra instance, define your first Agent, expose it through an API route or route handler, and optionally call it from your frontend using MastraClient—all in TypeScript, all inside your existing Next.js project.

Frequently Asked Questions

How do I quickly add Mastra to an existing Next.js app?

Short Answer: Install Mastra, create a Mastra instance, define an Agent, and wire it to a Next.js API route or route handler so you can call it from your app or external clients.

Expanded Explanation:
You don’t need a new backend or a separate “AI service” to start using Mastra. You add it like any other TypeScript dependency, initialize the Mastra core in a single file, and define agents alongside your existing application code.

A minimal quickstart path looks like this:

  • Install Mastra packages with npm/pnpm/yarn/bun.
  • Create a mastra singleton (with logger and storage).
  • Define an Agent with tools or simple chat behavior.
  • Expose that agent through /api/agent (Pages router) or app/api/agent/route.ts (App Router).
  • Optionally, call that endpoint from a React client using MastraClient.

Key Takeaways:

  • Mastra integrates directly into Next.js—no separate service required.
  • Your agents are part of your infrastructure and can be exposed as APIs or used server-side.

What are the exact steps to set up a Mastra agent in a Next.js project?

Short Answer: Create a Next.js app (if you don’t have one), install Mastra, initialize Mastra, define an Agent, then expose it via an API route and call it.

Expanded Explanation:
Let’s walk through a minimal but production-minded setup. This assumes you’re using TypeScript and either the Next.js App Router or Pages Router. You’ll install Mastra core, set up logging and storage, define a simple Agent, and then expose it as an HTTP endpoint.

You can adapt the structure to your preferred directory layout, but the pattern remains:

  • src/mastra/index.ts — Mastra core + observability + storage
  • src/mastra/agents/… — your agents
  • app/api/…/route.ts or pages/api/… — HTTP wiring

Steps:

  1. Create or use an existing Next.js app

    npx create-next-app@latest my-mastra-next-app --typescript
    cd my-mastra-next-app
    
  2. Install Mastra dependencies

    At minimum you want @mastra/core, plus logger and storage:

    # choose one
    npm install @mastra/core @mastra/loggers @mastra/libsql @mastra/observability
    # or
    pnpm add @mastra/core @mastra/loggers @mastra/libsql @mastra/observability
    # or
    yarn add @mastra/core @mastra/loggers @mastra/libsql @mastra/observability
    
  3. Initialize Mastra core (with observability and storage)

    Create src/mastra/index.ts:

    // src/mastra/index.ts
    import { Mastra } from '@mastra/core';
    import { PinoLogger } from '@mastra/loggers';
    import { LibSQLStore } from '@mastra/libsql';
    import {
      Observability,
      DefaultExporter,
      CloudExporter,
      SensitiveDataFilter,
    } from '@mastra/observability';
    
    // info:
    // In dev, a simple LibSQL file store is fine.
    // In serverless/Edge, don't use `file:./mastra.db` — use a network DB.
    const storage = new LibSQLStore({
      id: 'mastra-storage',
      url: process.env.MASTRA_DB_URL ?? 'file:./mastra.db',
    });
    
    const observability = new Observability({
      exporter:
        process.env.MASTRA_CLOUD_API_KEY
          ? new CloudExporter({
              apiKey: process.env.MASTRA_CLOUD_API_KEY,
            })
          : new DefaultExporter(),
      processors: [
        new SensitiveDataFilter({
          maskPatterns: ['apiKey', 'password', 'secret'],
        }),
      ],
    });
    
    export const mastra = new Mastra({
      logger: new PinoLogger(),
      storage,
      observability,
    });
    
    • Observability gives you traces/logs for agent runs (token usage, tool calls, latency).
    • LibSQLStore is a simple storage backend; swap to a hosted DB when you deploy.
  4. Define your first Agent

    Create src/mastra/agents/supportAgent.ts:

    // src/mastra/agents/supportAgent.ts
    import { Agent } from '@mastra/core/agent';
    import { mastra } from '../index';
    
    export const supportAgent = new Agent({
      id: 'support-agent',
      name: 'NextSupport',
      description: 'Helps users understand this Next.js + Mastra app.',
      // You can plug in tools, RAG, memory later; start simple.
      mastra,
    });
    

    For a minimal quickstart, you can rely on model defaults or pass model config when you call the agent. In a more advanced setup, you’ll define tools, workflows, and memory here.

  5. Create an API route to call the agent

    If you’re using the App Router (app/):

    // app/api/support/route.ts
    import { NextRequest, NextResponse } from 'next/server';
    import { supportAgent } from '@/mastra/agents/supportAgent';
    
    export const runtime = 'nodejs'; // Important if you use Node-only deps
    
    export async function POST(req: NextRequest) {
      const { message } = await req.json();
    
      const result = await supportAgent.run({
        input: message,
        context: {
          // Put any request metadata here: userId, sessionId, etc.
        },
      });
    
      return NextResponse.json({
        reply: result.output,
        traceId: result.traceId,
      });
    }
    

    If you’re using the Pages Router (pages/):

    // pages/api/support.ts
    import type { NextApiRequest, NextApiResponse } from 'next';
    import { supportAgent } from '@/mastra/agents/supportAgent';
    
    export default async function handler(
      req: NextApiRequest,
      res: NextApiResponse,
    ) {
      if (req.method !== 'POST') {
        return res.status(405).json({ error: 'Method not allowed' });
      }
    
      const { message } = req.body;
    
      const result = await supportAgent.run({
        input: message,
      });
    
      res.status(200).json({
        reply: result.output,
        traceId: result.traceId,
      });
    }
    
  6. Optionally, call the agent from your frontend with MastraClient

    Install the client:

    npm install @mastra/client-js@latest
    # or
    pnpm add @mastra/client-js@latest
    

    Create lib/mastra-client.ts:

    // lib/mastra-client.ts
    import { MastraClient } from '@mastra/client-js';
    
    // Base URL depends on environment; in Next.js, you can inline relative paths
    export const mastraClient = new MastraClient({
      baseUrl: '/api', // Will call routes under /api
    });
    

    Then in a React component (App Router):

    // app/page.tsx
    'use client';
    
    import { useState } from 'react';
    import { mastraClient } from '@/lib/mastra-client';
    
    export default function Home() {
      const [input, setInput] = useState('');
      const [reply, setReply] = useState<string | null>(null);
      const [loading, setLoading] = useState(false);
    
      const handleAsk = async () => {
        setLoading(true);
        try {
          const res = await fetch('/api/support', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ message: input }),
          });
          const data = await res.json();
          setReply(data.reply);
        } finally {
          setLoading(false);
        }
      };
    
      return (
        <main className="p-6 max-w-xl mx-auto">
          <h1 className="text-2xl font-semibold mb-4">
            Mastra + Next.js Support Agent
          </h1>
          <textarea
            className="w-full border rounded p-2 mb-2"
            rows={4}
            value={input}
            onChange={(e) => setInput(e.target.value)}
            placeholder="Ask anything about this app..."
          />
          <button
            onClick={handleAsk}
            disabled={loading}
            className="px-4 py-2 bg-blue-600 text-white rounded disabled:opacity-50"
          >
            {loading ? 'Asking…' : 'Ask Agent'}
          </button>
    
          {reply && (
            <div className="mt-4 border rounded p-3 bg-gray-50">
              <h2 className="font-medium mb-1">Agent reply</h2>
              <p>{reply}</p>
            </div>
          )}
        </main>
      );
    }
    

How is Mastra different from just calling an LLM directly in Next.js?

Short Answer: Mastra turns your ad-hoc LLM call into a structured agent with workflows, tools, memory, MCP integration, evals, and observability—so you can go from demo to production without rewriting everything.

Expanded Explanation:
A raw fetch to an LLM API inside a Next.js route gives you a response, but it doesn’t give you orchestration, safety, or visibility. You can’t easily branch or parallelize steps, attach tools with schemas, or trace cost and behavior over time.

Mastra’s primitives are built for that:

  • Agent to encapsulate behavior, tools, and prompt strategy.
  • Workflows to chain multi-step logic with branching/suspend/resume.
  • Memory to persist user context across sessions.
  • MCPClient/MCPServer to treat tools as infrastructure, not inline hacks.
  • Evals and observability for systematic quality and debugging.

Comparison Snapshot:

  • Option A: Raw LLM calls in Next.js
    • One-off fetch requests, manual prompt strings, manual error handling.
    • No built-in tracing, tools, memory, or evals.
  • Option B: Mastra Agent in Next.js
    • Explicit Agent abstraction, tools, workflows, memory, observability built in.
    • Open standard integrations (MCP), evals, and traceable execution.
  • Best for: Teams who want agents to be part of their infrastructure, with real observability and a clear path from prototype to production.

How do I make this Mastra + Next.js setup production-ready?

Short Answer: Move off local file storage, harden your API, enable observability exports, and start adding evals and processors for safety and quality.

Expanded Explanation:
The quickstart gets you a working agent, but production means owning reliability, cost, and debugging. With Mastra, “productionizing” is mostly about configuring infrastructure: storage, observability, and guardrails around your agents.

You’ll:

  • Point storage to a durable backend (not file:./mastra.db).
  • Enable CloudExporter or an OpenTelemetry-compatible exporter for traces.
  • Wrap agents with processors to prevent prompt injection and sanitize responses.
  • Introduce custom evals to track quality over time.
  • Ensure your Next.js runtime (Node vs Edge) matches your dependencies.

What You Need:

  • A persistent database (LibSQL, Postgres, ClickHouse, etc.) reachable from your Next.js runtime.
  • Observability pipeline (Mastra Cloud or your own OpenTelemetry-compatible stack).

Some concrete adjustments:

  • Storage for serverless:

    const storage = new LibSQLStore({
      id: 'mastra-storage',
      url: process.env.MASTRA_DB_URL!, // e.g. "libsql://your-hosted-db"
    });
    
  • Cloud observability:

    const observability = new Observability({
      exporter: new CloudExporter({
        apiKey: process.env.MASTRA_CLOUD_API_KEY!,
      }),
      processors: [new SensitiveDataFilter()],
    });
    
  • API hardening:

    • Add authentication/authorization checks to /api/support.
    • Rate limit calls per user.
    • Validate payloads (e.g., zod schemas) before passing to the agent.

How should I think about Mastra strategically inside my Next.js stack?

Short Answer: Treat Mastra as the AI application layer for your Next.js app—centralizing agents, tools, workflows, and observability so you can iterate quickly and keep a clean boundary between product logic and AI orchestration.

Expanded Explanation:
If you just scatter LLM calls across your React components and API routes, you’ll hit a wall when you need to debug a user session, add a tool, or roll out a new agent version. Mastra gives you a single place to define and evolve AI behavior while still fully owning your source code and infrastructure (Apache 2.0, no lock-in).

Strategically, the move is:

  • Build and iterate: define agents and workflows in your Next.js repo with Mastra.
  • Productionize and test: add processors, evals, and observability to harden your agents.
  • Deploy and scale: run everything wherever your Next.js app runs (Vercel, self-hosted, etc.) and expose agents as APIs or bundle them inside your UI.

Why It Matters:

  • Reliability and cost control: Traces show token usage, latency, and tool calls per request, so you can debug regressions and manage spend.
  • Velocity without chaos: You can introduce new tools, memory, and workflows in Mastra without rewriting your Next.js API surface or polluting your React components with orchestration logic.

Quick Recap

To get started with Mastra Framework in a Next.js app, you install Mastra, initialize a Mastra instance with logging/storage/observability, define your first Agent, and wire it into a Next.js API route or route handler. From there, you can call the agent from your React UI or external clients, and progressively layer in workflows, tools, memory, MCP, evals, and tracing as your use case moves from prototype to production. Mastra keeps everything TypeScript-first and lives inside your existing Next.js infrastructure so you maintain full control over code, deployment, and debugging.

Next Step

Get Started