Claude API Express.js Middleware Example
If you're building a Node.js backend that calls Claude, you don't want to repeat API key checks, error handling, and logging in every route. The fix is a small set of Express middleware functions that wrap your Claude calls once and get reused everywhere. This article walks through exactly that: a working middleware stack you can drop into an existing Express app today.
We'll cover authentication middleware (verifying your own app's users, not Claude's keys), a request logger, an error-handling middleware tuned for LLM API failures (timeouts, rate limits, malformed responses), and a thin wrapper middleware that attaches a configured client to req so your route handlers stay short. Code examples use plain fetch calls, but the same pattern works whether you call Claude directly or through a proxy like SubToAPI.
Why middleware matters for Claude API apps
Calling Claude from a single route is easy. The problem shows up once you have five or ten routes that all need: a valid Claude key, consistent error shapes for the frontend, request/response logging for debugging, and some form of rate limiting so one user can't burn your whole budget. Middleware is the natural place to put all of that, because Express runs it before your route logic and lets you short-circuit bad requests early.
The middleware stack we'll build
attachClaudeClient— reads the API key from environment, attaches a small client object toreq.claude.requestLogger— logs method, path, and latency.rateLimiter— simple per-IP or per-user token bucket.errorHandler— catches thrown errors, maps Claude-specific error codes to clean JSON responses.
Step 1: attach a Claude client to each request
// middleware/claudeClient.js
function attachClaudeClient(req, res, next) {
req.claude = {
async send(messages, opts = {}) {
const response = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: opts.model || "claude-sonnet-4",
max_tokens: opts.maxTokens || 1024,
messages,
}),
});
if (!response.ok) {
const error = new Error("Claude API request failed");
error.status = response.status;
error.body = await response.json().catch(() => null);
throw error;
}
return response.json();
},
};
next();
}
module.exports = { attachClaudeClient };
This keeps API key handling and request formatting out of your route files entirely. Any route can now call req.claude.send(messages) without knowing how authentication works.
Step 2: request logging middleware
// middleware/requestLogger.js
function requestLogger(req, res, next) {
const start = Date.now();
res.on("finish", () => {
const duration = Date.now() - start;
console.log(`${req.method} ${req.originalUrl} ${res.statusCode} ${duration}ms`);
});
next();
}
module.exports = { requestLogger };
Logging on res.on("finish") instead of before the request gives you the real status code and total latency, including the Claude round trip.
Step 3: a simple rate limiter
LLM calls are expensive compared to a typical API call, so a basic in-memory limiter is worth having even before you reach for Redis.
// middleware/rateLimiter.js
const buckets = new Map();
function rateLimiter({ windowMs = 60000, max = 20 } = {}) {
return (req, res, next) => {
const key = req.ip;
const now = Date.now();
const entry = buckets.get(key) || { count: 0, resetAt: now + windowMs };
if (now > entry.resetAt) {
entry.count = 0;
entry.resetAt = now + windowMs;
}
entry.count += 1;
buckets.set(key, entry);
if (entry.count > max) {
return res.status(429).json({ error: "Rate limit exceeded, try again shortly" });
}
next();
};
}
module.exports = { rateLimiter };
This is fine for a single-process app. For multi-instance deployments, swap the Map for Redis with the same interface.
Step 4: error-handling middleware
Claude API calls can fail in ways that differ from normal REST errors — context length exceeded, overloaded model, malformed tool use. Centralizing this means your frontend gets consistent error shapes regardless of which route failed.
// middleware/errorHandler.js
function errorHandler(err, req, res, next) {
console.error("Claude API error:", err.message, err.body);
if (err.status === 429) {
return res.status(429).json({ error: "Upstream rate limit hit, retry shortly" });
}
if (err.status === 400) {
return res.status(400).json({ error: "Invalid request to Claude API", details: err.body });
}
if (err.status >= 500) {
return res.status(502).json({ error: "Claude API is temporarily unavailable" });
}
res.status(500).json({ error: "Unexpected server error" });
}
module.exports = { errorHandler };
Express error middleware must be registered last, and must have four arguments (err, req, res, next) or Express won't treat it as an error handler.
Wiring it all together
// app.js
const express = require("express");
const { attachClaudeClient } = require("./middleware/claudeClient");
const { requestLogger } = require("./middleware/requestLogger");
const { rateLimiter } = require("./middleware/rateLimiter");
const { errorHandler } = require("./middleware/errorHandler");
const app = express();
app.use(express.json());
app.use(requestLogger);
app.use(attachClaudeClient);
app.use("/api", rateLimiter({ windowMs: 60000, max: 20 }));
app.post("/api/chat", async (req, res, next) => {
try {
const { message } = req.body;
const result = await req.claude.send([{ role: "user", content: message }]);
res.json(result);
} catch (err) {
next(err);
}
});
app.use(errorHandler);
app.listen(3000, () => console.log("Server running on port 3000"));
Notice the route handler itself is tiny — four lines. All the real complexity lives in middleware you write once and never touch again.
Using SubToAPI instead of raw Claude credentials
If your app talks to Claude through SubToAPI, the middleware above doesn't change — you just point fetch at https://api.subtoapi.app/v1/messages with your sub_live_ key, as shown in the client above. SubToAPI turns your existing Claude access into a standard HTTPS API with per-key usage metadata, which is useful if you want to track consumption per team or per customer without building that yourself. Check the quickstart and messages endpoint docs for the full request/response shape, and streaming docs if you want to extend this middleware pattern to SSE responses. Plans start at €9/month solo, or team seats from €19, with a free trial at signup.
Extending this pattern
Once the base stack works, common additions are: a caching middleware that checks a Redis cache for identical prompts before calling Claude, a cost-tracking middleware that logs token usage per user, and an auth middleware that validates your own app's JWTs before anything touches req.claude. Each slots into the same app.use() chain without disrupting what's already there.
questions
Do I need a separate middleware for streaming responses? Yes — streaming requires piping the response body directly to the client instead of awaiting a full JSON payload, so it's cleaner as its own route-level handler rather than squeezed into the generic client middleware shown here.
Where should rate limiting live — before or after authentication? After. Rate limit by authenticated user ID rather than IP when possible; IP-based limiting is a reasonable fallback for anonymous or public endpoints only.
Can this middleware pattern work with Fastify instead of Express? Yes, the same separation of concerns (client attachment, logging, rate limiting, error handling) applies in Fastify using onRequest and preHandler hooks instead of app.use().