Nextjs Middleware Streamlined
Battle-tested command for create, optimized, next, middleware. Includes structured workflows, validation checks, and reusable patterns for nextjs vercel.
Next.js Middleware Streamlined
Create production-ready Next.js middleware with authentication, rate limiting, CORS, security headers, redirects, and URL rewriting in a composable, modular architecture.
When to Use This Command
Run this command when you need to add or refactor middleware in your Next.js application.
- You need authentication middleware that protects specific routes with JWT or session validation
- You want to add rate limiting to your API routes to prevent abuse
- You need security headers (CSP, HSTS, X-Frame-Options) applied to all responses
- You are implementing geo-based redirects or A/B testing through URL rewriting
Use it also when:
- You need to compose multiple middleware concerns (auth + rate limit + CORS) in a single file
- You want to set up middleware with proper TypeScript types and path matching
Quick Start
# .claude/commands/nextjs-middleware-streamlined.md name: nextjs-middleware-streamlined description: Create composable Next.js middleware arguments: type: auth | rate-limit | cors | security | redirect | full
# Generate full middleware with all features claude nextjs-middleware-streamlined "full"
Expected output:
Middleware generated:
middleware.ts (main composition file)
lib/middleware/
auth.ts (JWT/session authentication)
rateLimit.ts (token bucket rate limiter)
cors.ts (CORS policy handler)
security.ts (security headers)
redirects.ts (redirect rules engine)
types.ts (TypeScript definitions)
Route matcher: /api/:path*, /dashboard/:path*
Core Concepts
| Concept | Description |
|---|---|
| Middleware Composition | Chaining multiple middleware functions in sequence |
| Route Matcher | Config export that defines which paths trigger middleware |
| Edge Runtime | Middleware runs at the edge, before the request reaches your app |
| Security Headers | HTTP headers that protect against common web vulnerabilities |
| Rate Limiter | Token bucket or sliding window algorithm to throttle requests |
Middleware Execution Order:
Request āā> Security Headers āā> Rate Limit Check
ā
āāāāāāāā PASS āāāāāāāāā
v v
Auth Check CORS Headers
ā ā
v v
Route Handler āā> Response to Client
Configuration
| Parameter | Default | Description |
|---|---|---|
type | full | Middleware type: auth, rate-limit, cors, security, redirect, full |
auth-strategy | jwt | Authentication method: jwt, session, nextauth |
rate-limit | 100/min | Rate limit threshold per IP |
cors-origins | ["*"] | Allowed CORS origins array |
protected-paths | ["/api/*", "/dashboard/*"] | Paths requiring authentication |
Best Practices
-
Apply security headers first in the chain -- Security headers should be set before any other processing to ensure they are present even on error responses.
-
Use the matcher config to limit middleware scope -- Not every request needs middleware. Use the
config.matcherexport to target only relevant paths. -
Keep middleware lightweight -- Middleware runs on every matched request at the edge. Avoid heavy computations, database queries, or large imports.
-
Use environment variables for sensitive config -- Store JWT secrets, rate limit thresholds, and CORS origins in environment variables, not hardcoded in middleware.
-
Test middleware in isolation -- Each middleware module in
lib/middleware/can be tested independently with mock NextRequest objects.
Common Issues
-
Middleware runs on static assets -- Without a
matcherconfig, middleware runs on every request including images and CSS. Add a matcher to exclude/_next/staticand/favicon.ico. -
Rate limiter resets on deployment -- In-memory rate limit counters reset on every Vercel deployment. Use external storage (Redis, KV) for persistent rate limiting.
-
CORS preflight requests blocked -- OPTIONS requests need explicit handling in middleware. Return early with CORS headers for
OPTIONSmethod before applying auth checks.
Reviews
No reviews yet. Be the first to review this template!
Similar Templates
Git Commit Message Generator
Generates well-structured conventional commit messages by analyzing staged changes. Follows Conventional Commits spec with scope detection.
React Component Scaffolder
Scaffolds a complete React component with TypeScript types, Tailwind styles, Storybook stories, and unit tests. Follows project conventions automatically.
CI/CD Pipeline Generator
Generates GitHub Actions workflows for CI/CD including linting, testing, building, and deploying. Detects project stack automatically.