Claude API JavaScript Examples (2026)

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.

🔥 Launch tonight — Power Prompts PDF 50p (just 50p tonight)30 battle-tested Claude Code prompts · 8 pages · paste into CLAUDE.md · price reverts to £5

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.

Install

npm install @anthropic-ai/sdk

Or with Bun: bun add @anthropic-ai/sdk

First message

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);

With a system prompt

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?" }]
});

Streaming responses

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();

Tool use (function calling)

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);
}

Prompt caching (cut costs 90%)

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.

Counting tokens before a request

const count = await client.messages.countTokens({
  model: "claude-sonnet-4-6",
  messages: [{ role: "user", content: myPrompt }]
});
console.log("Input tokens:", count.input_tokens);

Error handling

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 */ }
  }
}

Useful links

Frequently asked questions

Which npm package is the official Anthropic JavaScript SDK?
@anthropic-ai/sdk. Install with: npm install @anthropic-ai/sdk. It supports TypeScript natively with full type definitions.
Does the Anthropic JavaScript SDK work in the browser?
The SDK is primarily designed for Node.js server-side use. Calling the Claude API directly from a browser exposes your API key to users — proxy requests through a server-side endpoint instead.
How do I stream Claude responses in JavaScript?
Use client.messages.stream() and iterate with for await (const event of stream). Filter for content_block_delta events where delta.type === 'text_delta' to extract each token as it arrives.
What Node.js version does @anthropic-ai/sdk require?
Node.js 18 or later. Node 18 introduced the native fetch API which the SDK depends on. Bun and Deno are also supported.

Free tools

Cost Calculator → Prompt-Pricing Recommender → Diff Summarizer → Skills Browser →

Related

Claude Opus 4.7 vs Sonnet 4.6 Pricing (2026 Comparison)How Much Does Claude Cost? (2026 API Pricing Guide)Claude Prompt Caching: 90% Cost Savings Explained (2026)Claude API Cost Calculator: Estimate Your Anthropic BillClaude vs GPT-4 Pricing: 2026 API Cost Comparison