Complete guide to using the Claude API with JavaScript in 2026. Node.js quickstart, streaming, tool use, and prompt caching code examples using the official Anthropic SDK.
The official Anthropic JavaScript/TypeScript SDK (@anthropic-ai/sdk) works in Node.js 18+, Deno, and modern bundlers. This guide covers the most common patterns from a single message to streaming tool use.
npm install @anthropic-ai/sdk
Or with Bun: bun add @anthropic-ai/sdk
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic(); // reads ANTHROPIC_API_KEY from env
const message = await client.messages.create({
model: "claude-sonnet-4-6",
max_tokens: 1024,
messages: [{ role: "user", content: "Explain async/await in JavaScript." }]
});
console.log(message.content[0].text);
const message = await client.messages.create({
model: "claude-sonnet-4-6",
max_tokens: 1024,
system: "You are a concise JavaScript expert. Reply in under 100 words.",
messages: [{ role: "user", content: "When should I use WeakRef?" }]
});
const stream = client.messages.stream({
model: "claude-sonnet-4-6",
max_tokens: 1024,
messages: [{ role: "user", content: "Write a quicksort in JS." }]
});
for await (const event of stream) {
if (event.type === "content_block_delta" && event.delta.type === "text_delta") {
process.stdout.write(event.delta.text);
}
}
await stream.finalMessage();
const tools = [
{
name: "get_weather",
description: "Returns current temperature for a city.",
input_schema: {
type: "object",
properties: { city: { type: "string", description: "City name" } },
required: ["city"]
}
}
];
const response = await client.messages.create({
model: "claude-sonnet-4-6",
max_tokens: 512,
tools,
messages: [{ role: "user", content: "What is the weather in Tokyo?" }]
});
if (response.stop_reason === "tool_use") {
const toolUse = response.content.find(b => b.type === "tool_use");
console.log("Tool called:", toolUse.name, toolUse.input);
}
const response = await client.messages.create({
model: "claude-sonnet-4-6",
max_tokens: 512,
system: [
{
type: "text",
text: "You are an expert on the Node.js docs. " + nodeDocs, // large static context
cache_control: { type: "ephemeral" }
}
],
messages: [{ role: "user", content: "How do I use the crypto module?" }]
});
The first call writes the cache; subsequent calls within 5 minutes read at 90% off. See the Claude Cost Calculator to model your savings.
const count = await client.messages.countTokens({
model: "claude-sonnet-4-6",
messages: [{ role: "user", content: myPrompt }]
});
console.log("Input tokens:", count.input_tokens);
import { APIError } from "@anthropic-ai/sdk";
try {
const response = await client.messages.create({ /* ... */ });
} catch (err) {
if (err instanceof APIError) {
console.error(err.status, err.message); // 429, 500, etc.
if (err.status === 429) { /* back off and retry */ }
}
}