{"id":"6b08c24c38c84264c202746e","slug":"ai-in-node","title":"AI in Node.js and TypeScript: the Anthropic SDK, Vercel AI SDK and LangChain.js in practice","summary":"A map of the AI ecosystem for Node.js – when the provider SDK is enough, when to use the Vercel AI SDK and when LangChain.js – plus streaming to the browser, tools, agents and structured data with Zod, with production notes.","servedLang":"en","availableLangs":["pl","en"],"topics":["ai-in-node","tool-use","ai-agents","mcp"],"techs":["typescript","node","javascript"],"tags":["nodejs","typescript","vercel-ai-sdk","langchainjs","anthropic-sdk","streaming","zod","claude"],"level":"intermediate","kind":"article","access":"members","status":"published","cover":null,"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"readingMinutes":13,"stats":{"views":2,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-26T23:35:40.570Z","updatedAt":"2026-11-27T13:08:15.540Z","requestedLang":"en","theme":{"hero":"classic","heroMedia":null,"accent":"rose","background":"hex","weaveResources":true,"toc":"right"},"seoDescription":"AI in Node.js and TypeScript: the Anthropic SDK, Vercel AI SDK (streamText, tools, Output), LangChain.js (createAgent), MCP, SSE streaming in Express and Next.js, Zod, aborting generation, limits, costs and testing.","wordCount":2446,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Node.js is a natural home for AI features in web applications: the same language on the front end and back end, excellent support for streams and asynchrony, and a rich library ecosystem on top. The choice is wide, though – from the provider's official SDK, through the "},{"type":"text","text":"Vercel AI SDK","marks":[{"type":"bold"}]},{"type":"text","text":", to "},{"type":"text","text":"LangChain.js","marks":[{"type":"bold"}]},{"type":"text","text":" – and it is easy to add an abstraction layer you do not need. This article shows the same tasks in three approaches so you can choose deliberately."}]},{"type":"stats","attrs":{"items":[{"value":"3","label":"levels of abstraction","hint":"provider SDK, Vercel AI SDK, LangChain.js"},{"value":"1","label":"Zod schema","hint":"validates tools, outputs and requests from the browser"},{"value":"0","label":"API keys in the browser","hint":"model calls always go through your backend"}]}},{"type":"callout","attrs":{"variant":"info","title":"TL;DR"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"The "},{"type":"text","text":"provider SDK","marks":[{"type":"bold"}]},{"type":"text","text":" ("},{"type":"text","text":"@anthropic-ai/sdk","marks":[{"type":"code"}]},{"type":"text","text":") gives full access to model features with the least magic; the "},{"type":"text","text":"Vercel AI SDK","marks":[{"type":"bold"}]},{"type":"text","text":" unifies providers and integrates streaming with the UI very well; "},{"type":"text","text":"LangChain.js","marks":[{"type":"bold"}]},{"type":"text","text":" adds ready-made agents, middleware and integrations."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Stream responses (SSE), abort generation when the client disconnects, and validate input from the browser before you pay for tokens."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Zod is the common language: it describes "},{"type":"text","text":"tool","marks":[{"type":"link","attrs":{"href":"/en/topics/tool-use"}}]},{"type":"text","text":" arguments, structured responses and API contracts – fully typed in TypeScript."}]}]}]}]},{"type":"heading","attrs":{"level":2,"id":"the-problem-a-chat-added-quickly"},"content":[{"type":"text","text":"The problem: a chat added \"quickly\""}]},{"type":"paragraph","content":[{"type":"text","text":"The pierogi ordering app is Next.js on the front end and an Express API. The first version of the chat took an afternoon: the front end called the model API directly from the browser (the key in a "},{"type":"text","text":"NEXT_PUBLIC_…","marks":[{"type":"code"}]},{"type":"text","text":" variable), waited a dozen seconds for the full answer and pulled order data out of the text with regular expressions. Within a week the key leaked through the browser's developer tools, users closed the tab before anything appeared (while generation kept running – and costing), and the parser fell over on \"two ruskie and one with cabbage\"."}]},{"type":"paragraph","content":[{"type":"text","text":"Each of these problems has a ready solution in the Node ecosystem. You just need to know which layer to use."}]},{"type":"heading","attrs":{"level":2,"id":"the-ecosystem-map"},"content":[{"type":"text","text":"The ecosystem map"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Library"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"What it gives you"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"When to choose it"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"@anthropic-ai/sdk","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"the official Claude SDK: Messages API, streaming, tool runner, structured outputs, caching, batches, types"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"you want full control and access to all features of one provider"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"ai","marks":[{"type":"code"}]},{"type":"text","text":" + "},{"type":"text","text":"@ai-sdk/anthropic","marks":[{"type":"code"}]},{"type":"text","text":" (Vercel AI SDK)"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"one interface for many providers, "},{"type":"text","text":"streamText","marks":[{"type":"code"}]},{"type":"text","text":"/"},{"type":"text","text":"generateText","marks":[{"type":"code"}]},{"type":"text","text":", tools, "},{"type":"text","text":"Output","marks":[{"type":"code"}]},{"type":"text","text":", UI hooks ("},{"type":"text","text":"useChat","marks":[{"type":"code"}]},{"type":"text","text":")"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"a web app with streaming to the UI, a need to switch providers"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"langchain","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"@langchain/anthropic","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"agents ("},{"type":"text","text":"createAgent","marks":[{"type":"code"}]},{"type":"text","text":"), middleware (e.g. human-in-the-loop, summarization), integrations with vector stores and loaders"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"complex flows, RAG over many sources, ready-made agent patterns"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"@modelcontextprotocol/sdk","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"MCP","marks":[{"type":"link","attrs":{"href":"/en/topics/mcp"}}]},{"type":"text","text":" servers and clients"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"exposing tools to many AI applications"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"openai","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"the OpenAI SDK, also for APIs compatible with it"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"OpenAI models or local servers compatible with that API"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"@huggingface/transformers","marks":[{"type":"code"}]},{"type":"text","text":" (Transformers.js)"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"models running locally in Node or the browser (ONNX)"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"embeddings and small models without sending data out"}]}]}]}]},{"type":"diagram","attrs":{"kind":"mermaid","code":"flowchart TB\n  B[\"Browser<br/>useChat() / EventSource\"] -->|\"POST /api/chat\"| R[\"Node backend<br/>Next.js route or Express\"]\n  R -->|\"Zod validation, limits, session\"| S[\"SDK: Anthropic / AI SDK / LangChain.js\"]\n  S -->|\"HTTPS, key from secrets\"| M[\"Claude API\"]\n  S -->|\"tool calls\"| T[\"Order service<br/>(authorization from the session)\"]\n  S -->|\"MCP\"| P[\"MCP servers\"]\n  M -->|\"token stream\"| R\n  R -->|\"SSE\"| B","caption":"A typical architecture: the browser talks to your backend, and only the backend talks to the model and tools"}},{"type":"heading","attrs":{"level":2,"id":"streaming-to-the-browser"},"content":[{"type":"text","text":"Streaming to the browser"}]},{"type":"paragraph","content":[{"type":"text","text":"A model's answer is produced token by token, so the user should see it from the first token. In plain Express you stream SSE events from the Anthropic SDK; in Next.js with the Vercel AI SDK one line ("},{"type":"text","text":"toUIMessageStreamResponse()","marks":[{"type":"code"}]},{"type":"text","text":") returns a stream in the format the client-side "},{"type":"text","text":"useChat","marks":[{"type":"code"}]},{"type":"text","text":" hook understands."}]},{"type":"codeGroup","attrs":{"title":"Chat with streaming: Express + Anthropic SDK and Next.js + AI SDK"},"content":[{"type":"codeBlock","attrs":{"language":"typescript","filename":"server.ts"},"content":[{"type":"text","text":"// npm i @anthropic-ai/sdk express zod\nimport Anthropic from \"@anthropic-ai/sdk\";\nimport express from \"express\";\nimport { z } from \"zod\";\n\nconst app = express();\napp.use(express.json({ limit: \"100kb\" }));\nconst client = new Anthropic(); // the API key stays on the server - never in the browser\n\nconst ChatRequest = z.object({\n  messages: z\n    .array(z.object({ role: z.enum([\"user\", \"assistant\"]), content: z.string().max(4000) }))\n    .min(1)\n    .max(40),\n});\n\napp.post(\"/api/chat\", async (req, res) => {\n  const parsed = ChatRequest.safeParse(req.body); // untrusted input: validate before paying for tokens\n  if (!parsed.success) return void res.status(400).json({ error: \"invalid_request\" });\n\n  res.setHeader(\"Content-Type\", \"text/event-stream\");\n  res.setHeader(\"Cache-Control\", \"no-cache\");\n\n  const stream = client.messages.stream({\n    model: \"claude-opus-5-5\",\n    max_tokens: 64000,\n    system: \"You are the ordering assistant of Halina's Pierogi. Answer briefly.\",\n    messages: parsed.data.messages,\n  });\n  // Stop generating (and paying) when the browser goes away.\n  res.on(\"close\", () => {\n    if (!res.writableFinished) stream.abort();\n  });\n  stream.on(\"text\", (delta) => res.write(`data: ${JSON.stringify({ delta })}\\n\\n`));\n\n  try {\n    const final = await stream.finalMessage();\n    res.write(`data: ${JSON.stringify({ done: true, stop: final.stop_reason, usage: final.usage })}\\n\\n`);\n  } catch (err) {\n    if (!stream.aborted) res.write(`data: ${JSON.stringify({ error: \"generation_failed\" })}\\n\\n`);\n  } finally {\n    res.end();\n  }\n});\n\napp.listen(3000, () => console.log(\"Chat API on http://localhost:3000\"));"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"app/api/chat/route.ts"},"content":[{"type":"text","text":"// Next.js App Router + Vercel AI SDK: npm i ai @ai-sdk/anthropic\nimport { anthropic } from \"@ai-sdk/anthropic\";\nimport { convertToModelMessages, streamText, type UIMessage } from \"ai\";\n\nexport const maxDuration = 60; // seconds - long answers need more than the default serverless limit\n\nexport async function POST(req: Request) {\n  const { messages }: { messages: UIMessage[] } = await req.json();\n\n  const result = streamText({\n    model: anthropic(\"claude-opus-5-5\"),\n    system: \"You are the ordering assistant of Halina's Pierogi. Answer briefly.\",\n    messages: await convertToModelMessages(messages),\n    abortSignal: req.signal, // client disconnects -> generation stops\n    onFinish: ({ usage }) => console.log(\"tokens\", usage.inputTokens, usage.outputTokens),\n  });\n\n  // A stream format understood by the useChat() hook from @ai-sdk/react.\n  return result.toUIMessageStreamResponse();\n}"}]}]}]},"toc":[{"id":"the-problem-a-chat-added-quickly","text":"The problem: a chat added \"quickly\"","level":2,"locked":false},{"id":"the-ecosystem-map","text":"The ecosystem map","level":2,"locked":false},{"id":"streaming-to-the-browser","text":"Streaming to the browser","level":2,"locked":false},{"id":"tools-and-agents","text":"Tools and agents","level":2,"locked":true},{"id":"structured-data-with-zod","text":"Structured data with Zod","level":2,"locked":true},{"id":"which-library-to-choose","text":"Which library to choose","level":2,"locked":true},{"id":"production-what-not-to-forget","text":"Production: what not to forget","level":2,"locked":true},{"id":"checklist","text":"Checklist","level":2,"locked":true},{"id":"test-yourself","text":"Test yourself","level":2,"locked":true},{"id":"what-s-next","text":"What's next","level":2,"locked":true}],"locked":true,"paywall":null,"previewRatio":0.3,"totalBlocks":43,"visibleBlocks":12,"resources":[{"id":"6b0857bf3c96f2d34d0b425d","type":"article","provider":"web","url":"https://ai-sdk.dev/docs/introduction","embedUrl":null,"title":"AI SDK by Vercel | AI SDK","description":"The AI SDK is the TypeScript toolkit for building AI applications and agents with React, Next.js, Vue, Svelte, Node.js, and more.","author":"Vercel","thumbnailUrl":"https://ai-sdk.dev/og/introduction/image.png","durationSec":null,"lang":"en","topics":["ai-in-node"],"techs":["node","javascript","typescript"],"tags":["ai"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":null,"popularity":65,"verifiedAt":"2026-11-26T11:25:52.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:02.417Z","updatedAt":"2026-11-26T16:01:02.417Z"},{"id":"6b0857a93c96f2d34d0b324f","type":"repo","provider":"github","url":"https://github.com/vercel/ai","embedUrl":null,"title":"vercel/ai","description":"The AI Toolkit for TypeScript, from the creators of Next.js.","author":"vercel","thumbnailUrl":"https://opengraph.githubassets.com/1/vercel/ai","durationSec":null,"lang":"en","topics":["ai-in-node"],"techs":["typescript"],"tags":[],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"seed","publishedAt":null,"popularity":89,"verifiedAt":"2026-11-26T00:00:00.000Z","curated":true,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:41.718Z","updatedAt":"2026-11-26T16:00:41.718Z"},{"id":"6b0857b23c96f2d34d0b344d","type":"repo","provider":"github","url":"https://github.com/langchain-ai/langchainjs","embedUrl":null,"title":"langchain-ai/langchainjs","description":"The agent engineering platform","author":"langchain-ai","thumbnailUrl":"https://opengraph.githubassets.com/1/langchain-ai/langchainjs","durationSec":null,"lang":"en","topics":["ai-in-node"],"techs":["node","typescript"],"tags":["ai"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"github","publishedAt":"2023-02-06T22:50:27.000Z","popularity":82,"verifiedAt":"2026-11-26T10:55:56.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:49.541Z","updatedAt":"2026-11-26T16:00:49.541Z"},{"id":"6b0857ca3c96f2d34d0b4b7a","type":"video","provider":"youtube","url":"https://www.youtube.com/watch?v=WLBrpwYSCjQ","embedUrl":"https://www.youtube-nocookie.com/embed/WLBrpwYSCjQ","title":"AI Dev 25 x NYC | Aayush Kapoor: Vercel AI SDK: From Fundamentals to Deep Research","description":"Aayush Kapoor, Software Engineer on the AI SDK team at Vercel, shared during AI Dev 25 x NYC how to build production-ready agents with the Vercel AI SDK. He covered fundamentals like text generation, tool and function calling, structured outputs, and swapping models with a single line, then code a…","author":"DeepLearningAI","thumbnailUrl":"https://i.ytimg.com/vi/WLBrpwYSCjQ/hqdefault.jpg","durationSec":null,"lang":"en","topics":["ai-in-node"],"techs":["node","javascript"],"tags":["ai"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"youtube-rss","publishedAt":"2025-12-02T21:51:13.000Z","popularity":49,"verifiedAt":"2026-11-26T10:58:13.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:12.872Z","updatedAt":"2026-11-26T16:01:12.872Z"},{"id":"6b0857b23c96f2d34d0b345f","type":"repo","provider":"github","url":"https://github.com/huggingface/transformers.js","embedUrl":null,"title":"huggingface/transformers.js","description":"State-of-the-art Machine Learning for the web. Run 🤗 Transformers directly in your browser, with no need for a server!","author":"huggingface","thumbnailUrl":"https://opengraph.githubassets.com/1/huggingface/transformers.js","durationSec":null,"lang":"en","topics":["llm-fundamentals","ai-in-node"],"techs":["javascript"],"tags":["browser","javascript","transformers","webml","machine-learning","ai"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"github","publishedAt":"2023-02-13T13:51:45.000Z","popularity":81,"verifiedAt":"2026-11-26T11:01:30.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:49.541Z","updatedAt":"2026-11-26T16:00:49.541Z"},{"id":"6b0857b23c96f2d34d0b3415","type":"repo","provider":"github","url":"https://github.com/mastra-ai/mastra","embedUrl":null,"title":"mastra-ai/mastra","description":"Mastra is the modern TypeScript framework for AI-powered applications and agents.","author":"mastra-ai","thumbnailUrl":"https://opengraph.githubassets.com/1/mastra-ai/mastra","durationSec":null,"lang":"en","topics":["evals","ai-agents","ai-in-node","mcp"],"techs":["node","javascript","typescript"],"tags":["agents","ai","chatbots","evals","javascript","llm","mcp","nextjs","nodejs","reactjs"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"github","publishedAt":"2024-08-06T20:44:31.000Z","popularity":86,"verifiedAt":"2026-11-26T11:00:38.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:49.541Z","updatedAt":"2026-11-26T16:00:49.541Z"}],"challenges":[],"attachments":[],"hasCode":true,"repoUrl":null,"series":[],"prev":null,"next":null,"featured":false,"authorCard":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","headline":"Wzorce projektowe · Architektura · AI i LLM","community":false,"reputation":{"points":3900,"level":{"key":"mentor","label":"Mentor"}},"articles":68,"skills":[{"key":"typescript","title":"TypeScript","level":5,"levelLabel":"Authority","articles":63},{"key":"dotnet","title":".NET","level":5,"levelLabel":"Authority","articles":53},{"key":"python","title":"Python","level":5,"levelLabel":"Authority","articles":52},{"key":"java","title":"Java","level":5,"levelLabel":"Authority","articles":38}]}}