GuidesAI development

Tutorial: calling the Claude API from Node.js

By the Banzai Labs teamUpdated on 2 min read

index.tsPOSTClaude{ JSON }Key on the serverYour server calls the API, never the browser
Your Node.js server calls the Claude API with a key kept on the server, and gets JSON back.

1. Install

npm install @anthropic-ai/sdk

In the server’s .env file, never in the repository:

ANTHROPIC_API_KEY=sk-ant-...
CLAUDE_MODEL=model-identifier

2. Send a message

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

const client = new Anthropic(); // reads ANTHROPIC_API_KEY

const msg = await client.messages.create({
  model: process.env.CLAUDE_MODEL!,
  max_tokens: 1024,
  system: 'Answer in English, in three sentences at most.',
  messages: [{ role: 'user', content: 'Explain what a webhook is.' }],
});

const text = msg.content.find((b) => b.type === 'text');
console.log(text?.text);
console.log(msg.usage.input_tokens, msg.usage.output_tokens);

3. Good habits

  • Key on the serverIn an environment variable, never in browser code.
  • Output capmax_tokens bounds the length, and therefore the cost.
  • Token logusage gives the input and output of every call.
  • A single functionEvery call goes through it: switching models becomes trivial.

Next: stream the answer and get reliable JSON.

Frequently asked questions

Can I call the API from the browser?
No: the key would be visible to everyone. The browser calls your server, which calls the API.
Which model should I pick?
Anthropic's documentation lists the models and their identifiers. Put the identifier in an environment variable so you can change it without touching the code.
What about a 429 or overloaded error?
The SDK retries automatically a few times. Beyond that, queue the request and try again later.

Read next

All guides