Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

middleware.md

896 lines29.8 KB

1---
2id: middleware
3title: Middleware
4---
5​
6## What is Middleware?
7​
8Middleware allows you to customize the behavior of both server routes like GET/POST/etc (including requests to SSR your application) and server functions created with `createServerFn`. Middleware is composable and can even depend on other middleware to create a chain of operations that are executed hierarchically and in order.
9​
10### What kinds of things can I do with Middleware?
11​
12- **Authentication**: Verify a user's identity before executing a server function.
13- **Authorization**: Check if a user has the necessary permissions to execute a server function.
14- **Logging**: Log requests, responses, and errors.
15- **CSP**: Configure Content Security Policy and other security measures.
16- **Observability**: Collect metrics, traces, and logs.
17- **Provide Context**: Attach data to the request object for use in other middleware or server functions.
18- **Error Handling**: Handle errors in a consistent way.
19- And many more! The possibilities are up to you!
20​
21## Middleware Types
22​
23There are two types of middleware: **request middleware** and **server function middleware**.
24​
25- **Request middleware** is used to customize the behavior of any server request that passes through it, including server functions.
26- **Server function middleware** is used to customize the behavior of server functions specifically.
27​
28> [!NOTE]
29> Server function middleware is a subset of request middleware that has extra functionality specifically for server functions like being able to validate input data or perform client-side logic both before and after the server function is executed.
30​
31### Key Differences
32​
33| Feature | Request Middleware | Server Function Middleware |
34| ----------------- | -------------------------------- | -------------------------- |
35| Scope | All server requests | Server functions only |
36| Methods | `.server()` | `.client()`, `.server()` |
37| Input Validation | No | Yes (`.validator()`) |
38| Client-side Logic | No | Yes |
39| Dependencies | Can depend on request middleware | Can depend on both types |
40​
41> [!NOTE]
42> Request middleware cannot depend on server function middleware, but server function middleware can depend on request middleware.
43​
44## Core Concepts
45​
46### Middleware Composition
47​
48All middleware is composable, which means that one middleware can depend on another middleware.
49​
50```tsx
51import { createMiddleware } from '@tanstack/react-start'
52​
53const loggingMiddleware = createMiddleware().server(() => {
54 //...
55})
56​
57const authMiddleware = createMiddleware()
58 .middleware([loggingMiddleware])
59 .server(() => {
60 //...
61 })
62```
63​
64### Progressing the Middleware Chain
65​
66Middleware is next-able, which means that you must call the `next` function in the `.server` method (and/or `.client` method if you are creating a server function middleware) to execute the next middleware in the chain. This allows you to:
67​
68- Short circuit the middleware chain and return early
69- Pass data to the next middleware
70- Access the result of the next middleware
71- Pass context to the wrapping middleware
72​
73```tsx
74import { createMiddleware } from '@tanstack/react-start'
75​
76const loggingMiddleware = createMiddleware().server(async ({ next }) => {
77 const result = await next() // <-- This will execute the next middleware in the chain
78 return result
79})
80```
81​
82## Request Middleware
83​
84Request middleware is used to customize the behavior of any server request that passes through it, including server routes, SSR and server functions.
85​
86To create a request middleware, call the `createMiddleware` function. You may call this function with the `type` property set to 'request', but this is the default value so you can omit it if you'd like.
87​
88```tsx
89import { createMiddleware } from '@tanstack/react-start'
90​
91const loggingMiddleware = createMiddleware().server(() => {
92 //...
93})
94```
95​
96### Available Methods
97​
98Request middleware has the following methods:
99​
100- `middleware`: Add a middleware to the chain.
101- `server`: Define server-side logic that the middleware will execute before any nested middleware and ultimately a server function, and also provide the result to the next middleware.
102​
103### The `.server` method
104​
105The `.server` method is used to define server-side logic that the middleware will execute before any nested middleware, and also provide the result to the next middleware. It receives the `next` method and other things like context and the request object:
106​
107```tsx
108import { createMiddleware } from '@tanstack/react-start'
109​
110const loggingMiddleware = createMiddleware().server(
111 ({ next, context, request }) => {
112 return next()
113 },
115```
116​
117To quickly visualize this handshake, here is a diagram:
118​
119```mermaid
120sequenceDiagram
121 HTTP ->> Middleware.server: Request
122 Middleware.server ->> Middleware.server: next()
123 Middleware.server ->> ServerFn: payload
124 ServerFn ->> Middleware.server: result
125 Middleware.server ->> Middleware.server: return
126 Middleware.server ->> HTTP: Response
127​
128 box Server
129 participant Middleware.server
130 participant ServerFn
131 end
132```
133​
134### Using Request Middleware with Server Routes
135​
136You can use request middleware with server routes in two ways:
137​
138#### All Server Route Methods
139​
140To have a server route use middleware for all methods, pass a middleware array to the `middleware` property of the method builder object.
141​
142```tsx
143import { createMiddleware } from '@tanstack/react-start'
144​
145const loggingMiddleware = createMiddleware().server(() => {
146 //...
147})
148​
149export const Route = createFileRoute('/foo')({
150 server: {
151 middleware: [loggingMiddleware],
152 handlers: {
153 GET: () => {
154 //...
155 },
156 POST: () => {
157 //...
158 },
159 },
160 },
161})
162```
163​
164#### Specific Server Route Methods
165​
166You can pass middleware to specific server route methods by using the `createHandlers` utility and passing a middleware array to the `middleware` property of the method object.
167​
168```tsx
169import { createMiddleware } from '@tanstack/react-start'
170​
171const loggingMiddleware = createMiddleware().server(() => {
172 //...
173})
174​
175export const Route = createFileRoute('/foo')({
176 server: {
177 handlers: ({ createHandlers }) =>
178 createHandlers({
179 GET: {
180 middleware: [loggingMiddleware],
181 handler: () => {
182 //...
183 },
184 },
185 }),
186 },
187})
188```
189​
190## Server Function Middleware
191​
192Server function middleware is a **subset** of request middleware that has extra functionality specifically for server functions like being able to validate input data or perform client-side logic both before and after the server function is executed.
193​
194To create a server function middleware, call the `createMiddleware` function with the `type` property set to 'function'.
195​
196```tsx
197import { createMiddleware } from '@tanstack/react-start'
198​
199const loggingMiddleware = createMiddleware({ type: 'function' })
200 .client(() => {
201 //...
202 })
203 .server(() => {
204 //...
205 })
206```
207​
208### Available Methods
209​
210Server function middleware has the following methods:
211​
212- `middleware`: Add a middleware to the chain.
213- `validator`: Modify the data object before it is passed to this middleware and any nested middleware and eventually the server function.
214- `client`: Define client-side logic that the middleware will execute on the client before (and after) the server function calls into the server to execute the function.
215- `server`: Define server-side logic that the middleware will execute on the server before (and after) the server function is executed.
216​
217> [!NOTE]
218> If you are (hopefully) using TypeScript, the order of these methods is enforced by the type system to ensure maximum inference and type safety.
219​
220### The `.client` method
221​
222The `.client` method is used to define client-side logic that the middleware will wrap the execution and result of the RPC call to the server.
223​
224```tsx
225import { createMiddleware } from '@tanstack/react-start'
226​
227const loggingMiddleware = createMiddleware({ type: 'function' }).client(
228 async ({ next, context }) => {
229 const result = await next() // <-- This will execute the next middleware in the chain and eventually, the RPC to the server
230 return result
231 },
233```
234​
235### The `.validator` method
236​
237The `validator` method is used to modify the data object before it is passed to this middleware, nested middleware, and ultimately the server function. This method should receive a function that takes the data object and returns a validated (and optionally modified) data object. It's common to use a validation library like `zod` to do this.
238​
239```tsx
240import { createMiddleware } from '@tanstack/react-start'
241import { zodValidator } from '@tanstack/zod-adapter'
242import { z } from 'zod'
243​
244const mySchema = z.object({
245 workspaceId: z.string(),
246})
247​
248const workspaceMiddleware = createMiddleware({ type: 'function' })
249 .validator(zodValidator(mySchema))
250 .server(({ next, data }) => {
251 console.log('Workspace ID:', data.workspaceId)
252 return next()
253 })
254```
255​
256### Using Server Function Middleware
257​
258To have a middleware wrap a specific server function, you can pass a middleware array to the `middleware` property of the `createServerFn` function.
259​
260```tsx
261import { createServerFn } from '@tanstack/react-start'
262import { loggingMiddleware } from './middleware'
263​
264const fn = createServerFn()
265 .middleware([loggingMiddleware])
266 .handler(async () => {
267 //...
268 })
269```
270​
271To quickly visualize this handshake, here is a diagram:
272​
273```mermaid
274sequenceDiagram
275 ServerFn (client) ->> Middleware.client: payload
276 Middleware.client ->> Middleware.client: next()
277 Middleware.client ->> Middleware.server: Request
278 Middleware.server ->> Middleware.server: next()
279 Middleware.server ->> ServerFn: payload
280 ServerFn ->> Middleware.server: result
281 Middleware.server ->> Middleware.server: return
282 Middleware.server ->> Middleware.client: Response
283 Middleware.client ->> Middleware.client: return
284 Middleware.client ->> ServerFn (client): result
285​
286 box Client
287 participant ServerFn (client)
288 participant Middleware.client
289 end
290​
291 box Server
292 participant Middleware.server
293 participant ServerFn
294 end
295```
296​
297## Context Management
298​
299### Providing Context via `next`
300​
301The `next` function can be optionally called with an object that has a `context` property with an object value. Whatever properties you pass to this `context` value will be merged into the parent `context` and provided to the next middleware.
302​
303```tsx
304import { createMiddleware } from '@tanstack/react-start'
305​
306const awesomeMiddleware = createMiddleware({ type: 'function' }).server(
307 ({ next }) => {
308 return next({
309 context: {
310 isAwesome: Math.random() > 0.5,
311 },
312 })
313 },
315​
316const loggingMiddleware = createMiddleware({ type: 'function' })
317 .middleware([awesomeMiddleware])
318 .server(async ({ next, context }) => {
319 console.log('Is awesome?', context.isAwesome)
320 return next()
321 })
322```
323​
324### Sending Client Context to the Server
325​
326**Client context is NOT sent to the server by default since this could end up unintentionally sending large payloads to the server.** If you need to send client context to the server, you must call the `next` function with a `sendContext` property and object to transmit any data to the server. Any properties passed to `sendContext` will be merged, serialized and sent to the server along with the data and will be available on the normal context object of any nested server middleware.
327​
328```tsx
329import { createMiddleware } from '@tanstack/react-start'
330​
331const requestLogger = createMiddleware({ type: 'function' })
332 .client(async ({ next, context }) => {
333 return next({
334 sendContext: {
335 // Send the workspace ID to the server
336 workspaceId: context.workspaceId,
337 },
338 })
339 })
340 .server(async ({ next, data, context }) => {
341 // Woah! We have the workspace ID from the client!
342 console.log('Workspace ID:', context.workspaceId)
343 return next()
344 })
345```
346​
347#### Client-Sent Context Security
348​
349You may have noticed that in the example above while client-sent context is type-safe, it is not required to be validated at runtime. If you pass dynamic user-generated data via context, that could pose a security concern, so **if you are sending dynamic data from the client to the server via context, you should validate it in the server-side middleware before using it.**
350​
351> **Shape validation is not authorization.** A parsed UUID/number is a _well-formed_ identifier, not an _authorized_ one. If the value is going to be used as a query key, filter, or path parameter β€” anything that selects which row(s) get read or written β€” you must also verify the session principal has access to it. Otherwise a logged-in user can rewrite the value in their own request and walk other tenants' data.
352​
353```tsx
354import { createMiddleware } from '@tanstack/react-start'
355import { z } from 'zod'
356​
357const requestLogger = createMiddleware({ type: 'function' })
358 .client(async ({ next, context }) => {
359 return next({
360 sendContext: {
361 workspaceId: context.workspaceId,
362 },
363 })
364 })
365 .middleware([authMiddleware]) // session loaded server-side, NOT from sendContext
366 .server(async ({ next, context }) => {
367 // 1. Validate shape
368 const workspaceId = z.string().uuid().parse(context.workspaceId)
369 // 2. Validate access β€” does this session principal have membership?
370 const member = await db.memberships.find({
371 userId: context.session.userId,
372 workspaceId,
373 })
374 if (!member) throw new Error('Not a member of this workspace')
375 // 3. Now safe to use as a query key.
376 return next({ context: { workspaceId } })
377 })
378```
379​
380Always derive the session itself from a server-trusted source (a cookie + DB lookup in `authMiddleware`), never from `sendContext`. Anything the client can send, the client can lie about.
381​
382### Sending Server Context to the Client
383​
384Similar to sending client context to the server, you can also send server context to the client by calling the `next` function with a `sendContext` property and object to transmit any data to the client. Any properties passed to `sendContext` will be merged, serialized and sent to the client along with the response and will be available on the normal context object of any nested client middleware. The returned object of calling `next` in `client` contains the context sent from server to the client and is type-safe.
385​
386> [!WARNING]
387> The return type of `next` in `client` can only be inferred from middleware known in the current middleware chain. Therefore the most accurate return type of `next` is in middleware at the end of the middleware chain
388​
389```tsx
390import { createMiddleware } from '@tanstack/react-start'
391​
392const serverTimer = createMiddleware({ type: 'function' }).server(
393 async ({ next }) => {
394 return next({
395 sendContext: {
396 // Send the current time to the client
397 timeFromServer: new Date(),
398 },
399 })
400 },
402​
403const requestLogger = createMiddleware({ type: 'function' })
404 .middleware([serverTimer])
405 .client(async ({ next }) => {
406 const result = await next()
407 // Woah! We have the time from the server!
408 console.log('Time from the server:', result.context.timeFromServer)
409​
410 return result
411 })
412```
413​
414## Global Middleware
415​
416Global middleware runs automatically for every request in your application. This is useful for functionality like authentication, logging, and monitoring that should apply to all requests.
417​
418> [!NOTE]
419> The `src/start.ts` file is not included in the default TanStack Start template. You'll need to create this file when you want to configure global middleware or other Start-level options.
420​
421### Global Request Middleware
422​
423To have a middleware run for **every request handled by Start**, create a `src/start.ts` file and use the `createStart` function to return your middleware configuration:
424​
425```tsx
426// src/start.ts
427import { createStart, createMiddleware } from '@tanstack/react-start'
428​
429const myGlobalMiddleware = createMiddleware().server(() => {
430 //...
431})
432​
433export const startInstance = createStart(() => {
434 return {
435 requestMiddleware: [myGlobalMiddleware],
436 }
437})
438```
439​
440> [!NOTE]
441> Global **request** middleware runs before **every request, including server routes, SSR and server functions**.
442​
443### CSRF Middleware
444​
445Server functions are same-origin RPC endpoints and should be protected from cross-site requests. If your app does not define `src/start.ts`, TanStack Start installs its CSRF middleware automatically for server functions.
446​
447If you define a custom `src/start.ts`, add `createCsrfMiddleware()` explicitly:
448​
449```tsx
450// src/start.ts
451import { createStart, createCsrfMiddleware } from '@tanstack/react-start'
452​
453const csrfMiddleware = createCsrfMiddleware({
454 filter: (ctx) => ctx.handlerType === 'serverFn',
455})
456​
457export const startInstance = createStart(() => ({
458 requestMiddleware: [csrfMiddleware],
459}))
460```
461​
462By default, `Origin` and `Referer` checks compare against the incoming request URL origin. If your deployment needs to allow a different public origin, configure it on the CSRF middleware with `createCsrfMiddleware({ origin: 'https://app.example.com' })`.
463​
464By default, `createCsrfMiddleware()` validates every request handled by the middleware. Use `filter: (ctx) => ctx.handlerType === 'serverFn'` when installing it globally for server function protection. It verifies same-origin browser request metadata with `Sec-Fetch-Site`, `Origin`, or `Referer` headers and rejects requests that cannot be proven same-origin.
465​
466You can also use the same middleware to protect any other route.
467​
468```tsx
469export const Route = createFileRoute('/api/foo')({
470 server: {
471 middleware: [createCsrfMiddleware()],
472 handlers: { GET: () => {...} }
473 }
474})
475```
476​
477If you define `src/start.ts` without the CSRF middleware, Start shows a development warning for server function requests. If you intentionally handle CSRF another way, disable the warning:
478​
479```tsx
480// vite.config.ts or rsbuild.config.ts
481tanstackStart({
482 serverFns: {
483 disableCsrfMiddlewareWarning: true,
484 },
485})
486```
487​
488### Global Server Function Middleware
489​
490To have a middleware run for **every server function in your application**, add it to the `functionMiddleware` array in your `src/start.ts` file:
491​
492```tsx
493// src/start.ts
494import { createStart } from '@tanstack/react-start'
495import { loggingMiddleware } from './middleware'
496​
497export const startInstance = createStart(() => {
498 return {
499 functionMiddleware: [loggingMiddleware],
500 }
501})
502```
503​
504### Middleware Execution Order
505​
506Middleware is executed dependency-first, starting with global middleware, followed by server function middleware. The following example will log in this order:
507​
508- `globalMiddleware1`
509- `globalMiddleware2`
510- `a`
511- `b`
512- `c`
513- `d`
514- `fn`
515​
516```tsx
517import { createMiddleware, createServerFn } from '@tanstack/react-start'
518​
519const globalMiddleware1 = createMiddleware({ type: 'function' }).server(
520 async ({ next }) => {
521 console.log('globalMiddleware1')
522 return next()
523 },
525​
526const globalMiddleware2 = createMiddleware({ type: 'function' }).server(
527 async ({ next }) => {
528 console.log('globalMiddleware2')
529 return next()
530 },
532​
533const a = createMiddleware({ type: 'function' }).server(async ({ next }) => {
534 console.log('a')
535 return next()
536})
537​
538const b = createMiddleware({ type: 'function' })
539 .middleware([a])
540 .server(async ({ next }) => {
541 console.log('b')
542 return next()
543 })
544​
545const c = createMiddleware({ type: 'function' })
546 .middleware()
547 .server(async ({ next }) => {
548 console.log('c')
549 return next()
550 })
551​
552const d = createMiddleware({ type: 'function' })
553 .middleware([b, c])
554 .server(async () => {
555 console.log('d')
556 })
557​
558const fn = createServerFn()
559 .middleware([d])
560 .server(async () => {
561 console.log('fn')
562 })
563```
564​
565## Request and Response Modification
566​
567### Reading/Modifying the Server Response
568​
569Middleware that uses the `server` method executes in the same context as server functions, so you can follow the exact same [Server Function Context Utilities](./server-functions.md#server-function-context) to read and modify anything about the request headers, status codes, etc.
570​
571### Modifying the Client Request
572​
573Middleware that uses the `client` method executes in a **completely different client-side context** than server functions, so you can't use the same utilities to read and modify the request. However, you can still modify the request by returning additional properties when calling the `next` function.
574​
575#### Setting Custom Headers
576​
577You can add headers to the outgoing request by passing a `headers` object to `next`:
578​
579```tsx
580import { createMiddleware } from '@tanstack/react-start'
581import { getToken } from 'my-auth-library'
582​
583const authMiddleware = createMiddleware({ type: 'function' }).client(
584 async ({ next }) => {
585 return next({
586 headers: {
587 Authorization: `Bearer ${getToken()}`,
588 },
589 })
590 },
592```
593​
594#### Header Merging Across Middleware
595​
596When multiple middlewares set headers, they are **merged together**. Later middlewares can add new headers or override headers set by earlier middlewares:
597​
598```tsx
599import { createMiddleware } from '@tanstack/react-start'
600​
601const firstMiddleware = createMiddleware({ type: 'function' }).client(
602 async ({ next }) => {
603 return next({
604 headers: {
605 'X-Request-ID': '12345',
606 'X-Source': 'first-middleware',
607 },
608 })
609 },
611​
612const secondMiddleware = createMiddleware({ type: 'function' }).client(
613 async ({ next }) => {
614 return next({
615 headers: {
616 'X-Timestamp': Date.now().toString(),
617 'X-Source': 'second-middleware', // Overrides first middleware
618 },
619 })
620 },
622​
623// Final headers will include:
624// - X-Request-ID: '12345' (from first)
625// - X-Timestamp: '<timestamp>' (from second)
626// - X-Source: 'second-middleware' (second overrides first)
627```
628​
629You can also set headers directly at the call site:
630​
631```tsx
632await myServerFn({
633 data: { name: 'John' },
634 headers: {
635 'X-Custom-Header': 'call-site-value',
636 },
637})
638```
639​
640**Header precedence (all headers are merged, later values override earlier):**
641​
6421. Earlier middleware headers
6432. Later middleware headers (override earlier)
6443. Call-site headers (override all middleware headers)
645​
646#### Custom Fetch Implementation
647​
648For advanced use cases, you can provide a custom `fetch` implementation to control how server function requests are made. This is useful for:
649​
650- Adding request interceptors or retry logic
651- Using a custom HTTP client
652- Testing and mocking
653- Adding telemetry or monitoring
654​
655**Via Client Middleware:**
656​
657```tsx
658import { createMiddleware } from '@tanstack/react-start'
659import type { CustomFetch } from '@tanstack/react-start'
660​
661const customFetchMiddleware = createMiddleware({ type: 'function' }).client(
662 async ({ next }) => {
663 const customFetch: CustomFetch = async (url, init) => {
664 console.log('Request starting:', url)
665 const start = Date.now()
666​
667 const response = await fetch(url, init)
668​
669 console.log('Request completed in', Date.now() - start, 'ms')
670 return response
671 }
672​
673 return next({ fetch: customFetch })
674 },
676```
677​
678**Directly at Call Site:**
679​
680```tsx
681import type { CustomFetch } from '@tanstack/react-start'
682​
683const myFetch: CustomFetch = async (url, init) => {
684 // Add custom logic here
685 return fetch(url, init)
687​
688await myServerFn({
689 data: { name: 'John' },
690 fetch: myFetch,
691})
692```
693​
694#### Fetch Override Precedence
695​
696When custom fetch implementations are provided at multiple levels, the following precedence applies (highest to lowest priority):
697​
698| Priority | Source | Description |
699| ----------- | ------------------ | ---------------------------------------------------- |
700| 1 (highest) | Call site | `serverFn({ fetch: customFetch })` |
701| 2 | Later middleware | Last middleware in chain that provides `fetch` |
702| 3 | Earlier middleware | First middleware in chain that provides `fetch` |
703| 4 | createStart | `createStart({ serverFns: { fetch: customFetch } })` |
704| 5 (lowest) | Default | Global `fetch` function |
705​
706**Key principle:** The call site always wins. This allows you to override middleware behavior for specific calls when needed.
707​
708```tsx
709import { createMiddleware, createServerFn } from '@tanstack/react-start'
710import type { CustomFetch } from '@tanstack/react-start'
711​
712// Middleware sets a fetch that adds logging
713const loggingMiddleware = createMiddleware({ type: 'function' }).client(
714 async ({ next }) => {
715 const loggingFetch: CustomFetch = async (url, init) => {
716 console.log('Middleware fetch:', url)
717 return fetch(url, init)
718 }
719 return next({ fetch: loggingFetch })
720 },
722​
723const myServerFn = createServerFn()
724 .middleware([loggingMiddleware])
725 .handler(async () => {
726 return { message: 'Hello' }
727 })
728​
729// Uses middleware's loggingFetch
730await myServerFn()
731​
732// Override with custom fetch for this specific call
733const testFetch: CustomFetch = async (url, init) => {
734 console.log('Test fetch:', url)
735 return fetch(url, init)
737await myServerFn({ fetch: testFetch }) // Uses testFetch, NOT loggingFetch
738```
739​
740**Chained Middleware Example:**
741​
742When multiple middlewares provide fetch, the last one wins:
743​
744```tsx
745import { createMiddleware, createServerFn } from '@tanstack/react-start'
746import type { CustomFetch } from '@tanstack/react-start'
747​
748const firstMiddleware = createMiddleware({ type: 'function' }).client(
749 async ({ next }) => {
750 const firstFetch: CustomFetch = (url, init) => {
751 const headers = new Headers(init?.headers)
752 headers.set('X-From', 'first-middleware')
753 return fetch(url, { ...init, headers })
754 }
755 return next({ fetch: firstFetch })
756 },
758​
759const secondMiddleware = createMiddleware({ type: 'function' }).client(
760 async ({ next }) => {
761 const secondFetch: CustomFetch = (url, init) => {
762 const headers = new Headers(init?.headers)
763 headers.set('X-From', 'second-middleware')
764 return fetch(url, { ...init, headers })
765 }
766 return next({ fetch: secondFetch })
767 },
769​
770const myServerFn = createServerFn()
771 .middleware([firstMiddleware, secondMiddleware])
772 .handler(async () => {
773 // Request will have X-From: 'second-middleware'
774 // because secondMiddleware's fetch overrides firstMiddleware's fetch
775 return { message: 'Hello' }
776 })
777```
778​
779**Global Fetch via createStart:**
780​
781You can set a default custom fetch for all server functions in your application by providing `serverFns.fetch` in `createStart`. This is useful for adding global request interceptors, retry logic, or telemetry:
782​
783```tsx
784// src/start.ts
785import { createStart } from '@tanstack/react-start'
786import type { CustomFetch } from '@tanstack/react-start'
787​
788const globalFetch: CustomFetch = async (url, init) => {
789 console.log('Global fetch:', url)
790 // Add retry logic, telemetry, etc.
791 return fetch(url, init)
793​
794export const startInstance = createStart(() => {
795 return {
796 serverFns: {
797 fetch: globalFetch,
798 },
799 }
800})
801```
802​
803This global fetch has lower priority than middleware and call-site fetch, so you can still override it for specific server functions or calls when needed.
804​
805> [!NOTE]
806> Custom fetch only applies on the client side. During SSR, server functions are called directly without going through fetch.
807​
808## Environment and Performance
809​
810### Environment Tree Shaking
811​
812Middleware functionality is tree-shaken based on the environment for each bundle produced.
813​
814- On the server, nothing is tree-shaken, so all code used in middleware will be included in the server bundle.
815- On the client, all server-specific code is removed from the client bundle. This means any code used in the `server` method is always removed from the client bundle. `data` validation code will also be removed.
816​
817## Middleware Factories
818​
819Static middlewares are created once and reused across routes. A middleware factory wraps that creation in a function, allowing it to accept parameters and behave differently depending on the caller's needs. Authorization is a common use case.
820​
821**Authentication (Static Base Middleware) Example:**
822​
823This middleware validates the session and injects it into `context` for downstream middlewares.
824​
825> **Attach `authMiddleware` to every `createServerFn` that needs auth.** Server functions are API endpoints, so protect the endpoint that reads or mutates private data. A route `beforeLoad` guard improves route UX, but it is not the data boundary. See [Authentication Server Primitives](./authentication-server-primitives.md).
826​
827```tsx
828// middleware.ts
829import { createMiddleware } from '@tanstack/react-start'
830import { auth } from './my-auth'
831​
832export const authMiddleware = createMiddleware().server(
833 async ({ next, request }) => {
834 const session = await auth.getSession({ headers: request.headers })
835​
836 if (!session) {
837 throw new Error('Unauthorized')
838 }
839​
840 return await next({
841 context: { session },
842 })
843 },
845```
846​
847**Authorization (Middleware Factory) Example:**
848​
849The middleware validates access based on the dynamic `permissions` parameter, composing with `authMiddleware` so `context.session` is already available.
850​
851```tsx
852// middleware.ts
853import { createMiddleware } from '@tanstack/react-start'
854import { auth } from './my-auth'
855​
856export const authMiddleware = createMiddleware().server(
857 async ({ next, request }) => {
858 // ... (implementation from authentication example above)
859 },
861​
862type Permissions = Record<string, string[]>
863​
864export function authorizationMiddleware(permissions: Permissions) {
865 return createMiddleware({ type: 'function' })
866 .middleware([authMiddleware])
867 .server(async ({ next, context }) => {
868 const granted = await auth.hasPermission(context.session, permissions)
869​
870 if (!granted) {
871 throw new Error('Forbidden')
872 }
873​
874 return await next()
875 })
877```
878​
879**Usage in a Server Function:**
880​
881Access requirements are defined per server function, without duplicating any middleware logic.
882​
883```tsx
884import { createServerFn } from '@tanstack/react-start'
885import { authorizationMiddleware } from './middleware'
886​
887export const getClients = createServerFn()
888 .middleware([
889 authorizationMiddleware({
890 client: ['read'],
891 }),
892 ])
893 .handler(async ({ context }) => {
894 return { message: 'The user can read clients.' }
895 })
896```