Claude API Node.js Express Integration Guide
If you're building a Node.js backend and want to add Claude to an Express app, the integration itself is straightforward: install the SDK or use plain fetch, wrap the call in a route handler, and pass the response back to your frontend. The parts that actually take time are structuring the route cleanly, handling streaming responses, and dealing with errors and rate limits without crashing your server.
This guide walks through a working Express setup for the Claude API — a basic chat route, a streaming route using Server-Sent Events, environment configuration, and the error-handling patterns you'll want in production. It also covers how a service like SubToAPI changes the integration if you're currently blocked on Anthropic's own API access.
Project setup
Start with a minimal Express project:
mkdir claude-express && cd claude-express
npm init -y
npm install express dotenv
Create a .env file for your credentials:
ANTHROPIC_API_KEY=sk-ant-...
PORT=3000
If you're using SubToAPI instead of a direct Anthropic key, the only difference is the variable name and base URL:
SUBTOAPI_KEY=sub_live_...
Basic Express route for Claude
The core pattern is a POST route that accepts a prompt (or message history) from the client, forwards it to the Claude API, and returns the model's response as JSON.
// server.js
import express from "express";
import dotenv from "dotenv";
dotenv.config();
const app = express();
app.use(express.json());
app.post("/api/chat", async (req, res) => {
const { messages } = req.body;
try {
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-sonnet-4-5",
max_tokens: 1024,
messages,
}),
});
if (!response.ok) {
const err = await response.json();
return res.status(response.status).json({ error: err });
}
const data = await response.json();
res.json(data);
} catch (err) {
console.error(err);
res.status(500).json({ error: "Internal server error" });
}
});
app.listen(process.env.PORT, () => {
console.log(`Server running on port ${process.env.PORT}`);
});
If you're routing through SubToAPI instead, the call looks the same with a different host and header:
const response = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
},
body: JSON.stringify({
model: "claude-sonnet-4-5",
max_tokens: 1024,
messages,
}),
});
The request and response shapes match the Claude Messages API, so your route logic, validation, and error handling don't need to change — see the docs for the full payload reference.
Streaming responses from Express
For chat UIs, you don't want to wait for the full response before sending anything to the client. Streaming with Server-Sent Events keeps the connection open and forwards tokens as they arrive.
app.post("/api/chat/stream", async (req, res) => {
const { messages } = req.body;
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Connection", "keep-alive");
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-sonnet-4-5",
max_tokens: 1024,
stream: true,
messages,
}),
});
const reader = response.body;
for await (const chunk of reader) {
res.write(chunk);
}
res.end();
});
On the client, consume this with EventSource or a fetch reader. If you need a full walkthrough of parsing SSE event types (content_block_delta, message_stop, etc.), see Claude API streaming.
Handling errors and rate limits
Production Express routes need to handle three recurring failure modes:
- 429 rate limits — back off and retry, or surface a clear error to the client instead of letting the request hang.
- Timeouts — set an
AbortControllertimeout on the fetch call so a slow response doesn't tie up your Node event loop indefinitely. - Malformed input — validate
messagesshape before sending it to the API; Claude will reject malformed requests with a 400, but catching it earlier saves a round trip.
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: "Something went wrong" });
});
A thin middleware like this, combined with try/catch around every API call, keeps one bad request from taking down the whole server.
Structuring routes for multiple consumers
Once you have more than one frontend (web app, mobile, internal tool), it's worth centralizing the Claude call into a single service module rather than duplicating fetch logic across routes:
// services/claude.js
export async function callClaude(messages, opts = {}) {
const res = 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: opts.model || "claude-sonnet-4-5",
max_tokens: opts.maxTokens || 1024,
messages,
}),
});
if (!res.ok) throw new Error(`Claude API error: ${res.status}`);
return res.json();
}
This also makes it trivial to swap in a different backend — like SubToAPI — by changing one file instead of every route that touches the model.
Where SubToAPI fits
The Express patterns above work identically whether you're calling Anthropic directly or through SubToAPI. The practical reasons teams route through SubToAPI instead:
- No separate Anthropic account approval — get an application key (
sub_live_...) right after signup. - Per-key usage metadata, so you can track which Express route or client is consuming tokens.
- Team seats for sharing access across a dev team without sharing one raw key.
Plans start at €9/month for solo use, with Team and Scale tiers for shared access — see pricing. If you're setting this up for the first time, the quickstart covers key generation and your first authenticated request in under five minutes.
questions
Do I need the official Anthropic SDK to use Claude in Express? No. The SDK is convenient but optional — plain fetch or axios against the Messages API endpoint works fine in any Node.js environment, including Express routes.
How do I stream Claude responses to a React or Vue frontend from Express? Set the response headers for text/event-stream, pipe the streamed fetch body through res.write(), and consume it client-side with EventSource or a ReadableStream reader. See streaming docs for event-by-event details.
Can I use tool calling in an Express route the same way? Yes — tool use works through the same Messages endpoint with a tools array in the request body. Your Express route just needs to handle the extra tool_use content blocks in the response; see tool use docs for schema examples.