Middleware
Middleware in TanStack Start enables you to compose reusable logic for authentication, logging, validation, and more. Middleware runs on both request-level (for routes) and function-level (for server functions).What is Middleware?
Middleware is composable logic that runs before your route handlers or server functions. It can:- Authenticate users: Verify sessions and tokens
- Transform data: Validate and sanitize inputs
- Modify context: Add data available to downstream handlers
- Control flow: Short-circuit execution with responses
- Log and monitor: Track requests and performance
Types of Middleware
TanStack Start has two types of middleware:- Request Middleware: Runs for every request to a route
- Function Middleware: Runs for server function calls
Creating Middleware
Middleware Context
Pass data between middleware and handlers:Composing Middleware
Chain multiple middleware together:Route Middleware Patterns
Middleware for API Routes
Apply middleware to server route handlers:Global Request Middleware
Apply middleware to all requests:Input Validation Middleware
Validate and transform input data:Client-Side Middleware
Run middleware on the client before sending requests:Error Handling in Middleware
Handle errors gracefully:Conditional Middleware
Run middleware based on conditions:Response Modification
Modify responses in middleware:Testing Middleware
Test middleware in isolation:Best Practices
- Keep middleware focused: Each middleware should do one thing well
- Order matters: Place authentication before authorization
- Use types: Leverage TypeScript for context typing
- Handle errors: Always implement error handling
- Avoid side effects: Keep middleware pure when possible
- Test thoroughly: Unit test middleware in isolation
- Document context: Clearly document what context each middleware adds
- Compose wisely: Reuse middleware through composition