Middleware
Middleware functions in React Router allow you to run code before your route loaders and actions execute, enabling authentication, authorization, logging, and more.Enable Middleware
Middleware is a future flag that must be enabled inreact-router.config.ts:
Route Middleware
Define middleware in route modules:Middleware Execution Order
Middleware executes in route hierarchy order, from parent to child:Middleware Return Values
Middleware can return data that gets merged into the context:Client Middleware
Client-side middleware runs before client loaders and actions:Middleware Arguments
Middleware functions receive these arguments:request
The Web Fetch API Request object:
params
Route parameters from the URL:
context
Server context plus parent middleware data:
Throwing Responses
Middleware can throw responses to short-circuit execution:Common Use Cases
Authentication
Authorization
Logging
Feature Flags
Rate Limiting
Middleware vs. Loaders
Use middleware for:- Authentication and authorization
- Request validation
- Logging and analytics
- Setting up shared context
- Rate limiting
- Fetching data to render
- Database queries
- API calls
- Business logic specific to the route
TypeScript Types
With type generation enabled:Server-Only Middleware
Server middleware exports are automatically removed from client bundles:Caveats
- Middleware runs for every request - Keep it fast
- Middleware blocks rendering - Avoid heavy computation
- Context is merged - Avoid key conflicts between parent/child middleware
- Throwing ends execution - No subsequent middleware/loaders run
- Client middleware is different - Runs separately from server middleware