Middleware
Middleware in TanStack Start allows you to intercept and modify requests, responses, and context at both the request and function levels. Use middleware for authentication, logging, error handling, and more.Types of Middleware
TanStack Start supports two types of middleware:- Request Middleware - Runs for all requests (pages and API routes)
- Function Middleware - Runs for specific server functions
Request Middleware
Request middleware runs on every request before rendering or handling:Function Middleware
Function middleware runs specifically for server functions:Creating Middleware
Basic Middleware
Client + Server Middleware
Middleware Context
Adding Context
Middleware can add data to the context:Accessing Context
Access context in route handlers and server functions:Send Context
Send data back to the client:Common Middleware Patterns
Authentication
Rate Limiting
Request Logging
CORS Headers
Error Handling
Composing Middleware
Middleware Chains
Chain multiple middleware together:Reusable Middleware
Create reusable middleware for common patterns:API Route Middleware
Use middleware with API routes:Global Middleware
Apply middleware to all routes using the Start configuration:Input Validation Middleware
Validate inputs in middleware:Middleware Execution Order
Middleware executes in order:Best Practices
-
Keep Middleware Focused
- Each middleware should do one thing well
- Compose multiple middleware for complex scenarios
-
Handle Errors Properly
- Always catch and handle errors in middleware
- Provide meaningful error responses
-
Be Careful with Context
- Only add necessary data to context
- Avoid large objects that need serialization
-
Order Matters
- Place authentication/validation middleware first
- Put logging/monitoring middleware early
- Error handlers should be at the start of the chain
-
Type Your Context
- Use TypeScript to type context additions
- Leverage type inference for better DX
-
Performance Considerations
- Avoid expensive operations in middleware
- Cache results when possible
- Use async operations wisely
-
Security First
- Validate all inputs
- Sanitize data before adding to context
- Use proper authentication and authorization
Next Steps
- Learn about Server Functions
- Explore API Routes
- See Data Fetching strategies