Blog · Claude API
Using the Claude API with Node.js: A Team Guide
Build Claude into a Node.js or TypeScript backend the way a team should: typed SDK usage, streaming to the browser, tool calling, secret management, and deployment-ready patterns.
If your product is a web application, there is a good chance the code that talks to Claude will live in a Node.js service — an API route, a backend-for-frontend, or a serverless function sitting between your React frontend and Anthropic’s Messages API. The official TypeScript SDK, @anthropic-ai/sdk, is built for exactly this: full type definitions, streaming helpers that map cleanly onto HTTP responses, and the same request shapes as the Python SDK, so knowledge transfers across your team.
This guide is written for teams rather than solo hackers: alongside the code, it covers the conventions — key handling, shared client modules, streaming architecture, and review practices — that keep a multi-developer Claude integration consistent and safe as it grows.
Setup and a Typed First Request
Install the SDK and set the key in your environment (or your platform’s secret store):
npm install @anthropic-ai/sdkimport Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic(); // reads ANTHROPIC_API_KEY
const msg = await client.messages.create({
model: "claude-sonnet-5",
max_tokens: 1024,
messages: [{ role: "user", content: "Summarize what an SDK is." }],
});
console.log(msg.content[0].type === "text" ? msg.content[0].text : "");Response content is a discriminated union — TypeScript will force you to narrow on block.type before reading .text, which is the compiler catching a real runtime hazard. Plain JavaScript projects use the same package; the types simply become editor hints. One team convention worth adopting immediately: construct the client once in a shared module and import it, rather than instantiating per request.
Never Call Claude from the Browser
The single most important architectural rule: the API key lives server-side, always. A key shipped in frontend JavaScript is public within minutes, and anyone holding it can spend your budget. The standard architecture is:
- Browser calls your backend endpoint (Express route, Next.js route handler, serverless function).
- Your backend authenticates the user, applies rate limits and input validation, then calls Claude with the server-held key.
- The response — streamed or complete — is relayed to the browser.
This proxy layer is also where team-level controls belong: per-user quotas, prompt-injection filtering on user input, logging with request IDs, and cost attribution by feature. Use distinct API keys per environment, store them in your platform’s secret manager, and rotate on any suspected exposure — practices we drill in corporate Claude AI training sessions.
Streaming to the Frontend
Claude streams via server-sent events, and the SDK wraps this in an async iterable that pairs naturally with a streaming HTTP response. An Express example relaying text deltas as SSE:
app.post("/api/chat", async (req, res) => {
res.setHeader("Content-Type", "text/event-stream");
const stream = client.messages.stream({
model: "claude-sonnet-5", max_tokens: 2048,
messages: req.body.messages,
});
stream.on("text", (delta) => res.write(`data: ${JSON.stringify(delta)}\n\n`));
const final = await stream.finalMessage();
res.end();
});Use finalMessage() to get the assembled message and usage counts — do not hand-wire event listeners into a Promise. The same pattern works in Next.js route handlers with web-standard ReadableStreams, and streaming is required behavior for large max_tokens values to avoid HTTP timeouts.
Tool Use: Letting Claude Call Your Functions
Tool use turns Claude from a text generator into an orchestrator of your backend: you define functions with JSON schemas, Claude decides when to call them, your code executes and returns results. The raw loop is: send tools with the request, watch for stop_reason: “tool_use”, execute each tool_use block, and send back matching tool_result blocks in a user message.
The SDK’s beta tool runner automates that loop — you pass tool definitions with attached run functions (plain JSON Schema or Zod) and it iterates until Claude finishes. Team guidelines that prevent pain later:
- Write tool descriptions that say when to call the tool, not just what it does.
- Validate every tool input server-side; model output is untrusted input.
- Gate destructive operations (sends, writes, deletes) behind explicit checks or human approval.
Team Conventions That Scale
Multi-developer Claude codebases stay healthy with a few enforced conventions:
- One client module: a single configured Anthropic instance exported from lib/claude.ts, so timeouts and retries are set in one place.
- Use SDK types: Anthropic.MessageParam, Anthropic.Tool, and friends — never redefine parallel interfaces.
- Prompts as reviewed artifacts: keep system prompts in versioned files with owners, not inline template literals scattered across handlers.
- Centralized model config: map task names to model IDs (claude-haiku-4-5 for cheap paths, claude-sonnet-5 default, claude-opus-4-8 for hard reasoning) so tier changes are one-line diffs — our model guide helps calibrate the mapping.
- A tiny eval script in CI: a handful of golden cases catches prompt and model regressions before deploy.
Production Readiness Checklist
Before the integration takes real traffic:
- Error handling: catch the SDK’s typed errors (RateLimitError, APIError) most-specific-first; the SDK already retries transient failures with backoff.
- Timeout awareness: the SDK timeout is in milliseconds — set explicit values on latency-sensitive routes, and remember serverless platforms impose their own execution limits on long streams.
- Cost telemetry: log usage (including cache-read tokens) per route into your metrics stack.
- Prompt caching: mark stable system prompts and tool definitions with cache breakpoints; verify hits via cache_read_input_tokens.
- Graceful degradation: decide per route what happens when Claude is slow or unavailable — queue, fallback tier, or honest error.
Teams that want to level up together — API, MCP, tool use, and agent patterns in one program — can run through our Claude API & MCP training.
Key takeaways
- Install @anthropic-ai/sdk, construct one shared client from an environment-held key, and let TypeScript's discriminated unions guard your response handling.
- Never expose the API key to the browser — every Claude call goes through your authenticated backend proxy.
- Stream with client.messages.stream() and finalMessage(); relay deltas to the frontend as SSE or a ReadableStream.
- Use the SDK tool runner for tool-calling loops, and treat every tool input as untrusted data requiring validation.
- Centralize model IDs and prompts in config so tier changes and prompt updates are reviewable one-line diffs.
- Ship with typed error handling, per-route usage logging, and prompt caching verified via cache_read_input_tokens.
FAQ
Questions
Can I use the Claude API directly from a React or browser app?
Technically discouraged and practically dangerous: your API key would be visible to anyone who opens dev tools. Always route requests through a backend you control — a Next.js route handler, Express endpoint, or serverless function — which holds the key, authenticates users, and relays streamed responses to the browser.
Does the TypeScript SDK work with plain JavaScript and with edge runtimes?
Yes. @anthropic-ai/sdk works in plain Node.js JavaScript — the type definitions simply become optional editor hints. It also runs in common serverless and edge environments; just watch platform execution limits when streaming long responses, and prefer web-standard streams where the runtime requires them.
How should a team manage Claude API keys across environments?
Use separate keys for development, staging, and production, stored in each platform’s secret manager rather than .env files in the repo. Scope spend limits per key in the Anthropic Console, restrict production key access to the deployment system, and rotate immediately on any suspected exposure.
Who delivers it
Anthropic-certified Claude trainers
Every programme is delivered by Anthropic Claude Certified trainers who use Claude daily on live client work — engineering, analysis, research and content. We have trained 200,000+ professionals across 20+ countries for 600+ enterprise clients, including Tata Group, Adani, Siemens, GE Aerospace, HUL, Flipkart and Air India.
- Anthropic Claude Certified trainers, not generalist AI speakers
- 200,000+ professionals trained across 20+ countries
- 600+ enterprise clients, from BFSI and manufacturing to public sector
- Delivered in English, Hindi and Hinglish
Trusted by
Teams we’ve trained
…and 200+ organisations, across 16+ countries.
What participants say
Real feedback from real sessions
Verified feedback collected from participants across corporate sessions — average rating 4.8/5.
“A very productive session for working professionals. A must-do.”
“The session was highly insightful and conducted in a very professional and interactive manner. Learnt about AI and excited to learn more!”
“Highly recommended! Hands-on and directly useful — from making PPTs and strategic plans to building KRAs.”
“Great work done by Mr Hitesh in the AI landscape — a true subject-matter expert. More power to him for spreading this knowledge.”
“I would recommend everyone to go through this session — it clarifies both what to expect from AI and where AI isn’t needed.”
“Amazing session by Hitesh. The AI tools he shared are very helpful for day-to-day work.”
“Mr Hitesh Motwani is a very informative trainer. The way he delivers training is awesome.”
“Mr Hitesh Motwani delivered a valuable, informative session and showed us exactly how to use AI tools to enhance our work. Thank you so much.”
“A nice interactive session with a lot of new insights and the power of AI. This will help me save time in routine activities.”
“A very good training session. AI can do wonders — we’ll implement it to create efficiency and save time.”
“Hitesh was very informative and knowledgeable about AI tools. It will let me use my time far more effectively.”
“Your session helped me walk into the world of magic.”
Explore more
Keep going with Claude AI training
Work with us
Bring Claude AI training to your team
Tell us your team, tools and goals and we will send a fixed proposal — usually within one business day.