Getting Started with the Claude API in Node.js
Updated November 2026: rewritten for the current Claude models and SDK. Every example below has been run.
To call Claude from a Node.js app, install @anthropic-ai/sdk in your project and set ANTHROPIC_API_KEY. Start with one message, then use the same client for conversations, streaming and an Express endpoint.
What you need
- Node.js 20 or newer
- An API key from the Claude Console
Install the SDK
Anthropic publishes two npm packages for different jobs:
- Call the Claude API from JavaScript or TypeScript. Run
npm install @anthropic-ai/sdkin your project. Your code importsAnthropicfrom this package. Claude API SDK documentation - Run Claude Code in your terminal. Use the installer for your operating system or, with Node.js 22 or later, run
npm install -g @anthropic-ai/claude-code@latest. Check the installation withclaude --version. Claude Code setup
For the API examples below, create a Node.js project and add the SDK:
mkdir claude-node && cd claude-node
npm init -y
npm pkg set type=module
npm install @anthropic-ai/sdk
Put your key in an environment variable rather than in your code. The SDK reads ANTHROPIC_API_KEY automatically:
export ANTHROPIC_API_KEY="sk-ant-..."
If you prefer a .env file, add ANTHROPIC_API_KEY=your_key_here to the file and add .env to your .gitignore. Run the script with node --env-file=.env first.js.
If the SDK reports a missing API key, check whether the Node process can see it. This command prints a Boolean and keeps the key out of your terminal output:
node --env-file=.env -e 'console.log(Boolean(process.env.ANTHROPIC_API_KEY))'
Omit --env-file=.env if you exported the variable in your shell. A result of true confirms the variable is present. If the API returns 401, verify that the value is an active key from the Claude Console. Claude API key setup
Your first message
Create first.js:
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic(); // reads ANTHROPIC_API_KEY from the environment
const message = await client.messages.create({
model: "claude-opus-5-5",
max_tokens: 1024,
messages: [{ role: "user", content: "What is the capital of France?" }],
});
// content is an array of blocks. Text answers come back as "text" blocks.
for (const block of message.content) {
if (block.type === "text") console.log(block.text);
}
Run it with node first.js.
Three things trip people up here:
max_tokensis required. It caps how long the reply can be. Leave it out and the API returns a 400 error.message.contentis an array of blocks, not a string. Printing it directly gives you[ { type: 'text', text: '...' } ]. Loop over the blocks and read.textfrom the text ones.- Check
stop_reason.end_turnmeans Claude finished.max_tokensmeans the reply was cut off, so raise the limit.
Conversations and system prompts
The API doesn't remember anything between requests. To hold a conversation, keep the history yourself and send all of it every time. A system prompt sets the role and rules for the whole conversation.
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
const history = [];
async function ask(question) {
history.push({ role: "user", content: question });
const message = await client.messages.create({
model: "claude-opus-5-5",
max_tokens: 1024,
system: "You are a patient maths tutor. Explain one step at a time.",
messages: history,
});
// Keep Claude's reply in the history so the next question has context.
history.push({ role: "assistant", content: message.content });
return message.content
.filter((block) => block.type === "text")
.map((block) => block.text)
.join("");
}
console.log(await ask("How do I solve x² - 5x + 6 = 0?"));
console.log(await ask("Why does factoring work there?"));
Pushing message.content (the whole array, not just the text) back into the history matters once you start using tools, because tool calls live in those blocks too.
Streaming responses
For anything longer than a sentence or two, stream the reply so users see it as it's written. client.messages.stream() gives you text as it arrives and the complete message at the end:
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
const stream = client.messages
.stream({
model: "claude-opus-5-5",
max_tokens: 4096,
messages: [{ role: "user", content: "Write a short story about a lighthouse keeper." }],
})
.on("text", (text) => process.stdout.write(text));
const message = await stream.finalMessage();
console.log(`\n\n${message.usage.output_tokens} output tokens, stopped because: ${message.stop_reason}`);
Streaming also stops long requests from hitting HTTP timeouts, so use it whenever you set a high max_tokens.
Choosing a model
These were the current models at the time of writing:
| Model | ID | Good for | Input / output per million tokens |
|---|---|---|---|
| Claude Opus 5.5 | claude-opus-5-5 |
Most tasks, especially reasoning and coding | $4 / $20 |
| Claude Sonnet 5.5 | claude-sonnet-5-5 |
Fast, capable everyday work | $2 / $10 |
| Claude Haiku 5.5 | claude-haiku-5-5 |
High-volume, simple, latency-sensitive jobs | $0.10 / $0.50 |
Models are retired over time (the claude-3-opus-20240229 ID this post originally used no longer works), so check the models overview and pricing before you pick one. Keep the model ID in one constant or environment variable so switching is a one-line change.
You can also trade quality for speed and cost on the same model with effort. For simple jobs like classification or short answers, low is usually enough:
const message = await client.messages.create({
model: "claude-opus-5-5",
max_tokens: 256,
output_config: { effort: "low" },
messages: [{ role: "user", content: "Is this review positive or negative? 'Arrived late, works great.'" }],
});
Handling errors and retries
You don't need a retry library. The SDK already retries rate limits (429), server errors (5xx) and connection problems twice, with exponential backoff. You can change that, along with the timeout, when you create the client.
Every API error extends Anthropic.APIError, so check the specific classes first:
import Anthropic from "@anthropic-ai/sdk";
// The SDK already retries 408, 409, 429 and 5xx responses twice with backoff.
// Raise or lower that here instead of adding a separate retry library.
const client = new Anthropic({ maxRetries: 4, timeout: 60_000 });
try {
const message = await client.messages.create({
model: "claude-opus-5-5",
max_tokens: 1024,
messages: [{ role: "user", content: "Hello, Claude" }],
});
console.log(message.content);
} catch (error) {
// Check the most specific classes first: they all extend Anthropic.APIError.
if (error instanceof Anthropic.AuthenticationError) {
console.error("Check ANTHROPIC_API_KEY.");
} else if (error instanceof Anthropic.NotFoundError) {
console.error("That model name doesn't exist:", error.message);
} else if (error instanceof Anthropic.RateLimitError) {
console.error("Still rate limited after retries. Slow down or queue requests.");
} else if (error instanceof Anthropic.APIError) {
console.error(`API error ${error.status}:`, error.message);
} else {
throw error;
}
}
Putting Claude behind an Express endpoint
Never call the API from the browser, because that exposes your key. Put it behind your own server instead:
npm install express
import express from "express";
import Anthropic from "@anthropic-ai/sdk";
const app = express();
app.use(express.json());
const client = new Anthropic();
app.post("/ask", async (req, res) => {
const { question } = req.body ?? {};
if (typeof question !== "string" || question.trim() === "") {
return res.status(400).json({ error: "Send a JSON body with a 'question' string." });
}
try {
const message = await client.messages.create({
model: "claude-opus-5-5",
max_tokens: 1024,
messages: [{ role: "user", content: question }],
});
const answer = message.content
.filter((block) => block.type === "text")
.map((block) => block.text)
.join("");
res.json({ answer, stopReason: message.stop_reason });
} catch (error) {
if (error instanceof Anthropic.RateLimitError) {
return res.status(429).json({ error: "Busy right now, try again shortly." });
}
console.error(error);
res.status(502).json({ error: "Couldn't reach Claude." });
}
});
app.listen(3000, () => console.log("Listening on http://localhost:3000"));
Test it:
curl -X POST http://localhost:3000/ask \
-H "Content-Type: application/json" \
-d '{"question": "What is the capital of France?"}'
Before you put this online, add authentication and rate limiting to /ask, because otherwise anyone who finds the URL can spend your credits.
Where to go next
- Claude API documentation
- TypeScript SDK on GitHub
- Getting started with the Claude API in Python, the same tutorial for Python
- Building MCP servers and clients with Node.js, to give Claude tools it can call