Originally published at claudeguide.io/claude-api-nodejs-typescript
Claude API Node.js TypeScript Tutorial: Complete Setup Guide (2026)
To use the Claude API with Node.js and TypeScript, install @anthropic-ai/sdk, set ANTHROPIC_API_KEY, and you can send your first typed message in under 15 lines of code. This tutorial walks through installation, authentication, typed request/response patterns, streaming, tool use, prompt caching, and error handling — all with TypeScript examples tested against the current API.
Installation and Project Setup
npm install @anthropic-ai/sdk
npm install --save-dev typescript @types/node ts-node
Initialize TypeScript if you haven't already:
npx tsc --init
Recommended tsconfig.json settings for Claude API projects:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"outDir": "./dist",
"esModuleInterop": true
}
}
Set your API key as an environment variable:
export ANTHROPIC_API_KEY="sk-ant-..."
Or use a .env file with dotenv:
npm install dotenv
import 'dotenv/config';
Your First Typed API Call
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic();
async function main() {
const message = await client.messages.create({
model: 'claude-sonnet-4-5',
max_tokens: 1024,
messages: [
{ role: 'user', content: 'Explain TypeScript generics in one paragraph.' }
]
});
// TypeScript knows this is a TextBlock
const textBlock = message.content[0];
if (textBlock.type === 'text') {
console.log(textBlock.text);
}
}
main();
The SDK ships with complete TypeScript types — message.content is typed as `Array<TextBlock | ToolUseBlock
Tool Use (Function Calling) with TypeScript
`typescript
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic();
// Define a typed tool
const weatherTool: Anthropic.Tool = {
name: 'get_weather',
description: 'Get current weather for a city',
input_schema: {
type: 'object',
properties: {
city: { type: 'string', description: 'City name' },
unit: { type: 'string', enum: ['celsius', 'fahrenheit'] }
},
required: ['city']
}
};
interface WeatherInput {
city: string;
unit?: 'celsius' | 'fahrenheit';
}
async function runWithTools() {
const response = await client.messages.create({
model: 'claude-sonnet-4-5',
max_tokens: 1024,
tools: [weatherTool],
messages: [{ role: 'user', content: "What's the weather in Seoul?" }]
});
if (response.stop_reason === 'tool_use') {
const toolUse = response.content.find(
(b): b is Anthropic.ToolUseBlock =
Top comments (0)