AI Web Applications
How We Build Agent-Powered Web Apps with Next.js and Mastra
One TypeScript codebase, from the chat box to the ERP
Chatbots answer questions. Agents get work done. Here is the stack we use to put agents inside real web products, with the code, the diagrams and the mistakes we no longer make.
- AI Web Applications
- Next.js
- Mastra
- AI Agents
A year ago, most "AI features" we were asked to build were chat boxes. Someone typed a question, a model answered, and that was it. Useful, but limited: the moment a user asked the bot to do something, like check stock, draft a quote or update a record, we were back to writing piles of glue code.
Today almost every project we take on is about agents: software that reads a request, decides which tools to use, takes action in your systems and asks a person when it should. We build them with two pieces we trust: Next.js for the web app, and Mastra for the agent itself.
This article walks through how that fits together, using a real example, with the code and the trade-offs. No hype, just the setup we use every week.
- language, TypeScript, from UI to agent
- 1
- repository and one deploy
- 1
- hand-written agent loops
- 0
- to switch AI provider
- 1 line
Why Next.js and Mastra work so well together
Next.js already handles the hard web parts: pages that load fast, secure server code, streaming responses and simple deployment. What it doesn't give you is an opinion on how an agent should think, use tools, remember things or wait for approval.
That's the gap Mastra fills. It's an open-source TypeScript framework with a small set of building blocks:
- Agents: a model, plain-language instructions and a set of tools.
- Tools: typed functions the agent is allowed to call, like "check stock" or "create quote".
- Workflows: fixed, step-by-step processes for the things that must happen the same way every time.
- Memory: conversation history and user context, stored in your own database.
- Evals and tracing: so you can see what the agent did and measure whether it's getting better or worse.
Because both sides are TypeScript, the agent lives in a folder inside the Next.js project. The same types flow from the database to the tool to the screen. When a tool's input changes, the compiler tells you everywhere that needs fixing. That alone saves us days on every project.
- 01
Chat UI
React · useChat
Streams the answer word by word and shows which tools the agent is using.
- streaming
- tool status
- approvals
- 02
Next.js route handler
app/api/chat/route.ts
Checks who the user is and decides which memory thread they can use.
- auth
- rate limits
- memory ids
- 03
Mastra agent
src/mastra/agents
Reads the request, picks tools and writes the reply.
- instructions
- model
- memory
- 04
Tools and workflows
src/mastra/tools · workflows
The only way the agent can touch your systems. Typed, validated and logged.
- checkStock
- getPriceList
- quoteApproval
- 05
Your systems
Postgres · ERP · CRM
Nothing new to host: the agent works with the data you already have.
- Postgres
- ERP API
- CRM
Our running example: a quote assistant
To keep this concrete, imagine a distributor of industrial parts. Their sales team spends hours a day answering the same kind of email:
"Can you ship 400 M8 bolts to Bergamo by Friday, and what's our price?"
Answering means checking stock in the ERP, finding the customer's price list, working out a delivery date and writing a quote. Discounts above 10% need a manager's sign-off.
That's a perfect job for an agent: lots of small lookups, a clear outcome and one step where a human must stay in charge. Let's build it.
Step 1: give the agent tools, not just a prompt
The biggest shift in thinking is this: the agent is only as useful as the tools you give it. A great prompt with no tools can only talk. A decent prompt with good tools can work.
In Mastra, a tool is a function with a description and a schema. The description tells the model when to use it. The schema makes sure the model sends valid input, and that what comes back is what you expect.
import { createTool } from '@mastra/core/tools';import { z } from 'zod';import { erp } from '@/lib/erp';export const checkStock = createTool({ id: 'check-stock', description: 'Check stock and the earliest ship date for a product code', inputSchema: z.object({ sku: z.string().describe('Product code, for example M8-40-A2'), quantity: z.number().int().positive(), }), outputSchema: z.object({ available: z.number(), earliestShipDate: z.string(), }), execute: async ({ sku, quantity }) => erp.stock(sku, quantity),});A few rules we follow for every tool:
- One job per tool. "Check stock" and "reserve stock" are two tools, not one with a flag.
- Write the description for a new colleague. If a person couldn't tell when to use it, neither can the model.
- Tools read before they write. Anything that changes data gets extra checks, or goes through a workflow (more on that below).
Step 2: describe the agent like you'd brief a new hire
The agent itself is short. Most of the work is in the instructions, and we write them the way we'd brief a new person on the sales team: what the job is, what to always do, what to never do.
import { Agent } from '@mastra/core/agent';import { Memory } from '@mastra/memory';import { checkStock, getPriceList, draftQuote } from '../tools';export const quoteAgent = new Agent({ id: 'quote-agent', name: 'Quote Assistant', instructions: ` You help our sales team answer stock and pricing questions and draft quotes. Always check stock before promising a delivery date. Always use the customer's own price list. Never invent a price. If something is unclear, ask one short question instead of guessing. `, model: 'anthropic/claude-sonnet-5-5', tools: { checkStock, getPriceList, draftQuote }, memory: new Memory({ options: { lastMessages: 20 } }),});Notice the model is just a string. Trying another provider, or a cheaper model for simple tasks, is a one-line change. We test that way all the time.
Then we register everything in one place:
import { Mastra } from '@mastra/core';import { LibSQLStore } from '@mastra/libsql';import { quoteAgent } from './agents/quote-agent';import { quoteApproval } from './workflows/quote-approval';export const mastra = new Mastra({ agents: { quoteAgent }, workflows: { quoteApproval }, storage: new LibSQLStore({ id: 'mastra-storage', url: process.env.MASTRA_DB_URL! }),});Before writing a single line of UI, we chat with the agent in Mastra's local dev environment. It shows every tool call and every step, so the client can try the agent in week one and tell us what's wrong while it's still cheap to change.
Step 3: stream it into your Next.js app
Now the agent needs a front door. In Next.js that's a route handler. It does two jobs: check who's asking, then stream the agent's answer back.
import { handleChatStream } from '@mastra/ai-sdk';import { createUIMessageStreamResponse } from 'ai';import { mastra } from '@/mastra';import { auth } from '@/lib/auth';import { threadFor } from '@/lib/threads';export async function POST(req: Request) { const session = await auth(); if (!session) return new Response('Unauthorized', { status: 401 }); const params = await req.json(); const stream = await handleChatStream({ mastra, agentId: 'quote-agent', version: 'v7', params: { ...params, // The server decides whose memory this is. Never trust ids from the browser. memory: { resource: session.user.id, thread: await threadFor(session.user.id, params.threadId), }, }, }); return createUIMessageStreamResponse({ stream });}On the page, the useChat hook from the AI SDK does the rest: it sends messages, receives the stream and re-renders as words arrive.
'use client';import { useChat } from '@ai-sdk/react';import { DefaultChatTransport } from 'ai';export function QuoteChat() { const { messages, sendMessage, status } = useChat({ transport: new DefaultChatTransport({ api: '/api/chat' }), }); // render messages, tool badges and the input box}Streaming isn't a nice-to-have. People happily wait six seconds for a good answer, but three seconds of a blank screen feels broken. We also show tool activity as it happens ("Checking stock…", "Loading price list…"), so users can see the agent is working and trust what it says.
- 01
Browser
Message sent
useChat posts the message to /api/chat.
- 02
Next.js
User checked
The route checks the session and picks the right memory thread.
- 03
Mastra
Agent plans
It reads the request and recent history, then decides what it needs.
- 04
Tools
Real data
checkStock and getPriceList call the ERP. Every input is validated.
- 05
Browser
Answer streams
Words and tool badges appear live. The draft quote is ready to review.
Step 4: use workflows for the parts that must not improvise
Agents are great when the path isn't known in advance. But some things should happen exactly the same way every time, like approving a big discount. You don't want a model to be creative there.
That's what Mastra workflows are for. A workflow is a fixed list of typed steps. A step can pause the run and wait for a person, and the run is saved, so it can resume minutes or days later.
Agent
When the path depends on the question
- Understands messy, natural language
- Chooses which tools to call and in what order
- Asks for missing details
- Great for answering, searching and drafting
Workflow
When the steps must never change
- Same steps, same order, every time
- Can pause and wait for a human
- Typed input and output at every step
- Great for approvals, payments and anything audited
Our rule: the agent can start a workflow, but it can never skip a step inside one.
Here's the approval step for our quote assistant:
import { createStep, createWorkflow } from '@mastra/core/workflows';import { z } from 'zod';import { sendQuote } from './send-quote';const managerApproval = createStep({ id: 'manager-approval', inputSchema: z.object({ quoteId: z.string(), discount: z.number() }), suspendSchema: z.object({ reason: z.string() }), resumeSchema: z.object({ approved: z.boolean(), approvedBy: z.string() }), outputSchema: z.object({ quoteId: z.string(), approved: z.boolean() }), execute: async ({ inputData, resumeData, suspend }) => { const { quoteId, discount } = inputData; // Small discounts go straight through. if (discount <= 0.1) return { quoteId, approved: true }; // Bigger ones wait for a manager. The run is saved until they decide. if (!resumeData) { return await suspend({ reason: `A ${discount * 100}% discount needs a manager` }); } return { quoteId, approved: resumeData.approved }; },});export const quoteApproval = createWorkflow({ id: 'quote-approval', inputSchema: z.object({ quoteId: z.string(), discount: z.number() }), outputSchema: z.object({ quoteId: z.string(), approved: z.boolean() }),}) .then(managerApproval) .then(sendQuote) .commit();In the Next.js app, the manager sees pending approvals on a normal page. Clicking "Approve" calls a server action that resumes the run. No new infrastructure, just a button, a server action and a saved workflow.
Memory: remembering without oversharing
Memory is what makes an agent feel like a colleague instead of a form. It remembers that this rep always quotes for the same three customers, or that the last message was about Bergamo.
Mastra organises memory around two ids: the resource (usually the user) and the thread (one conversation). The rule that matters most: those ids come from your server, never from the browser. Look at the route handler above: the user id comes from the session, and the thread is checked against that user. Skip this, and one user could read another user's conversations.
The same idea applies to data. If a tool fetches documents or customer records, it filters by what this user is allowed to see before anything reaches the model. The model can't leak what it never received.
Before launch: evals, tracing and costs
The difference between a demo and a product is whether you can tell, with numbers, that a change made things better. Before any agent goes live we set up three things:
- A test set of real requests. Thirty to a hundred real emails from the sales team, each with the expected outcome. We run them on every change to prompts, tools or models.
- Tracing. Mastra records every step: which tools were called, with what input, how long each took and how many tokens it used. When something goes wrong, we can replay exactly what happened.
- Cost limits. A token budget per request and per user, cheaper models for simple steps and caching for repeated lookups. Surprise bills almost always come from a missing limit, not from the model price.
- 01
Weeks 1–2
Prototype
Agent and first tools, tested in Mastra's dev environment with real requests.
- 02
Weeks 3–6
Build
Next.js screens, auth, memory, workflows and the connections to your systems.
- 03
Weeks 7–9
Harden
Test set, tracing, cost limits and a pilot with a small group of users.
- 04
Week 10+
Launch and improve
Roll out to the team, review real conversations and keep raising the scores.
What we'd tell you over coffee
If you remember only a few things from this article:
- Start with the job, not the model. "Answer quote requests in under two minutes" is a project. "Add AI" isn't.
- Tools decide what the agent can actually do. Spend most of your time there.
- Let people stay in charge of what matters. Approvals, payments and anything you'd be audited on go through a workflow.
- Measure before and after every change. Without a test set, every upgrade is a guess.
Next.js and Mastra let a small team build all of this in one TypeScript codebase, with one deploy, on top of the systems you already have. If you want to learn more about how agents work in general, read our guide to agentic AI. For agents that need to work with your company documents, see RAG for business document intelligence.
Planning an agent for your own team? Our agent-powered software development service covers this stack end to end, or tell us what you'd like to automate and we'll help you scope it.
Frequently asked questions
What teams ask us before starting an agent-powered web app.
What Is a Super Agent? DeepSeek's Router-Worker Design, Explained Honestly
A super agent is one always-on AI agent that watches your tools, hands work to isolated workers and only interrupts you when it matters. Here's how the design works, what DeepSeek's numbers really show, and how to use the idea safely.
AI Gateway: How We Route Voice, Vision, Text and Decisions Across Multiple Models
What an AI gateway is, why one model isn't enough, and how our custom AI gateway routes voice, vision, text and decisions to the right model, with security and cost control built in.
PLC to MES Interconnection for Industry 4.0: Connecting Machines with OPC-UA
How to connect PLC machines to a MES in real time over OPC-UA, and why machine interconnection is the key requirement for Italy's 2026 iperammortamento (Industry 4.0).