Open History to see the last commit
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 },
114)
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 },
232)
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 },
314)
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 },
401)
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 },
524)
525β
526const globalMiddleware2 = createMiddleware({ type: 'function' }).server(
527 async ({ next }) => {
528 console.log('globalMiddleware2')
529 return next()
530 },
531)
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 },
591)
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 },
610)
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 },
621)
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 },
675)
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)
686}
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 },
721)
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)
736}
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 },
757)
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 },
768)
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)
792}
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 },
844)
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 },
860)
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 })
876}
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```