← Blog

Claude API Node.js SDK Quickstart Guide

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

If you're searching for a Claude API Node.js SDK quickstart, you're probably trying to get a working request from your Node app to Claude without digging through pages of documentation. This guide covers exactly that: installing the SDK, authenticating, sending your first message, streaming responses, and handling errors — with runnable code at every step.

By the end, you'll have a Node.js script that calls Claude, prints a streamed response token by token, and knows what to do when something goes wrong. We'll also cover the one decision that trips up most teams early: whether to call Claude directly with a personal API key, or route requests through an application-level API layer so you're not shipping your main credential into every service you build.

Installing the SDK

Anthropic publishes an official Node.js/TypeScript SDK. Install it with npm, yarn, or pnpm:

npm install @anthropic-ai/sdk

It works in both CommonJS and ESM projects, and ships with TypeScript types out of the box, so you get autocomplete on request and response shapes without extra @types packages.

Authenticating your client

The SDK reads your API key from the ANTHROPIC_API_KEY environment variable by default, or you can pass it explicitly:

import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic({
  apiKey: process.env.ANTHROPIC_API_KEY,
});

Keep the key in a .env file during development (loaded via dotenv) and in your platform's secret manager in production. Never hardcode it, and never ship it to a frontend bundle — it will be scraped within hours if it ends up in client-side JavaScript.

Sending your first message

The core call is messages.create(). It takes a model, a max token budget, and an array of messages:

const response = await client.messages.create({
  model: "claude-sonnet-4-5",
  max_tokens: 1024,
  messages: [
    { role: "user", content: "Explain what a closure is in JavaScript." },
  ],
});

console.log(response.content[0].text);

A few things worth knowing before you ship this:

Streaming responses

For chat UIs or anything with a visible "thinking" delay, streaming is the difference between a good UX and a frustrating one. The SDK exposes a dedicated streaming helper:

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

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

const finalMessage = await stream.finalMessage();
console.log("\n--- usage ---", finalMessage.usage);

The text event fires as tokens arrive, which is what you pipe into a WebSocket or Server-Sent Events connection to your frontend. finalMessage() resolves once the stream completes, giving you the full assembled response plus usage metadata.

Using tools (function calling)

Claude can call functions you define — useful for letting it query a database, hit an internal API, or run a calculation. Define a tool with a JSON schema, and Claude decides when to use it:

const response = await client.messages.create({
  model: "claude-sonnet-4-5",
  max_tokens: 1024,
  tools: [
    {
      name: "get_weather",
      description: "Get current weather for a city",
      input_schema: {
        type: "object",
        properties: {
          city: { type: "string" },
        },
        required: ["city"],
      },
    },
  ],
  messages: [{ role: "user", content: "What's the weather in Lisbon?" }],
});

const toolUse = response.content.find((block) => block.type === "tool_use");
if (toolUse) {
  console.log(toolUse.name, toolUse.input);
}

Your code executes the actual function, then sends the result back as a tool_result block in a follow-up message. This round-trip pattern is the backbone of most agentic Claude applications.

Handling errors and rate limits

Production code needs to handle rate limits (429), overloaded errors (529), and transient network failures. Wrap calls in retry logic with exponential backoff, or rely on the SDK's built-in retry behavior, which you can configure:

const client = new Anthropic({
  apiKey: process.env.ANTHROPIC_API_KEY,
  maxRetries: 3,
  timeout: 30 * 1000,
});

Always catch and inspect error.status and error.message — logging the raw error object will save you time when debugging quota or malformed-request issues.

When a direct SDK call isn't enough

The pattern above is great for a single developer prototyping locally. It gets harder once you have a team: everyone needs a key, you want per-feature usage visibility, and you don't want five services sharing one root credential that can't be revoked individually.

This is the gap SubToAPI fills. Instead of distributing your main Claude credential, you generate scoped sub_live_... keys per app or team member from one dashboard, and call a stable HTTPS endpoint that mirrors the same request shape:

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

You still get streaming, tool use, and usage metadata — see the streaming docs and tool use docs — but with revocable per-key access and team seats layered on top. If you're setting up Node.js access for more than one person, start with the quickstart and check pricing for Solo, Team, and Scale plans; there's a free trial at signup.

Putting it together

A minimal, production-leaning setup looks like this:

  1. Install @anthropic-ai/sdk (or point your existing client at an API layer like SubToAPI's /v1/messages endpoint).
  2. Store the key in environment variables, never in code.
  3. Use messages.stream() for anything user-facing.
  4. Log usage on every call so you can track cost per feature.
  5. Add retries and explicit error handling before you deploy.

From here, the natural next steps are adding tool use for structured data retrieval and wiring up proper request logging — both covered in the full docs.

Questions

Do I need the official Anthropic SDK, or can I just use fetch? Either works. The SDK gives you types, retries, and streaming helpers out of the box, which saves boilerplate. Raw fetch is fine for simple scripts or if you're calling an HTTP-compatible layer like SubToAPI directly.

What Node.js version does the SDK require? Node 18 or later is recommended, mainly because it ships with native fetch support, which the SDK relies on internally for requests.

How do I avoid putting my API key in frontend code? Always call Claude from a backend route or serverless function, never from the browser. If multiple apps or team members need access, issue scoped keys per use case instead of sharing one root key — this is exactly what SubToAPI is built for.

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 →