N

Nextjs Middleware Streamlined

Battle-tested command for create, optimized, next, middleware. Includes structured workflows, validation checks, and reusable patterns for nextjs vercel.

CommandClipticsnextjs vercelv1.0.0MIT
0 views0 copies

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

ConceptDescription
Middleware CompositionChaining multiple middleware functions in sequence
Route MatcherConfig export that defines which paths trigger middleware
Edge RuntimeMiddleware runs at the edge, before the request reaches your app
Security HeadersHTTP headers that protect against common web vulnerabilities
Rate LimiterToken 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

ParameterDefaultDescription
typefullMiddleware type: auth, rate-limit, cors, security, redirect, full
auth-strategyjwtAuthentication method: jwt, session, nextauth
rate-limit100/minRate limit threshold per IP
cors-origins["*"]Allowed CORS origins array
protected-paths["/api/*", "/dashboard/*"]Paths requiring authentication

Best Practices

  1. 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.

  2. Use the matcher config to limit middleware scope -- Not every request needs middleware. Use the config.matcher export to target only relevant paths.

  3. Keep middleware lightweight -- Middleware runs on every matched request at the edge. Avoid heavy computations, database queries, or large imports.

  4. Use environment variables for sensitive config -- Store JWT secrets, rate limit thresholds, and CORS origins in environment variables, not hardcoded in middleware.

  5. Test middleware in isolation -- Each middleware module in lib/middleware/ can be tested independently with mock NextRequest objects.

Common Issues

  1. Middleware runs on static assets -- Without a matcher config, middleware runs on every request including images and CSS. Add a matcher to exclude /_next/static and /favicon.ico.

  2. Rate limiter resets on deployment -- In-memory rate limit counters reset on every Vercel deployment. Use external storage (Redis, KV) for persistent rate limiting.

  3. CORS preflight requests blocked -- OPTIONS requests need explicit handling in middleware. Return early with CORS headers for OPTIONS method before applying auth checks.

Community

Reviews

Write a review

No reviews yet. Be the first to review this template!

Similar Templates