Middleware Pattern
Request preprocessing using Next.js middleware for authentication, CORS, logging, rate limiting, and request validation across multiple routes.
What's Included#
- Authentication middleware with protected/public path configuration
- CORS middleware with origin allowlisting and preflight handling
- Request logging middleware with unique request IDs and timing
- Composable middleware chain pattern for combining multiple concerns
- API key validation middleware
- Request body validation middleware with Zod schema integration
Usage#
Via CLI#
Loading code block...
Via AI Assistant#
Ask your AI assistant:
- "Use the middleware pattern from Bootspring"
- "Apply the Bootspring middleware pattern to my project"
Key Considerations#
- Keep middleware fast since it runs on every matched request; avoid heavy computations
- Use config.matcher to restrict middleware to only the paths that need it
- Compose middleware into reusable functions for separation of concerns
- Add request IDs in middleware for debugging and distributed tracing
- Remember middleware runs at the edge, so not all Node.js APIs are available
- Log strategically with structured logging; avoid excessive logging that impacts performance
Related Patterns#
- Route Handler - API route implementation
- Rate Limiting - Protect APIs from abuse
- Error Handling - Consistent error responses
- Session Management - User session protection