Anthropic Claude API SDK for Node.js & TypeScript
Anthropic ships an official @anthropic-ai/sdk package for Node.js and TypeScript. It wraps the Claude API in a typed client, handles request signing and retries, and gives you first-class types for messages, streaming events, and tool calls. If you're building a backend, CLI, or Next.js API route in TypeScript, this is the fastest path from zero to a working Claude integration.
This article covers installing and configuring the SDK, typing requests and responses correctly, streaming tokens, handling tool use, and dealing with errors and rate limits — the parts that trip people up when moving from a quick curl test to production TypeScript code.
Installing the SDK
npm install @anthropic-ai/sdk
The package ships its own TypeScript types, so there's no need for @types/.... Instantiate the client with your API key, ideally from an environment variable:
import Anthropic from "@anthropic-ai/sdk";
const anthropic = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
});
If you're using ESM ("type": "module" in package.json) the import above works as-is. For CommonJS, use const Anthropic = require("@anthropic-ai/sdk").default;.
A typed message request
The SDK exposes Message, MessageParam, and ContentBlock types, which makes it easy to build strongly typed chat functions instead of passing loosely shaped objects around:
import Anthropic, { Anthropic as AnthropicTypes } from "@anthropic-ai/sdk";
const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
async function askClaude(prompt: string): Promise<string> {
const message = await anthropic.messages.create({
model: "claude-opus-4-20250514",
max_tokens: 1024,
messages: [
{ role: "user", content: prompt } satisfies AnthropicTypes.MessageParam,
],
});
const textBlock = message.content.find((b) => b.type === "text");
return textBlock ? textBlock.text : "";
}
The content field on a Message is an array of typed blocks (text, tool_use, etc.), so TypeScript will flag it if you try to access .text without narrowing the type first — which is exactly what you want when a response might contain a tool call instead of plain text.
Streaming responses
For chat UIs or CLI tools, streaming avoids the "wait for the whole answer" feel. The SDK supports this with messages.stream(), which returns an async iterator of typed events:
const stream = anthropic.messages.stream({
model: "claude-opus-4-20250514",
max_tokens: 1024,
messages: [{ role: "user", content: "Explain event loops in Node.js" }],
});
stream.on("text", (text) => {
process.stdout.write(text);
});
const finalMessage = await stream.finalMessage();
console.log("\n\nUsage:", finalMessage.usage);
This pattern is useful locally, but if you're exposing streaming to a browser frontend, you generally want a backend endpoint that proxies and forwards Server-Sent Events rather than giving the client your API key directly.
Tool use with typed schemas
Claude's tool use (function calling) lets the model request a function call instead of returning plain text. In TypeScript you define the tool schema and handle the tool_use content block:
const response = await anthropic.messages.create({
model: "claude-opus-4-20250514",
max_tokens: 1024,
tools: [
{
name: "get_weather",
description: "Get current weather for a city",
input_schema: {
type: "object",
properties: {
city: { type: "string" },
},
required: ["city"],
},
},
],
messages: [{ role: "user", content: "What's the weather in Lisbon?" }],
});
const toolUse = response.content.find((b) => b.type === "tool_use");
if (toolUse && toolUse.type === "tool_use") {
console.log(toolUse.name, toolUse.input);
}
Narrowing with b.type === "tool_use" is required because content is a union type — TypeScript won't let you read .name or .input otherwise. This is a common source of confusion for developers new to the SDK's type system, but it's also what catches bugs before runtime.
Error handling and retries
The SDK throws typed errors (Anthropic.APIError, Anthropic.RateLimitError, Anthropic.AuthenticationError) that you can catch specifically:
try {
await anthropic.messages.create({ /* ... */ });
} catch (err) {
if (err instanceof Anthropic.RateLimitError) {
console.warn("Rate limited, backing off");
} else if (err instanceof Anthropic.APIError) {
console.error(err.status, err.message);
} else {
throw err;
}
}
By default the client retries on transient failures with exponential backoff. You can tune this with maxRetries and timeout options on the Anthropic constructor if your use case needs faster fail-over or longer timeouts for long completions.
When raw SDK access isn't enough
The official SDK is the right tool when you control the backend and just need Claude calls inside your own Node.js service. But teams often hit three gaps once they move past a prototype:
- Multiple consumers, one Claude plan. If several apps or team members need API access, sharing one
ANTHROPIC_API_KEYmeans no per-app visibility or revocation. - No built-in usage dashboard. The SDK gives you token counts per response, but aggregating spend across apps and teammates means building that yourself.
- Team and billing structure. Seats, per-key limits, and spend tracking aren't part of the SDK — they're infrastructure you'd otherwise build on top of it.
SubToAPI sits on top of your existing Claude access and exposes it as a standard HTTPS API with its own scoped keys (sub_live_...), so each app or teammate gets a separate key while usage and billing stay centralized. The request/response shape matches what you'd expect from the Anthropic Messages API, so switching the baseURL in the SDK config (or just using fetch/curl against https://api.subtoapi.app/v1/messages) is usually enough:
curl https://api.subtoapi.app/v1/messages \
-H "Authorization: Bearer $SUBTOAPI_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-opus-4-20250514",
"max_tokens": 1024,
"messages": [{"role": "user", "content": "Summarize this in one sentence."}]
}'
Streaming and tool use work the same way as the native SDK — see /docs/streaming and /docs/tools for details. If you're deciding between a raw SDK integration and a managed layer, the quickstart and Messages API reference are the fastest way to compare the request shape directly. Plans start at €9/month for solo use, with team and scale tiers at /pricing for shared access.
Picking the right approach
If you're a solo developer building a single app, the official @anthropic-ai/sdk with TypeScript is the simplest and most direct path — no extra layer, no extra cost. If you're distributing Claude access across multiple apps, environments, or teammates and want per-key usage tracking without building it yourself, a managed API key layer like SubToAPI removes that overhead while keeping the same request format you already know.
FAQ
Does the Anthropic SDK support TypeScript out of the box? Yes. @anthropic-ai/sdk is written in TypeScript and ships its own type definitions, including typed request params, response content blocks, and streaming events — no separate @types package needed.
How do I stream Claude responses in Node.js? Use anthropic.messages.stream(), which returns an async event emitter you can listen to with .on("text", ...), then call .finalMessage() to get the completed message object with usage data.
Can I use the same SDK code against a different base URL, like SubToAPI? Yes, as long as the endpoint implements a compatible Messages API shape. Point your HTTP client or SDK config at https://api.subtoapi.app/v1/ with a sub_live_... key — see /docs/quickstart for the exact setup.