Using the JavaScript SDK
The @anthropic-ai/sdk package wraps the API in a clean client for Node and TypeScript.
Rather than building HTTP requests by hand, most web developers use the official SDK. The JavaScript/TypeScript package is @anthropic-ai/sdk; the Python package is anthropic.
What the SDK gives you
- A client that reads your API key from the environment.
- Typed methods like
messages.create. - Automatic retries, streaming helpers, and error classes.
The basic shape
You create one client and reuse it. Each call passes the same fields you would send over HTTP: model, max_tokens, and messages.
Example
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic(); // reads ANTHROPIC_API_KEY
async function ask(question) {
const response = await client.messages.create({
model: "claude-opus-4-8",
max_tokens: 1024,
messages: [{ role: "user", content: question }],
});
const text = response.content.find((b) => b.type === "text");
return text ? text.text : "";
}
console.log(await ask("Give me three CSS layout tips."));When to use it
- Replace manual fetch calls in your Node backend with the SDK to get automatic retries and typed responses.
- Use the TypeScript SDK in a Next.js API route for full type-safety on the request and response objects.
- Import the SDK into a build script that generates static content at deploy time using Claude.
More examples
Install the SDK and make a call
Adds the official package; the SDK reads ANTHROPIC_API_KEY from the environment automatically.
npm install @anthropic-ai/sdkBasic SDK usage in Node/TypeScript
Creates a client instance and calls messages.create — the primary SDK method for all completions.
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic(); // key from ANTHROPIC_API_KEY
const msg = await client.messages.create({
model: "claude-haiku-4-5",
max_tokens: 128,
messages: [{ role: "user", content: "Translate 'hello' to French." }],
});
console.log(msg.content[0].text); // "Bonjour"SDK in a Next.js API route
Wires the SDK into a Next.js App Router route handler, keeping the API key safely on the server.
// src/app/api/summarise/route.ts
import { NextRequest, NextResponse } from "next/server";
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
export async function POST(req: NextRequest) {
const { text } = await req.json();
const msg = await client.messages.create({
model: "claude-haiku-4-5",
max_tokens: 256,
messages: [{ role: "user", content: `Summarise: ${text}` }],
});
return NextResponse.json({ summary: msg.content[0].text });
}
Discussion