How to Do Express Middleware Setup on Claude Code
In this article
- What is Express middleware and why use Claude Code to set it up?
- How to prompt Claude Code for Express middleware setup
- Common Express middleware patterns Claude Code handles well
- Using Claude Code slash commands during middleware setup
- How to avoid hitting usage limits during a middleware session
- Example: a full middleware setup prompt that works well
- Key takeaways
- Sources
Claude Code can scaffold and configure a complete Express middleware stack in minutes using natural-language prompts. It's best suited for Node.js developers who want to skip boilerplate and stay in flow. The trade-off: Claude Code burns tokens on code generation, so a complex middleware chain (auth, CORS, rate limiting, logging) can push you toward your usage ceiling faster than you expect. One thing to watch: a mid-task lockout while wiring up a critical auth layer is painful. Knowing your limits in advance matters.
- Express middleware setup typically involves 3-6 distinct layers (body parsing, CORS, auth, rate limiting, error handling, logging)
- Claude Code can generate, test, and iterate on a full middleware chain in a single session
- Claude Pro and Max plans have 5-hour usage windows that reset on a rolling basis (Anthropic support)
What is Express middleware and why use Claude Code to set it up?
Express middleware are functions that execute in the request-response pipeline of a Node.js web server. Each middleware function receives the req, res, and next objects and either terminates the cycle or passes control forward. A typical production stack layers in body parsing, CORS headers, authentication checks, rate limiting, input validation, and error handling.
Setting this up manually means hunting down package docs, wiring order-sensitive middleware correctly, and debugging integration issues. Claude Code collapses that into a conversation. You describe the stack you need, Claude generates it, and you iterate inline without leaving your terminal.
How to prompt Claude Code for Express middleware setup
The key is being specific in your initial prompt. Claude Code works best when you describe your stack, not just your intent. Here's a practical approach:
Start a new Claude Code session in your project root
Open your terminal in your Express project directory and launch Claude Code:
claude
If you haven't set up Claude Code yet, see the guide on setting up Claude Code in macOS terminal to get started.
Use a detailed setup prompt
Vague prompts produce generic output. Tell Claude Code exactly what middleware layers you need and in what order. For example:
Set up Express middleware for a REST API. I need:
1. express.json() and express.urlencoded() for body parsing
2. CORS configured for https://myapp.com only
3. Helmet for security headers
4. express-rate-limit: 100 requests per 15 minutes per IP
5. Morgan logging in 'combined' format
6. A centralized error handler at the bottom
Use TypeScript. Create a middleware/index.ts that exports all middleware as an array.
Ask Claude Code to install dependencies
After generating the middleware code, prompt Claude to handle the package installs:
Install all necessary npm packages for this middleware stack and update package.json
Claude Code will run npm install for helmet, cors, express-rate-limit, morgan, and their TypeScript types automatically.
Iterate with specific refinements
Once the base stack is wired, you can refine individual layers:
Add JWT verification middleware that skips /health and /docs routesMake the rate limiter use Redis as the store instead of memoryAdd a request ID middleware that attaches a UUID to each request for log tracing
For auth-specific middleware like JWT, there's a dedicated walkthrough on JWT authentication setup on Claude Code. For rate limiting in depth, see how to do rate limiting on Claude Code.
Common Express middleware patterns Claude Code handles well
| Middleware | Package | Typical prompt phrase |
|---|---|---|
| CORS | cors | "Configure CORS for [origin], allow [methods]" |
| Security headers | helmet | "Add Helmet with CSP for my React frontend" |
| Rate limiting | express-rate-limit | "Rate limit to 100 req/15min, stricter on /auth" |
| Authentication | jsonwebtoken / passport | "Verify JWT on all routes except /public" |
| Request logging | morgan / pino-http | "Add structured JSON logging with pino" |
| Body parsing | express built-in | "Parse JSON bodies, limit to 10mb" |
| Validation | zod / joi / express-validator | "Validate request body against this Zod schema" |
| Error handling | custom / http-errors | "Centralized error handler, return JSON errors" |
Using Claude Code slash commands during middleware setup
Claude Code's slash commands are useful checkpoints during a complex middleware session:
- /review: Ask Claude to review the middleware order and flag any security issues before you commit
- /usage: Check how much of your session budget you've consumed mid-task (also available at claude.ai/settings/usage)
- /clear: Reset context if the conversation drifts from the middleware task
- /compact: Summarize long context when you're iterating heavily and want to preserve budget
The /usage command is worth checking before starting a big middleware refactor. If you're already at 70% of your window, you may hit a limit mid-session. This is exactly the kind of context-switching frustration that Usagebar is built to prevent.
How to avoid hitting usage limits during a middleware session
Express middleware setup is iterative. You'll generate code, test it, refine it, and repeat. Each round-trip costs tokens, and a complex setup (TypeScript, Redis-backed rate limiting, multi-strategy Passport auth) can burn through a significant chunk of a 5-hour usage window (Claude Pro/Max plan details).
Practical ways to stay within limits:
- Front-load specificity. One detailed prompt beats five vague back-and-forth exchanges
- Use
/compactafter each major milestone (e.g., after body parsing and CORS are done) to compress context before moving to auth - Check
/usagebefore starting each major middleware layer - Break large stacks into focused sessions: one for security headers + CORS, one for auth, one for observability
For a broader look at keeping token consumption down, see how to reduce Claude Code token usage.
Monitor your usage window in real time with Usagebar
The most reliable way to avoid a mid-task lockout is to know your remaining capacity at a glance. Usagebar sits in your macOS menu bar and shows your Claude Code usage in real time, with smart alerts at 50%, 75%, and 90% of your limit. It uses macOS Keychain to store your credentials securely and tells you exactly when your 5-hour window resets.
There's no worse moment to hit your limit than halfway through wiring up JWT middleware for a PR deadline. Usagebar keeps that context visible without making you switch to a browser tab.
Get Usagebar: instant download, pay-what-you-want pricing (free for students).
Example: a full middleware setup prompt that works well
Here's a prompt structure that consistently produces clean, production-ready Express middleware with Claude Code:
I'm building a REST API with Express and TypeScript. Set up a middleware stack with:
- Helmet (CSP: default-src 'self', script-src 'self')
- CORS: allow https://app.example.com, credentials: true
- express-rate-limit: 200 req/15min globally, 10 req/15min on POST /auth
- express.json() with 5mb limit
- Morgan in 'combined' format, write to ./logs/access.log
- JWT auth middleware: verify RS256 tokens, skip /health /docs
- Zod validation middleware: validate req.body shape per route
- Global error handler: return { error: string, code: number } JSON
Create src/middleware/index.ts with all middleware in correct order.
Create src/middleware/auth.ts, validation.ts, error.ts as separate files.
Install all packages.
This single prompt gives Claude Code everything it needs to produce a usable, ordered middleware chain with correct separation of concerns. You can also pair this pattern with Drizzle ORM setup or Supabase auth setup if you're building a full backend from scratch.
Key takeaways
- Use a single detailed prompt that specifies every middleware layer, its config, and the file structure you want
- Ask Claude Code to install packages in the same session, not as a follow-up
- Use
/compactafter major milestones to preserve your token budget for complex layers like auth - Check
/usageor monitor via Usagebar before starting large refactors - Break a 6+ layer stack into focused sessions (security, auth, observability) if you're working within a Pro plan window
- Use
/reviewbefore committing to catch middleware ordering bugs (auth before rate limit, error handler last)
Sources
Never Get Locked Out Mid-Task Again
Never hit your usage limits unexpectedly. Usagebar lives in your menu bar and shows your 5-hour and weekly limits at a glance.
Get Usagebar$9 — one-time, lifetime updates