Skip to main content

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 in react-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
Use loaders for:
  • 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

  1. Middleware runs for every request - Keep it fast
  2. Middleware blocks rendering - Avoid heavy computation
  3. Context is merged - Avoid key conflicts between parent/child middleware
  4. Throwing ends execution - No subsequent middleware/loaders run
  5. Client middleware is different - Runs separately from server middleware

See Also