---
id: start-middleware
track: learn
product: start
locale: en
order: 11
revision: 2
sourceCheckedOn: "2026-08-03"
versionRange: "Start ^1"
verifiedAgainst: "@tanstack/react-start@1.168.34"
contentModel: 2
prerequisites:
  - "Server Functions and Server Routes"
sourceRefs:
  - "https://tanstack.com/start/latest/docs/framework/react/guide/middleware"
  - "https://tanstack.com/start/latest/docs/framework/react/guide/server-functions"
---

# Compose request boundaries with Middleware

> Separate request middleware from Server Function middleware and compose logging, context, and security checks with next().

**Outcome:** Choose the right middleware scope, explain the execution chain, and avoid treating client-sent context as trusted authorization data.

## Choose the scope first

Request middleware can cover SSR, Server Routes, and Server Functions. Middleware with type: 'function' wraps Server Functions and additionally supports client phases and data validation. Put a rule in the narrowest scope that still covers the requirement.

## The chain advances only through next

Middleware can run before next(), add context for downstream code, and inspect the result after next() returns. Intentionally omitting next() short-circuits the chain; accidentally omitting it prevents the downstream handler from running.

> **Note:** Validate client-sent context on the server and establish identity again from a server-trusted source.

File: `src/server/timing-middleware.ts`

```ts
import { createMiddleware } from '@tanstack/react-start'

export const timingMiddleware = createMiddleware({ type: 'function' })
  .server(async ({ next }) => {
    const startedAt = performance.now()
    const result = await next()
    console.info('server function ms', performance.now() - startedAt)
    return result
  })
```

## Practice and verification

### Completion checkpoint

Request and function middleware have explicit scopes, and context flows in declared order.

### Exercise

Compose request-id and function-timing middleware, then read the id in a handler and emit structured logs.

### Verification

Send two concurrent requests; each should have an independent id and timing should cover the full handler chain.

### Common pitfalls

- Forgetting to return or await next().
- Storing request data in module-level mutable state.

## Official sources

- https://tanstack.com/start/latest/docs/framework/react/guide/middleware
- https://tanstack.com/start/latest/docs/framework/react/guide/server-functions
