TypeScript AI Agent
AdvancedAi AgentsA code-first AI agent in TypeScript: one Next.js app for the agent, its API, and its chat interface.
Published 2 October 2026
About TypeScript AI Agent
This stack builds an agent and the interface people use to talk to it in one TypeScript codebase. The agent is code you write: a language model picks the next step, calls your tools, reads the results, and repeats until the task is done. The Vercel AI SDK is the default framework for that loop. It gives one API across model providers, typed tool definitions, and an agent class that keeps calling tools until a stop condition is met. Mastra and LangChain fill the same role with more built in, and the rest of the stack stays the same whichever you choose.
Next.js carries both halves. A route handler runs the agent on the server and streams its answer to the browser as it is produced, and React renders the conversation, including tool calls and their results, through the AI SDK's chat hooks. Types flow from the tool definitions on the server to the components that display them, so a change to a tool shows up as a compile error and not as a broken screen.
PostgreSQL holds what the agent has to remember: conversations, messages, and whatever your tools read and write. The AI SDK leaves storage to you, so you save each finished message to your own tables, while Mastra and LangChain bring their own PostgreSQL storage for threads and run state. The same database can hold embeddings through the pgvector extension, which covers retrieval for many agents before a dedicated vector database is needed.
Where the app runs decides how long a run can last. On a serverless platform each request has a time limit, which suits chat-length runs and needs a durable workflow layer for anything longer. On a container host the app is an ordinary long-lived Node.js server with no such limit. The model is a separate choice from all of this: Claude is the default, and OpenAI or Gemini is a small configuration change. Sign-in with Clerk or BetterAuth is optional and worth adding once the agent has more than one user, as are tracing with Langfuse or LangSmith and a sandbox such as E2B for code the agent writes.
Key Features
- ✓An agent loop on a TypeScript framework: the Vercel AI SDK by default, or Mastra or LangChain
- ✓One Next.js app for the agent, its API routes, and the chat interface
- ✓Streaming responses, with tool calls and their results rendered in React as they happen
- ✓Types shared from the tool definitions on the server to the components that display them
- ✓Model-agnostic: Claude by default, with OpenAI or Gemini a configuration change away
- ✓Conversations and agent state in PostgreSQL, with vector search available through pgvector
When to Use TypeScript AI Agent
- →A chat assistant inside a product, with tools that read and change the user's own data
- →An internal copilot over company documents and APIs
- →A customer-facing support agent with its own branded chat interface
- →Generative interfaces, where the agent's tool results render as live React components
- →A prototype that has to become a deployed, shareable app quickly
Pros
- Agent and interface live in one codebase and one deployment, in one language
- End-to-end types catch mismatches between tools, model output, and the interface at compile time
- Most of the chat interface is provided: streaming, message state, and tool rendering come from ready-made hooks
- Each layer swaps on its own: framework, model, database, and host
Cons
- Serverless hosting puts a time limit on each run, so long tasks need a workflow layer or a container host
- Python still has more agent frameworks, evaluation tools, and data libraries
- With the Vercel AI SDK, the default framework, saving and loading conversations is code you write
- The agent frameworks change quickly between major versions, so upgrades can mean reworking code
Database Options for TypeScript AI Agent
The default: a PostgreSQL instance you run yourself or rent as a plain managed database. It stores conversations, messages, and the data your tools work on, and with the pgvector extension it also holds embeddings. Vercel, the default host, does not run databases itself, so on that route the instance lives with another provider, while on a container host it can sit in the same project as the app. From serverless functions, connect through a pooler so short-lived instances don't use up the connection limit.
Serverless PostgreSQL, and the usual pairing on Vercel: it installs from the Vercel Marketplace, scales to zero when nobody is chatting, and has a serverless driver suited to short-lived functions. The free plan covers a prototype, and paid usage is billed at $0.106 per compute-unit hour and $0.35 per GB a month with no minimum. pgvector is available on every plan, and each preview deployment can get its own database branch.
Managed PostgreSQL with a dashboard, built-in pgvector, and a connection pooler that suits serverless functions. It also brings auth and file storage, which can stand in for a separate sign-in service if the agent later needs user accounts. The free plan pauses a project after a week without activity, so anything long-lived belongs on Pro, from $25 a month.
These are highlighted picks. To see all the tools, check the Databases category.
LLM Options for TypeScript AI Agent
The default. Claude holds up well over long tool-calling runs and follows detailed instructions across many steps. The frameworks expose it through the same calls as every other model, so nothing else in the app depends on the choice. The current Sonnet model costs $2 per million input tokens and $10 per million output, and Haiku at $1 and $5 suits simple steps. Prompt caching cuts the price of the instructions and tool definitions resent with every message.
GPT models are widely supported across TypeScript agent tooling, and many framework examples are written against them first. The mid-tier model costs $2 per million input tokens and $10 per million output, the same as Claude's, and the smallest tier at $0.10 and $0.50 is a cheap way to run high-volume simple steps such as titling a conversation or routing a request.
Gemini's Flash and Flash-Lite models are priced below the mid-tier models from Anthropic and OpenAI, which matters in a chat product where every message resends the conversation. They take images, audio, and video as input, useful when users upload screenshots or files. Several of them have a rate-limited free tier in Google AI Studio, enough to build and demo the agent before paying anything.
These are highlighted picks. To see all the tools, check the LLM category.
Hosting Options for TypeScript AI Agent
The platform Next.js is built for: push to Git and the app deploys, with a preview for every branch. The agent runs in Vercel Functions, where time spent waiting on the model is not billed as CPU. A run can last up to 300 seconds on Hobby and 800 seconds on Pro, and Vercel Workflows covers longer or resumable runs. Hobby is free for personal, non-commercial projects, and Pro is $20 a month per seat with $20 of usage included. The AI Gateway reaches many model providers through one key with no markup.
A container platform that runs Next.js as a long-lived Node.js server, so a run is not bound by a serverless function's time limit and background work continues after the response is sent. A PostgreSQL service is added to the same project from a template, which keeps the app and its database on one private network. The Hobby plan is $5 a month including $5 of usage, and memory is billed at about $10 per GB a month.
Runs the app as a container on machines in the regions you choose, billed per second, with the option to stop idle machines and start them on the next request. A fit when users are spread across continents or when the agent keeps WebSocket connections open. A small always-on machine with 1 GB of RAM costs under $10 a month. The app ships as a Docker image, so there is a little more setup than on a Git-push platform.
For teams already on AWS. Next.js runs as a container on ECS with Fargate, PostgreSQL on RDS, and models are available through Amazon Bedrock, which the AI SDK supports as a provider, so model usage lands on the same account and bill. Expect more setup than the other three: networking, a load balancer, and a deploy pipeline are yours to configure, and the bill starts at tens of dollars a month once the load balancer and the database are running.
These are highlighted picks. To see all the tools, check the Hosting & Cloud category.
Agent Framework Options for TypeScript AI Agent
The default, and the lightest of the three. The AI SDK gives one API for text, structured output, and tool calling across model providers, an agent class (ToolLoopAgent) that keeps calling tools until a stop condition you set, and React hooks such as useChat that render the stream. It deliberately stores nothing: you save finished messages to PostgreSQL yourself. Pick it when you want a thin layer you fully control and the agent lives inside a Next.js app.
A fuller framework built for TypeScript that runs in the same Next.js route handlers and streams to the same AI SDK chat hooks. It adds what the AI SDK leaves out: agent memory with threads and semantic recall stored in PostgreSQL, a workflow engine with typed steps and retries, and built-in evals and tracing. Pick it when the agent needs long-term memory or multi-step workflows and you would rather configure those than write them.
LangChain.js mirrors the Python library: createAgent gives a tool-calling agent in a few lines and runs on LangGraph underneath, with a PostgreSQL checkpointer that saves state after every step and middleware for human approval, retries, and summarising long conversations. Pick it when the team already knows LangChain from Python, when you want graph-style control over a run, or when you plan to trace with LangSmith.
These are highlighted picks. To see all the tools, check the Agent Frameworks category.
TypeScript AI Agent Add-ons
Each addition below extends this stack with a capability the base stack works fine without. None are required: include the ones your product actually needs when building this stack, and skip the rest.
Authentication Add-ons
Add authentication when the app needs user accounts — sign-up, login, and data scoped to a specific user instead of a fully open app.
Hosted sign-in with prebuilt React components and Next.js middleware, so each conversation can be tied to a user without building login screens. The free plan covers 50,000 monthly retained users per app, and Pro is $25 a month, or $20 billed yearly. Add it when the agent is opened to more than one person and conversations have to be private to their owner.
An open-source TypeScript auth library that runs inside the Next.js app and keeps users and sessions in the same PostgreSQL database as the conversations. There is no per-user fee and no third-party service holding the accounts, at the cost of building the sign-in screens yourself. A natural choice when the agent's data has to stay in your own database.
These are highlighted picks. To see all the tools, check the Authentication category.
Vector Db Add-ons
Add a vector database when the agent needs to find documents, notes, or past conversations by meaning instead of exact keywords.
A fully managed, serverless vector database, which matches a serverless app: there is no server to keep warm, and the TypeScript client is called straight from a route handler. Hosted embedding and reranking models are part of the service, and the Starter plan is free for prototypes. Add it when the document collection outgrows pgvector on the main PostgreSQL database, or when you would rather not tune a vector index yourself.
An open-source vector database with a managed cloud and a free small cluster for testing, or a single container you run next to the app on a container host. It filters on metadata during the search itself, which matters when each user must only retrieve their own documents. The choice when you want the freedom to self-host later, or fine control over how results are ranked.
The simplest store to start with. Chroma has a JavaScript client and a managed Chroma Cloud with usage-based pricing, and it embeds documents for you, so a first retrieval tool is a few lines. In a serverless deployment it has to be the cloud version or a separately hosted server, since a function has no disk to keep a local database on.
Llm Observability Add-ons
Add LLM observability when you want to see every model call, tool call, and token cost inside a run, so a wrong answer can be traced to the step that caused it.
Open-source tracing and evaluation with integrations for the Vercel AI SDK and LangChain. Every model call and tool call in a conversation shows up as a nested trace with its cost and latency, which is how you find out why an answer went wrong. The cloud Hobby plan is free up to 50,000 units a month and Core is $29, or it can be self-hosted for free.
LangChain's own platform and the closest fit when the agent is built on LangChain.js, where tracing is switched on with environment variables. Agents on the other frameworks can send traces through its TypeScript SDK or OpenTelemetry. The Developer plan is free for one seat with 5,000 traces a month, and Plus is $39 per seat. It is a hosted, closed-source service.
Code Sandbox Add-ons
Add a code sandbox when the agent runs code it wrote itself, and that code should execute in an isolated environment away from your server and its credentials.
Sandboxes for running code the model wrote, each in its own Firecracker microVM, started from the JavaScript SDK in a fraction of a second. The agent gets a tool that executes code and returns output, errors, and charts, which the chat interface can then render. The Hobby plan includes free credits and sessions up to an hour, and Pro is $150 a month.
Sandboxes that start in under 100 milliseconds and can stay alive with no time limit, driven from a TypeScript SDK with file, Git, and process APIs. Useful when the agent works on a project over many messages and needs the same environment each time. New accounts get $200 in compute credits, then billing is per second.
These are highlighted picks. To see all the tools, check the Agent Sandboxes & Code Execution category.
Model Aggregator Add-ons
Add a model aggregator when you want one API key and one bill for models from many providers, with automatic fallback when one of them is down, instead of setting up each provider separately.
One API key and one prepaid balance for hundreds of models, with a provider package for the AI SDK and an OpenAI-compatible endpoint for everything else. Useful for letting users pick a model in the interface, and for fallback when a provider is down. Models are billed at the providers' prices, with a 5.5% fee when you buy credits. On Vercel, the platform's own AI Gateway does a similar job.
An open-source gateway you host yourself between the app and the model providers. It gives one OpenAI-compatible endpoint, budgets and spend tracking per key, and fallback rules, under your own provider API keys. It is a separate service with its own PostgreSQL database, so it fits a container host or a team that already runs shared infrastructure more than a purely serverless deployment.
These are highlighted picks. To see all the tools, check the AI Model Aggregators category.
CI/CD Add-ons
Add CI/CD when you want a dedicated pipeline for running tests, linting, or multi-stage builds before a deploy goes out. Many hosting platforms already redeploy automatically on every push on their own — a CI/CD tool adds the most value on top of that by gating the deploy on a passing test suite, and matters even more when the hosting choice does not auto-deploy at all, such as a self-hosted server.
Runs type checks and tests on every push, and handles the deploy on hosts that don't deploy from Git on their own. For an agent the useful extra is an evaluation step: replay saved conversations against a changed prompt or model, and fail the build when the answers get worse.
These are highlighted picks. To see all the tools, check the CI/CD Pipelines category.
Containerization Add-ons
Add containerization when you want the app packaged the same way across local development, staging, and production, or need to deploy somewhere that isn't a managed serverless platform.
Packages the Next.js app as an image using its standalone output, which is how it deploys to a container host or to AWS. It isn't needed on Vercel, which builds from the repository. Docker Compose is also a simple way to run PostgreSQL next to the app during local development.
These are highlighted picks. To see all the tools, check the Containerization category.
Styling Add-ons
Add styling when you want a component or utility-class system to build the UI faster than hand-writing CSS from scratch.
A utility-class CSS framework composed directly in the markup, and the styling most Next.js projects start with. The AI SDK's prebuilt chat components, AI Elements, are styled with it, so adding it gives the chat interface a ready-made look to adjust instead of a blank page.
These are highlighted picks. To see all the tools, check the CSS Frameworks category.
Frequently Asked Questions about TypeScript AI Agent
Should I use the Vercel AI SDK, Mastra, or LangChain?
They sit at different heights. The AI SDK is the thinnest: model calls, tools, an agent loop, and chat hooks, with storage and memory left to you. That is the right start for a chat agent inside a Next.js app. Mastra adds memory, workflows, and evals as configuration and streams to the same chat hooks, so moving up to it later keeps the interface. LangChain.js is the choice when you want its graph runtime and PostgreSQL checkpointing, or when the team shares code and habits with a Python LangChain project. Changing framework later means rewriting the agent code, while the interface, the database, and the host carry over.
Can an agent run on serverless hosting, or do I need a server?
A chat-style agent runs fine on serverless. On Vercel a run can last up to 300 seconds on the Hobby plan and 800 seconds on Pro, and time spent waiting for the model is not billed as CPU. That covers most conversations where the agent takes a handful of steps. It stops fitting when a run takes many minutes, has to wait hours for a person's approval, or must survive a deploy. Then there are two routes: a durable workflow layer such as Vercel Workflows, which saves each step and resumes the run, or a container host such as Railway or Fly.io, where the app is a long-lived Node.js server.
What drives the model bill, and how do I keep it down?
Token spend is the line that grows, not hosting. In a chat product every new message resends the instructions, the tool definitions, and the conversation so far, so a long conversation costs more with each turn. Three things help most. Prompt caching, which Claude and OpenAI both discount heavily for repeated input. Sending simple jobs, such as titling a conversation, to a small model. And limiting how many steps a run may take and how much history goes with each message. If you add tracing with Langfuse or LangSmith, it shows what each conversation cost. The Pricing section has the per-token rates.
How is this different from the Python AI Agent stack?
The Python AI Agent stack is a backend: FastAPI serves the agent as an API, and any interface is a separate project. This stack puts the agent and its chat interface in one Next.js app, which is faster to ship when the product is a conversation in a browser. Python has the wider choice of agent frameworks and data libraries, and it is the better base for heavy retrieval, data analysis, or long-running background agents. TypeScript wins when the agent is a feature of a web product and the team already writes React. Both use PostgreSQL and the same models, so the choice is mostly about language and where the interface lives.
Can I keep this interface and write the agent in Python?
Yes. The Next.js app can stay as the interface while the agent runs in a separate Python service, which is the Python AI Agent stack behind this frontend. The chat hooks only need a response in the stream format they understand, and Pydantic AI can produce it from a FastAPI endpoint. You gain Python's wider choice of agent frameworks and data libraries, and you pay with a second codebase, a second deployment, and types that no longer flow from the tools to the components. It is worth it when the agent needs heavy retrieval, data analysis, or long background runs. For a chat assistant inside a web product, one TypeScript app is simpler.
Stacks Related to TypeScript AI Agent
Next.js + Payload CMS
ProjectNext.js app with Payload CMS as a code-first, developer-friendly content backend.
Hasura + Next.js
ProjectInstant GraphQL API over PostgreSQL with Hasura, consumed by Next.js: a data layer without the boilerplate.
Directus + Next.js
ProjectThe open-source backend platform on your own PostgreSQL or MySQL database, rendered by Next.js.
Next.js + PostgreSQL
ProjectNext.js with a PostgreSQL database, an ORM, and authentication: full-stack TypeScript web apps.
Scores
Popularity4/5
Next.js is the most used React framework and the Vercel AI SDK the most downloaded AI library in the JavaScript ecosystem, so this pairing is a common way to build agent products for the web. Agent development itself is still a specialised corner of web development.
Learning Curve3/5
A developer who already builds with Next.js and React gets a working chat agent quickly, because the default framework is a thin layer and the interface hooks are provided. What remains to learn is the agent side: tool design, prompts, message storage, and how to evaluate changes.
Flexibility4/5
The framework, the model, the database, and the host each swap independently, and the agent's logic is ordinary TypeScript. The interface layer is tied to Next.js and React, and the choice of agent frameworks is narrower than in Python.
Performance3/5
Response time is set by the model: each step waits on a model call. Streaming makes the interface feel responsive from the first token, and serverless cold starts add little next to model latency, but neither makes a multi-step run finish sooner.
Portability4/5
Every core piece is open source and runs on any host that runs Node.js, the model is reached through a provider-agnostic API, and the data is in plain PostgreSQL. Some conveniences, such as durable workflows and the model gateway, are tied to one hosting platform, and the agent code is written against one framework.
Tools in the TypeScript AI Agent Stack
Programming Languages
Add-ons (optional — add any, or none)
Authentication
Vector Db
Llm Observability
Code Sandbox
Model Aggregator
CI/CD
Containerization
Styling
TypeScript AI Agent Pricing
Next.js, the agent frameworks, and PostgreSQL are open source and free. Hosting starts free for a personal project and is about $20 a month per developer on a commercial plan, or $5 to $10 on a container host. A serverless PostgreSQL free plan covers a prototype. The model is the line that grows: mid-tier models cost $2 per million input tokens and $10 per million output, small models a tenth of that or less, and every message resends the conversation so far. Sign-in, tracing, sandboxes, and a vector database are optional and have free tiers.
Next.js, React, the Vercel AI SDK, Mastra, and LangChain are free to use.
About $2 per million input tokens and $10 per million output on mid-tier models; small models from $0.10 and $0.50. Usually the largest line.
Free for personal projects on a serverless platform and about $20 a month per developer for commercial use; a container host starts at $5 a month.
Serverless free plans cover a prototype; paid plans are usage-based or from $25 a month.