← Blog

Claude API Node.js SDK Tutorial: Build Your First App

2026-11-15 · 5 min read · SubToAPI Team

If you're searching for a Claude API Node.js SDK tutorial, you want working code: how to install the SDK, authenticate, send a message, stream a response, and handle errors — in that order, with no detours. This article walks through exactly that, using the official @anthropic-ai/sdk package, then shows how the same patterns map onto a plain HTTPS setup if you'd rather not manage a separate Anthropic account and billing relationship.

By the end you'll have a runnable Node.js script that sends prompts to Claude and gets structured responses back, plus the knowledge to add streaming and tool use on top of it.

Prerequisites

Installing the SDK

npm install @anthropic-ai/sdk

This gives you a typed client with methods for messages, streaming, and tool calls. It works the same whether you're pointing at Anthropic directly or at a compatible gateway.

Your First Request

Create a .env file with your key, then load it with dotenv or your framework's config loader. Here's the minimal script:

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-20241022",
    max_tokens: 1024,
    messages: [
      { role: "user", content: "Explain what a closure is in JavaScript, in two sentences." },
    ],
  });

  console.log(message.content[0].text);
}

main();

Run it with node index.js. You should get a short, direct answer back within a second or two. The content field is an array because Claude can return multiple content blocks — text, tool calls, or both — so always index into it rather than assuming a single string.

Handling Multi-Turn Conversations

Claude's API is stateless: you send the full conversation history on every request. For a chat-style app, keep an array of messages and append to it as the conversation progresses.

const history = [
  { role: "user", content: "What's the capital of Portugal?" },
];

const first = await client.messages.create({
  model: "claude-3-5-sonnet-20241022",
  max_tokens: 512,
  messages: history,
});

history.push({ role: "assistant", content: first.content[0].text });
history.push({ role: "user", content: "What's the population there?" });

const second = await client.messages.create({
  model: "claude-3-5-sonnet-20241022",
  max_tokens: 512,
  messages: history,
});

Watch your token usage as history grows — long conversations need either truncation or summarization to stay under the context window.

Streaming Responses

For chat UIs, streaming tokens as they're generated makes the app feel responsive instead of frozen for several seconds. The SDK exposes a .stream() helper:

const stream = client.messages.stream({
  model: "claude-3-5-sonnet-20241022",
  max_tokens: 1024,
  messages: [{ role: "user", content: "Write a haiku about Node.js." }],
});

stream.on("text", (text) => {
  process.stdout.write(text);
});

await stream.finalMessage();

This pattern works identically whether the stream originates from Anthropic directly or from a service that proxies the same event format.

Adding Tool Use

Claude can call functions you define — useful for pulling live data, running calculations, or triggering actions in your app. You describe tools with a JSON schema, and Claude decides when to call them.

const tools = [
  {
    name: "get_weather",
    description: "Get the current weather for a city",
    input_schema: {
      type: "object",
      properties: {
        city: { type: "string" },
      },
      required: ["city"],
    },
  },
];

const response = await client.messages.create({
  model: "claude-3-5-sonnet-20241022",
  max_tokens: 1024,
  tools,
  messages: [{ role: "user", content: "What's the weather in Lisbon?" }],
});

const toolCall = response.content.find((block) => block.type === "tool_use");
if (toolCall) {
  console.log(toolCall.name, toolCall.input);
  // run your actual weather lookup here, then send the result back
  // as a tool_result message in the next request
}

This is the pattern behind most Claude-powered agents: the model proposes a call, your code executes it, and you feed the result back as a follow-up message.

When You Don't Want to Manage Anthropic Billing Directly

The SDK above talks straight to Anthropic's API, which means you're on their billing, rate limits, and key management from day one. If you're already paying for Claude through a subscription and want an HTTPS API with application-level keys, usage metadata, and team seats instead of managing raw Anthropic credentials, SubToAPI exposes the same request shapes — messages, streaming, and tool use — under a sub_live_... key.

curl https://api.subtoapi.app/v1/messages \
  -H "Authorization: Bearer $SUBTOAPI_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-3-5-sonnet-20241022",
    "max_tokens": 1024,
    "messages": [{"role": "user", "content": "Hello Claude"}]
  }'

The request and response structure matches what's shown throughout this tutorial, so the Node.js code above needs only a base URL and key swap to run against it. See /docs/quickstart for setup and /docs/messages and /docs/streaming for full parameter references. Plans start at /pricing, with a free trial at /signup.

Error Handling and Retries

Production code should handle rate limits (HTTP 429) and transient server errors (5xx) with exponential backoff:

async function withRetry(fn, attempts = 3) {
  for (let i = 0; i < attempts; i++) {
    try {
      return await fn();
    } catch (err) {
      if (i === attempts - 1) throw err;
      await new Promise((r) => setTimeout(r, 2 ** i * 500));
    }
  }
}

Wrap your messages.create calls in this and you'll avoid most flaky failures in production.

questions

Do I need the official Anthropic SDK, or can I use plain fetch? Either works. The SDK adds typed responses, streaming helpers, and retry logic, but the underlying API is plain HTTPS/JSON, so fetch or axios work fine if you prefer fewer dependencies.

Can I use this tutorial's code against a non-Anthropic endpoint? Yes, as long as the service implements the same request and response shapes. Point the baseURL (or your fetch URL) at the alternate host and swap the API key — the message and streaming code stays identical.

What Node version do I need for streaming to work? Node 18+ is recommended since it has native fetch and stable async iterator support, both of which the SDK's streaming client relies on internally.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →