Claude API User Authentication Middleware in Node.js
If you're putting the Claude API behind a Node.js backend, you need middleware that authenticates your own users before any request reaches Anthropic — not just an API key check on the Claude side. This is the piece most tutorials skip: they show you how to call messages.create, but not how to make sure the person calling your /chat endpoint is who they say they are, hasn't exceeded their quota, and isn't able to see other users' data.
This article covers exactly that: a practical Express/Node.js middleware stack for authenticating end users, attaching per-user context, enforcing rate limits, and only then forwarding the request to Claude (either directly or through a gateway like SubToAPI). The goal is a clean separation between "who is calling my API" and "how do I call Claude."
Why you need a middleware layer at all
A single Anthropic API key is a shared secret for your whole backend. It has no concept of individual users. If you expose Claude functionality to multiple users — through a SaaS product, an internal tool, or a public API — you need a layer that:
- Verifies the caller's identity (JWT, session cookie, or API key)
- Attaches a
req.userobject with id, plan, and permissions - Enforces per-user rate limits and quotas
- Logs usage per user for billing or auditing
- Returns consistent error responses before any tokens are spent on a Claude call
Without this, a bug or an exposed endpoint can let anyone burn your Claude budget, and you have no way to attribute cost or abuse to a specific account.
Step 1: authenticate the request
The simplest pattern is JWT-based auth, since it avoids a database lookup on every request:
const jwt = require('jsonwebtoken');
function authenticateUser(req, res, next) {
const authHeader = req.headers.authorization;
if (!authHeader?.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Missing bearer token' });
}
const token = authHeader.split(' ')[1];
try {
req.user = jwt.verify(token, process.env.JWT_SECRET);
next();
} catch (err) {
return res.status(401).json({ error: 'Invalid or expired token' });
}
}
If you're issuing API keys to your own customers instead of sessions, swap the JWT check for a lookup against a keys table (hashed keys, never stored in plaintext), and attach the matching user record to req.user.
Step 2: enforce per-user rate limits
Claude calls cost money and time, so rate limiting by user — not just by IP — matters. express-rate-limit supports custom keys:
const rateLimit = require('express-rate-limit');
const claudeLimiter = rateLimit({
windowMs: 60 * 1000,
max: (req) => (req.user.plan === 'pro' ? 60 : 10),
keyGenerator: (req) => req.user.id,
message: { error: 'Rate limit exceeded for your plan' }
});
app.use('/api/chat', authenticateUser, claudeLimiter);
This gives you plan-based throttling without touching Claude's own rate limits, and it keeps noisy or buggy clients from starving other users.
Step 3: forward the authenticated request
Once the middleware has verified identity and checked quota, the route handler just needs to make the Claude call. Here's where the architecture splits into two common patterns.
Pattern A — direct Anthropic SDK call, using your backend's single Claude API key:
app.post('/api/chat', authenticateUser, claudeLimiter, async (req, res) => {
try {
const response = await anthropic.messages.create({
model: 'claude-sonnet-4-5',
max_tokens: 1024,
messages: [{ role: 'user', content: req.body.message }]
});
res.json({ reply: response.content[0].text, userId: req.user.id });
} catch (err) {
res.status(502).json({ error: 'Upstream model error' });
}
});
This works, but every user hits the same key, so you still need your own usage logging to know who consumed what.
Pattern B — route through SubToAPI with per-application keys. SubToAPI sits between your backend and Claude, exposing a plain HTTPS API with its own sub_live_... keys and built-in usage metadata per key. You still authenticate your end users with your own middleware exactly as above — SubToAPI doesn't replace that — but it removes the need to manage Anthropic credentials and gives you a usage trail per application key out of the box:
app.post('/api/chat', authenticateUser, claudeLimiter, async (req, res) => {
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: 'claude-sonnet-4-5',
max_tokens: 1024,
messages: [{ role: 'user', content: req.body.message }]
})
});
const data = await response.json();
res.json({ reply: data.content[0].text, userId: req.user.id });
});
For teams with multiple developers or environments, issuing separate sub_live_ keys per service (staging, production, internal tools) means you can see usage and spend broken down by key in the dashboard, without building that tracking yourself. See /docs/quickstart for setup and /docs/messages for the full request/response shape.
Step 4: log and attribute usage
Even with a gateway handling the Claude call, you should log at the middleware level who made each request and when:
function logUsage(req, res, next) {
res.on('finish', () => {
console.log(JSON.stringify({
userId: req.user?.id,
route: req.originalUrl,
status: res.statusCode,
ts: new Date().toISOString()
}));
});
next();
}
Pipe this into your existing logging stack (structured JSON to stdout works fine for most setups) so you can reconcile per-user activity against billing or abuse reports later.
Putting it together
A reasonable middleware chain looks like:
authenticateUser— verify JWT or API key, attachreq.userclaudeLimiter— enforce per-plan rate limitslogUsage— record the request for auditing- Route handler — call Claude directly or via SubToAPI
This keeps user authentication fully decoupled from model access. If you later swap providers, change rate-limit tiers, or move from direct Anthropic calls to a gateway, the first three layers don't need to change at all.
Questions
Do I still need my own auth if I use a gateway like SubToAPI? Yes. SubToAPI authenticates your application to Claude via its own API keys — it has no knowledge of your end users. You still need middleware like the examples above to authenticate individual users before your backend makes the call.
Should rate limits be enforced before or after the Claude call? Before. Checking quota first avoids spending tokens on requests you're going to reject anyway, and it returns errors faster to the client.
How do I handle streaming responses in this middleware setup? Keep the auth and rate-limit middleware unchanged — they run before the handler. The handler itself needs to pipe the stream to the client instead of buffering a full response; see /docs/streaming for the request format when streaming through SubToAPI.