Claude API Node.js Quickstart Guide
If you're trying to get a Node.js app talking to Claude, the fastest path is: get an API key, install the SDK (or use plain fetch), send a request to the Messages endpoint, and handle the response shape correctly. This guide walks through each step with working code, so you can go from zero to a functioning Claude integration in under 15 minutes.
We'll cover both the official approach (direct Anthropic API access) and what to do once you're ready to ship that integration to real users — because calling Claude from your laptop and calling it from a production app with multiple customers are two very different problems.
Prerequisites
Before you start, you need:
- Node.js 18 or later (for native
fetchsupport) - An Anthropic API key, or an API key from a provider that exposes Claude over a compatible HTTPS API
- A terminal and a text editor — no framework required for this quickstart
Create a new project:
mkdir claude-node-quickstart
cd claude-node-quickstart
npm init -y
Option 1: Using the official SDK
Anthropic publishes an official Node.js SDK that wraps the HTTP API and handles retries, types, and streaming for you.
npm install @anthropic-ai/sdk
Store your key in an environment variable rather than hardcoding it:
export ANTHROPIC_API_KEY="your-key-here"
Then make your first request:
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
});
async function main() {
const message = await client.messages.create({
model: "claude-3-5-sonnet-latest",
max_tokens: 1024,
messages: [
{ role: "user", content: "Explain promises in Node.js in two sentences." },
],
});
console.log(message.content[0].text);
}
main();
Run it with node index.js (add "type": "module" to your package.json or use .mjs). If everything is set up correctly, you'll get a plain-text response printed to your terminal within a second or two.
Option 2: Calling the API directly with fetch
If you don't want a dependency, plain fetch works fine since Node 18+:
const response = await fetch("https://api.anthropic.com/v1/messages", {
method: "POST",
headers: {
"content-type": "application/json",
"x-api-key": process.env.ANTHROPIC_API_KEY,
"anthropic-version": "2023-06-01",
},
body: JSON.stringify({
model: "claude-3-5-sonnet-latest",
max_tokens: 1024,
messages: [{ role: "user", content: "Write a haiku about Node.js." }],
}),
});
const data = await response.json();
console.log(data.content[0].text);
This is useful to understand because it shows exactly what's happening under the hood: a POST request with a JSON body, an API key header, and a response object containing a content array.
Handling the response shape
A common beginner mistake is assuming the response is a plain string. It isn't — content is an array of content blocks, because Claude can return text, tool calls, or other block types in the same response:
const textBlocks = message.content.filter((block) => block.type === "text");
const fullText = textBlocks.map((b) => b.text).join("");
For simple text-only requests, message.content[0].text is usually enough, but writing defensive code that filters by type will save you debugging time once you add tool use or longer multi-turn conversations.
Basic error handling
Production code needs to handle rate limits, timeouts, and malformed requests gracefully:
try {
const message = await client.messages.create({
model: "claude-3-5-sonnet-latest",
max_tokens: 1024,
messages: [{ role: "user", content: "Hello" }],
});
console.log(message.content[0].text);
} catch (err) {
if (err.status === 429) {
console.error("Rate limited — back off and retry.");
} else if (err.status >= 500) {
console.error("Upstream error — retry with backoff.");
} else {
console.error("Request failed:", err.message);
}
}
A simple exponential backoff on 429 and 5xx responses is enough for most early-stage apps.
Multi-turn conversations
Claude doesn't retain conversation state server-side — you send the full message history on every call:
const history = [
{ role: "user", content: "What's a closure in JavaScript?" },
];
const first = await client.messages.create({
model: "claude-3-5-sonnet-latest",
max_tokens: 512,
messages: history,
});
history.push({ role: "assistant", content: first.content[0].text });
history.push({ role: "user", content: "Give me a short code example." });
const second = await client.messages.create({
model: "claude-3-5-sonnet-latest",
max_tokens: 512,
messages: history,
});
This pattern — append, call, append, call — is the backbone of every chat interface, agent, or assistant built on Claude.
Going from quickstart to a real product
This setup is enough to build a prototype, but shipping it to actual users raises new questions: How do you give each customer their own API key instead of sharing one secret across your app? How do you track usage per customer for billing? How do you expose streaming and tool calls over a clean HTTPS interface your frontend or mobile team can consume without touching SDK internals?
This is the gap SubToAPI fills. It turns your existing Claude access into a proper HTTPS API with scoped application keys (sub_live_...), per-key usage metadata, streaming, tool use, and team seats, all from one dashboard — without you building key management and billing plumbing yourself. If you're past the "does this work" stage and into "how do I ship this to customers" stage, it's worth a look at /docs/quickstart and /pricing.
For the pure API basics — request/response shape, authentication headers, message formatting — /docs/messages and /docs/streaming cover the same patterns shown above, applied to SubToAPI's endpoint instead of calling Anthropic directly.
Questions
Do I need the official SDK, or can I just use fetch? Either works. The SDK gives you typed responses, built-in retries, and streaming helpers. Plain fetch has zero dependencies and is easier to understand when you're first learning the request/response shape.
Why does Claude return an array for content instead of a string? Because a single response can contain multiple block types — text, tool calls, or other structured content. Filtering by type keeps your code correct as you add features like tool use.
How do I avoid sending my API key to every customer's device? Never call the Claude API directly from client-side code. Route requests through your own backend, or use a service like SubToAPI that issues scoped per-customer keys you can revoke individually.