Working Node.js code to call the Claude API in 2026. Install @anthropic-ai/sdk, set your API key, and get a response in under 10 lines.
The official Anthropic JavaScript/TypeScript SDK works in Node.js, Deno, Bun, and Cloudflare Workers.
npm install @anthropic-ai/sdk
const Anthropic = require("@anthropic-ai/sdk");
const client = new Anthropic(); // reads ANTHROPIC_API_KEY from process.env
async function main() {
const message = await client.messages.create({
model: "claude-sonnet-4-6",
max_tokens: 1024,
messages: [{ role: "user", content: "Hello, Claude. What year is it?" }]
});
console.log(message.content[0].text);
}
main();
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
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);
| Parameter | Type | Notes |
|---|---|---|
model | string | Use claude-sonnet-4-6 for most tasks. See model comparison. |
max_tokens | number | Hard cap on output tokens. Set to 512–2048 for typical tasks. |
messages | array | Alternating user/assistant turns. |
system | string | System prompt, passed separately from messages array. |
console.log(message.usage.input_tokens); // tokens charged for input
console.log(message.usage.output_tokens); // tokens charged for output
console.log(message.stop_reason); // "end_turn" or "max_tokens"
See the streaming Node.js example for real-time token delivery, or the tool use Node.js example for function calling.