Skip to main content

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:
  1. Request Middleware - Runs for all requests (pages and API routes)
  2. 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:
Access send context on 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

  1. Keep Middleware Focused
    • Each middleware should do one thing well
    • Compose multiple middleware for complex scenarios
  2. Handle Errors Properly
    • Always catch and handle errors in middleware
    • Provide meaningful error responses
  3. Be Careful with Context
    • Only add necessary data to context
    • Avoid large objects that need serialization
  4. Order Matters
    • Place authentication/validation middleware first
    • Put logging/monitoring middleware early
    • Error handlers should be at the start of the chain
  5. Type Your Context
    • Use TypeScript to type context additions
    • Leverage type inference for better DX
  6. Performance Considerations
    • Avoid expensive operations in middleware
    • Cache results when possible
    • Use async operations wisely
  7. Security First
    • Validate all inputs
    • Sanitize data before adding to context
    • Use proper authentication and authorization

Next Steps