Claude API TypeScript SDK Setup Guide
Claude API TypeScript SDK Setup Guide
If you're building a TypeScript backend or Node.js service that talks to Claude, you have two practical paths: install Anthropic's official @anthropic-ai/sdk package and manage your own API key, or point your existing HTTP client at a compatible gateway that gives you application-level keys, usage metadata, and team billing out of the box. This guide covers the former in detail — package install, client setup, types, streaming, and tool use — and shows where a service like SubToAPI fits if you need more than a single developer key.
By the end you'll have a working TypeScript project that sends typed requests to Claude, handles streaming responses, and fails gracefully when something goes wrong.
Installing the SDK
Start with a clean Node project (Node 18+ recommended for native fetch support):
mkdir claude-ts-demo && cd claude-ts-demo
npm init -y
npm install @anthropic-ai/sdk
npm install -D typescript tsx @types/node
npx tsc --init
In tsconfig.json, make sure you're targeting ES2020 or later and have esModuleInterop enabled — the SDK ships ESM-friendly builds but plays well with CommonJS too:
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"esModuleInterop": true,
"strict": true,
"skipLibCheck": true
}
}
Basic client setup
Create a client instance once and reuse it across your app. Never hardcode keys — load them from environment variables:
import Anthropic from "@anthropic-ai/sdk";
const anthropic = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
});
async function main() {
const message = await anthropic.messages.create({
model: "claude-opus-4-20250514",
max_tokens: 1024,
messages: [{ role: "user", content: "Explain promises in two sentences." }],
});
console.log(message.content);
}
main();
Run it with npx tsx index.ts. The SDK's TypeScript types cover the full Message, ContentBlock, and error shapes, so your editor will autocomplete fields like message.usage.input_tokens without extra typings.
Typing requests and responses properly
One advantage of the TypeScript SDK over raw fetch calls is that request and response shapes are strongly typed. Define your own wrapper types when you need to pass structured data through your app:
import type { MessageParam, Tool } from "@anthropic-ai/sdk/resources/messages";
interface ChatTurn {
role: "user" | "assistant";
content: string;
}
function toMessageParams(turns: ChatTurn[]): MessageParam[] {
return turns.map((t) => ({ role: t.role, content: t.content }));
}
This keeps your conversation state decoupled from the SDK's internal types while still being type-safe at the boundary.
Streaming responses
For chat UIs or long completions, streaming is essential. The SDK exposes a .stream() helper that returns an async iterator of events:
async function streamReply(prompt: string) {
const stream = anthropic.messages.stream({
model: "claude-sonnet-4-20250514",
max_tokens: 1024,
messages: [{ role: "user", content: prompt }],
});
for await (const event of stream) {
if (event.type === "content_block_delta" && event.delta.type === "text_delta") {
process.stdout.write(event.delta.text);
}
}
const final = await stream.finalMessage();
console.log("\n---\nUsage:", final.usage);
}
This pattern works identically whether you're writing to a terminal, piping into a WebSocket, or forwarding chunks to a frontend via Server-Sent Events.
Tool use with typed schemas
Claude's tool use (function calling) lets the model request structured actions from your code. Define tools with JSON Schema and TypeScript will check your handler logic against the response shape:
const tools: Tool[] = [
{
name: "get_weather",
description: "Get current weather for a city",
input_schema: {
type: "object",
properties: { city: { type: "string" } },
required: ["city"],
},
},
];
const response = await anthropic.messages.create({
model: "claude-opus-4-20250514",
max_tokens: 1024,
tools,
messages: [{ role: "user", content: "What's the weather in Lisbon?" }],
});
for (const block of response.content) {
if (block.type === "tool_use") {
console.log("Tool requested:", block.name, block.input);
}
}
The block.input field is typed as unknown by design since it depends on your schema — validate it with zod or a manual type guard before using it.
Error handling
Wrap calls in try/catch and check error.status — the SDK throws typed APIError subclasses for rate limits, auth failures, and overloaded responses:
import { APIError } from "@anthropic-ai/sdk";
try {
await anthropic.messages.create({ /* ... */ });
} catch (err) {
if (err instanceof APIError) {
console.error(`Claude API error ${err.status}: ${err.message}`);
} else {
throw err;
}
}
Add retry logic with exponential backoff for 429 and 529 responses in production — the SDK does basic retries internally, but explicit handling gives you visibility into failures.
When one API key isn't enough
The official SDK is built around a single API key tied to one account. That's fine for a solo project, but it breaks down once you have multiple apps, environments, or team members needing separate, revocable credentials with their own usage tracking. This is the gap SubToAPI fills: it turns your existing Claude access into application-scoped keys (sub_live_...) that work with the same request shapes — messages, streaming, tool use — so your TypeScript code barely changes.
const response = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "claude-opus-4-20250514",
max_tokens: 1024,
messages: [{ role: "user", content: "Summarize this ticket." }],
}),
});
You get per-key usage metadata, streaming support, and team seats across Solo, Team, and Scale plans, which matters once you're shipping Claude features to multiple projects instead of running a single script. Check /docs/quickstart for setup, /docs/messages and /docs/streaming for request formats, and /docs/tools if you're using function calling through the gateway.
Wrapping up
Setting up the Claude API TypeScript SDK is a five-minute job: install the package, instantiate a client with an environment-variable key, and start sending typed messages.create calls. The types cover streaming, tool use, and error handling well enough that you rarely need to write raw HTTP code. Once your usage grows past a single key and a single developer, layering a key-management service like SubToAPI on top keeps the same code paths while adding the operational controls — distinct keys per app, shared billing, team seats — that the base SDK doesn't provide. Start with /pricing if you want to compare plans, or /signup to get a key in a few minutes.
questions
Do I need the official SDK, or can I just use fetch? fetch works fine for simple scripts, but the SDK gives you typed request/response objects, built-in streaming helpers, and typed error classes, which save real time in larger TypeScript codebases.
Which Node version do I need for the Claude TypeScript SDK? Node 18 or later is recommended since the SDK relies on native fetch and modern async iterator support for streaming; older versions require polyfills.
Can I use the same TypeScript code with SubToAPI instead of a raw Anthropic key? Yes — SubToAPI's /v1/messages endpoint mirrors the standard request format, so you can swap your base URL and key with minimal code changes; see /docs/quickstart for details.