@rsc-kit/mcp 0.40.0 → 0.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/dist/recipes.js +37 -20
  2. package/dist/recipes.js.map +1 -1
  3. package/guides/admin-plugins.md +206 -6
  4. package/guides/api-routes.md +159 -215
  5. package/guides/authorization.md +103 -114
  6. package/guides/backend-answered-pages.md +301 -250
  7. package/guides/bap-vs-inertia.md +67 -25
  8. package/guides/blueprints.md +307 -174
  9. package/guides/bun.md +42 -25
  10. package/guides/caching.md +46 -49
  11. package/guides/coming-from-inertia.md +5 -5
  12. package/guides/commands.md +251 -200
  13. package/guides/connection.md +50 -54
  14. package/guides/content-security-policy.md +133 -84
  15. package/guides/domains.md +190 -149
  16. package/guides/edge-caching.md +242 -268
  17. package/guides/emails.md +96 -45
  18. package/guides/errors.md +116 -137
  19. package/guides/feature-flags.md +100 -30
  20. package/guides/file-uploads.md +101 -26
  21. package/guides/fonts.md +139 -110
  22. package/guides/forms.md +520 -538
  23. package/guides/images.md +87 -28
  24. package/guides/index.json +13 -33
  25. package/guides/instrumentation.md +134 -95
  26. package/guides/isr.md +3 -3
  27. package/guides/live-data-in-production.md +695 -0
  28. package/guides/live-data.md +170 -839
  29. package/guides/mcp.md +83 -59
  30. package/guides/metadata.md +124 -179
  31. package/guides/navigation.md +118 -147
  32. package/guides/no-javascript.md +49 -57
  33. package/guides/offline.md +118 -153
  34. package/guides/openapi.md +100 -35
  35. package/guides/pages.md +160 -50
  36. package/guides/ppr.md +178 -256
  37. package/guides/pwa.md +251 -218
  38. package/guides/queries.md +171 -300
  39. package/guides/react-compiler.md +90 -50
  40. package/guides/redirects.md +141 -177
  41. package/guides/response-headers.md +76 -74
  42. package/guides/route-interception.md +112 -111
  43. package/guides/routing.md +216 -322
  44. package/guides/sections.md +63 -66
  45. package/guides/seo-files.md +127 -65
  46. package/guides/server-actions.md +285 -357
  47. package/guides/static-generation.md +131 -199
  48. package/guides/testing.md +272 -150
  49. package/guides/third-party-scripts.md +94 -47
  50. package/guides/typed-routes.md +115 -113
  51. package/guides/url-validation.md +113 -61
  52. package/guides/validation.md +53 -62
  53. package/guides/view-transitions.md +159 -132
  54. package/guides/where-it-runs.md +226 -162
  55. package/package.json +2 -2
  56. package/guides/admin.md +0 -520
  57. package/guides/deployment.md +0 -598
  58. package/guides/go.md +0 -538
  59. package/guides/laravel.md +0 -786
  60. package/guides/your-own-backend.md +0 -587
package/guides/queries.md CHANGED
@@ -2,11 +2,10 @@
2
2
 
3
3
  > Reading from the server over GET, and letting TanStack Query or SWR own everything above it.
4
4
 
5
- `query()` marks a server function as a read, so the call goes out as a GET
6
- instead of a POST. Your logs and rate limiters can then tell it apart from a
7
- mutation, and a cache can hold the answer.
5
+ A query is a server function that only reads. Wrap it in `query()` and the
6
+ browser calls it with a GET instead of a POST:
8
7
 
9
- ```ts title="src/listings.ts"
8
+ ```ts title="src/queries.ts"
10
9
  "use server"
11
10
 
12
11
  import { query } from "@rsc-kit/core/query"
@@ -16,81 +15,49 @@ export const getListings = query(async (kind: string) => {
16
15
  })
17
16
  ```
18
17
 
19
- That is the whole feature. There is no cache here, no batching and no
20
- deduplication: [TanStack Query](https://tanstack.com/query) and
21
- [SWR](https://swr.vercel.app) already do those and do them better. **This owns
22
- the transport; they own everything above it.**
23
-
24
- You still need `"use server"`, and it is not claiming your function mutates.
25
- Despite the name it means *this may be called from the browser* — it is what
26
- gives the function an id and the client a stub to call it through.
27
-
28
- Two markers, two jobs. `"use server"` says the function crosses the boundary.
29
- `query()` says it is a read.
30
-
31
- :::caution[The call site picks the method]
32
- `query()` permits the GET; it does not force it. Calling the function directly
33
- from a client component is still a POST, because the browser cannot tell a query
34
- id from an action id — only `fetchQuery` sends a GET.
35
-
36
- ```tsx
37
- getListings(kind) // POST, even though it is a query
38
- fetchQuery(getListings, [kind]) // GET, and [kind] is typed from getListings
39
- ```
40
-
41
- Development warns from the server when a query arrives at the action endpoint,
42
- so a forgotten `fetchQuery` shows up rather than quietly costing you the method.
43
- :::
44
-
45
- ## What it changes
46
-
47
- Only the method. Same types, same arguments, same lack of an endpoint to write.
18
+ A query has no cache, batching or deduplication of its own.
19
+ [TanStack Query](https://tanstack.com/query) and [SWR](https://swr.vercel.app)
20
+ already do those, and a query works as their fetcher.
48
21
 
49
- Three things follow from that:
22
+ ## Defining a query
50
23
 
51
- - **Access logs and rate limiters** stop counting your reads as mutations. A
52
- limiter that allows 10 writes a minute should not be spending them on a list
53
- being refreshed.
54
- - **A GET is the only shape a cache can keep.** A browser cache, a CDN or a
55
- service worker can hold one; a POST can never be held by any of them.
56
- - **Repeating it is safe by contract**, which is what a prefetcher, a crawler
57
- or a retrying proxy assumes when it sees a GET.
24
+ Put it in a `"use server"` module and wrap it in `query()`. The directive lets
25
+ the browser call the function; `query()` says the call only reads. Export the
26
+ wrapped value, not the bare function beside it.
58
27
 
59
- TanStack Start makes the same choice from the other side: its `createServerFn()`
60
- is a GET unless you ask for `{ method: 'POST' }`. We cannot default it that way
61
- — React gives us one directive for everything, so a GET default would send
62
- mutations as GET too.
28
+ A GET is what lets the read be told apart from a write. Access logs and rate
29
+ limiters stop counting it as a mutation, a browser cache or a CDN can keep the
30
+ answer, and a prefetcher, a crawler or a retrying proxy can safely repeat it.
63
31
 
64
- ### If you skip it
32
+ ### The call site picks the method
65
33
 
66
- A plain server action still works as a cache library's fetcher, and nothing
67
- breaks:
34
+ Only `fetchQuery` sends a GET. Calling the function directly from a client
35
+ component still sends a POST, because the browser can't tell a query from an
36
+ action:
68
37
 
69
38
  ```tsx
70
- useQuery({ queryKey: ["listings", kind], queryFn: () => getListings(kind) })
39
+ getListings(kind) // POST, even though it is a query
40
+ fetchQuery(getListings, [kind]) // GET, and [kind] is typed from getListings
71
41
  ```
72
42
 
73
- You lose the three things above and keep everything else. So this is a
74
- reasonable place to start, and `query()` is the thing to reach for once a read
75
- is worth being precise about — anything hot enough to show up in a rate limiter,
76
- or public enough to be worth caching.
43
+ In development the server warns when a query arrives as a POST, so a forgotten
44
+ `fetchQuery` shows up.
77
45
 
78
- One caveat on the second: data that is the same for everyone usually wants
79
- [prerendering](/guides/static-generation/) rather than a client read at all, and
80
- a personal read answers `no-store` and is not cached either way. The caching win
81
- is real, and narrower than it sounds.
46
+ A plain server action also works as a cache library's fetcher. It's a fine
47
+ place to start; switch to `query()` once a read is hot enough to show up in a
48
+ rate limiter, or public enough to cache.
82
49
 
83
- ## Reading it
50
+ ## Reading a query in a server component
84
51
 
85
- **In a server component, call it.** It is ordinary server code — no HTTP, no
86
- cache, no client involved:
52
+ Call it. On the server it is an ordinary function, with no HTTP involved:
87
53
 
88
54
  ```tsx
89
55
  const listings = await getListings("stay")
90
56
  ```
91
57
 
92
- **Better still, do not await it.** Pass the promise down and let a client
93
- component resolve it, and the data streams with the page:
58
+ Better, don't await it. Pass the promise to a client component and wrap that
59
+ in `<Suspense>`, so the page paints at once and the rows stream into the same
60
+ response:
94
61
 
95
62
  ```tsx
96
63
  export default function Page() {
@@ -104,14 +71,12 @@ export default function Page() {
104
71
  }
105
72
  ```
106
73
 
107
- React serialises the promise as a pending row in the payload, so the shell
108
- paints at once and the rows arrive when the query answers — in the same
109
- response, with no request from the browser. Nothing in this package is involved;
110
74
  `use()` is React's. Reach for this first.
111
75
 
112
- **When the browser decides what to read** — a filter, another page, a refresh —
113
- call it. `fetchQuery` is an async function that goes to the server and gives
114
- back the typed answer; nothing else is required:
76
+ ## Reading a query from the browser
77
+
78
+ When the browser decides what to read - a filter, another page, a refresh -
79
+ call `fetchQuery`. It goes to the server and returns the typed answer:
115
80
 
116
81
  ```tsx
117
82
  'use client'
@@ -137,14 +102,17 @@ export function Listings({ initial }: { initial: Listing[] }) {
137
102
  }
138
103
  ```
139
104
 
140
- That is the whole pattern: an event handler, `await fetchQuery(...)`, a
141
- `setState`. `useTransition` keeps the old list on screen while the new one
142
- loads and gives you `pending` for the button. The same call works in a
143
- `useEffect`, in an `onSubmit`, anywhere in the browser.
105
+ `useTransition` keeps the old list on screen while the new one loads. The same
106
+ call works in a `useEffect`, an `onSubmit`, anywhere in the browser.
107
+
108
+ `fetchQuery` only works in the browser. React refuses a server-function call
109
+ during the first render, so don't call it while a component renders on the
110
+ server. TanStack and SWR never do: they fetch in an effect, after hydration.
144
111
 
145
- **When you want caching**, hand the same call to the library that will hold
146
- the answer. `fetchQuery` goes to the server every time; staleness,
147
- revalidation and deduplication belong to the library, not to the fetcher:
112
+ ## Using TanStack Query or SWR
113
+
114
+ Hand the same call to the library. `fetchQuery` goes to the server every time;
115
+ staleness, revalidation and deduplication are the library's:
148
116
 
149
117
  ```tsx
150
118
  // TanStack Query
@@ -158,22 +126,18 @@ useSWR(["listings", kind], () => fetchQuery(getListings, [kind]))
158
126
  ```
159
127
 
160
128
  :::caution[Keep the arrow]
161
- TanStack calls a bare `queryFn` with its own context — `{ client, queryKey,
162
- meta, signal }` — and a server function serialises whatever it is handed, so
163
- passing one unwrapped would try to put an `AbortSignal` on the wire. The arrow
164
- is where you choose what travels.
129
+ TanStack calls a bare `queryFn` with its own context - `{ client, queryKey,
130
+ meta, signal }` - and a server function sends whatever it is handed, so an
131
+ unwrapped one would try to put an `AbortSignal` on the wire. The arrow is where
132
+ you choose what travels.
165
133
  :::
166
134
 
167
- ### Server data in the cache
135
+ ### Starting the cache with the server's data
168
136
 
169
- The two above are the whole answer for most pages: `use()` when the server
170
- knows what to read, `fetchQuery` when the browser decides. This one is for
171
- data a cache library holds **and** that should already be on the page when it
172
- arrives: a list the browser refetches on focus, polls, pages through, or
173
- refreshes after a mutation. The server reads it, the page carries it, and the
174
- library starts with it rather than fetching it again. Data that is only
175
- displayed does not need it; a server component, or a promise passed to
176
- `use()`, is less code.
137
+ For data the library holds - refetched on focus, polled, paged, refreshed after
138
+ an action - the server can read it and the page can carry it, so the library
139
+ starts with it instead of fetching it again. Data that is only displayed
140
+ doesn't need this; a server component or `use()` is less code.
177
141
 
178
142
  Write the query's options once, and import them from both sides:
179
143
 
@@ -201,7 +165,7 @@ import { listingsQuery } from '@/listings'
201
165
  import { Listings } from './listings'
202
166
 
203
167
  export default function Page() {
204
- // A new client per request, here and never at module scope: a module-level
168
+ // A new client per request, never at module scope: a module-level
205
169
  // one on the server is shared by every visitor.
206
170
  const qc = new QueryClient({
207
171
  defaultOptions: {
@@ -236,7 +200,7 @@ export function Listings({ kind }: { kind: string }) {
236
200
  ```
237
201
 
238
202
  `HydrationBoundary` needs a `QueryClientProvider` above it, like any TanStack
239
- hook. From there on it is TanStack: `invalidateQueries(['listings'])` after
203
+ hook. After that it is plain TanStack: `invalidateQueries(['listings'])` after
240
204
  an action refetches through `fetchQuery`.
241
205
 
242
206
  SWR does the same with `fallback`, awaited rather than streamed:
@@ -273,30 +237,21 @@ export function Listings({ kind }: { kind: string }) {
273
237
  }
274
238
  ```
275
239
 
276
- Either way, the page's first render makes no request for the data: measured,
277
- zero requests to the query endpoint on load, with the data on screen.
278
-
279
- #### What crosses from server to browser
240
+ Either way, loading the page makes no request for the data.
280
241
 
281
- The options file is imported by both environments, and that is safe, with two
282
- things to hold to:
242
+ Two things to hold to, since the options file is imported on both sides:
283
243
 
284
244
  - **Server code stays on the server.** `getListings` comes from a
285
- `"use server"` module, so the browser bundle gets a reference to call it
286
- by, not its body; the `typeof window` branch that calls it directly never
287
- runs there. Checked on a build: nothing the query reads appeared in any
288
- browser chunk. What would leak is importing server-only code into the
289
- options file itself (a database client, `src/env.ts`), which is what the
290
- `"use server"` module is for.
245
+ `"use server"` module, so the browser gets a reference to call, not its body.
246
+ Don't import server-only code - a database client, `src/env.ts` - into the
247
+ options file itself.
291
248
  - **The data does reach the browser.** A dehydrated cache or a `fallback` is
292
- serialized into the page, the same as a prop. Seed only what the visitor
293
- may see, and create the `QueryClient` inside the component, per request,
294
- as above: a module-level one on the server carries one visitor's data into
295
- the next visitor's page.
249
+ written into the page like a prop. Seed only what the visitor may see, and
250
+ create the `QueryClient` inside the component, per request.
296
251
 
297
- ### Paging, polling, and the rest
252
+ ### Paging and polling
298
253
 
299
- All of it belongs to the library, and all of it works:
254
+ Both belong to the library, with `fetchQuery` as the fetcher:
300
255
 
301
256
  ```tsx
302
257
  // Infinite. The cursor is just an argument.
@@ -309,26 +264,21 @@ useInfiniteQuery({
309
264
  staleTime: 60_000,
310
265
  })
311
266
 
312
- // Data that changes while you watch. No live connection needed.
267
+ // Re-read every two seconds.
313
268
  useQuery({ queryKey: ["seats"], queryFn: () => fetchQuery(getSeats), refetchInterval: 2_000 })
314
269
  ```
315
270
 
316
- Page one comes from a server component and costs no request; later pages are
317
- ordinary reads. `/infinite`, `/pagination` and `/polling` in the example app are
318
- these three patterns end to end.
271
+ Page one comes from a server component; later pages are ordinary reads.
272
+ `/infinite`, `/pagination` and `/polling` in the example app show all three.
319
273
 
320
- :::caution[A seed is stale by default]
321
- TanStack treats `initialData` as stale at its default `staleTime` of `0`, so
322
- without an explicit `staleTime` it refetches page one on mount and the round
323
- trip you seeded to avoid happens anyway. SWR's `fallbackData` has the same
324
- shape of caveat, and `refetchInterval` pauses while the tab is hidden.
325
- :::
274
+ Set a `staleTime` whenever you seed `initialData`. At TanStack's default of `0`
275
+ the seed counts as stale and page one is refetched on mount anyway. SWR's
276
+ `fallbackData` has the same catch.
326
277
 
327
- ### Live data
278
+ ## Live data
328
279
 
329
- A value that keeps changing while someone watches is not what `query()` is —
330
- a query answers once and is cacheable — but a query is the natural thing to
331
- read *again*:
280
+ To keep a value current while someone watches, read the query again on an
281
+ interval with `usePolling`:
332
282
 
333
283
  ```tsx
334
284
  import { usePolling } from '@rsc-kit/core/usePolling'
@@ -336,20 +286,22 @@ import { usePolling } from '@rsc-kit/core/usePolling'
336
286
  const { data: seats } = usePolling(() => fetchQuery(getSeats), { every: 2_000 })
337
287
  ```
338
288
 
339
- It reuses what you already wrote, needs no special route, and goes through the
340
- query's `Cache-Control` — a thousand tabs polling the same seat count become
341
- one origin request per interval at the CDN. It pauses while the tab is hidden
342
- and never overlaps two reads.
289
+ It pauses while the tab is hidden, never overlaps two reads, and goes through
290
+ the query's `Cache-Control`, so a thousand tabs polling a public seat count are
291
+ one origin request per interval at the CDN.
292
+
293
+ When your own code changes the data, [`refreshOn`](/guides/live-data) refreshes
294
+ open tabs without polling. When the server can push values,
295
+ [a route that streams](/guides/api-routes/#a-route-that-streams) holds one
296
+ connection per tab instead.
297
+
298
+ ### Polling until something finishes
343
299
 
344
- **Until it settles.** A job that is queued, then running, then done wants
345
- polling that stops on its own. `until` says when a read is the last one, and
346
- `onSettled` fires once, on that read. The result is the data, and what to do
347
- when it settles is the page's to decide — so the same primitive serves two
348
- pages that want different things:
300
+ `until` says when a read is the last one, and `onSettled` fires once, on that
301
+ read:
349
302
 
350
303
  ```tsx
351
- // A list of jobs, server-rendered, some still running: poll those until they
352
- // settle, then re-render the card through the server path that built it.
304
+ // Poll a running job, then re-render the page through the server.
353
305
  usePolling(() => fetchQuery(jobStatus, [id]), {
354
306
  every: 2_000,
355
307
  enabled: !isTerminal(job),
@@ -357,8 +309,7 @@ usePolling(() => fetchQuery(jobStatus, [id]), {
357
309
  onSettled: () => refresh('page'),
358
310
  })
359
311
 
360
- // The page that started the job and owns its state machine: the value in
361
- // hand, and the terminal state driving the next step.
312
+ // Or drive the page's own state from the final value.
362
313
  const { data, status } = usePolling(() => fetchQuery(jobStatus, [id]), {
363
314
  every: 1_500,
364
315
  until: isTerminal,
@@ -366,15 +317,14 @@ const { data, status } = usePolling(() => fetchQuery(jobStatus, [id]), {
366
317
  })
367
318
  ```
368
319
 
369
- Settled means stopped: nothing is read again until `refresh()`, which starts
370
- it over, or the inputs change. A page that has to survive a reload keeps the
371
- job's id where it likes and passes it back in; the hook starts polling the
372
- moment it mounts with one.
320
+ Once settled, nothing is read again until `refresh()` starts it over or the
321
+ inputs change. To survive a reload, keep the job's id somewhere and pass it
322
+ back in; polling starts as soon as the hook mounts with one.
373
323
 
374
- **No library needed.** `data` is state; a component that only wants to show
375
- the value reads it. When the value already lives somewhere, `onData` hands
376
- every answer to it — a `useState`, a reducer, or a cache library — so that
377
- stays the source of truth:
324
+ ### Keeping the value in your own state
325
+
326
+ `data` is state already. When the value lives somewhere else, `onData` hands it
327
+ every answer:
378
328
 
379
329
  ```tsx
380
330
  const [seats, setSeats] = useState(initial)
@@ -386,13 +336,11 @@ usePolling(() => fetchQuery(getSeats), {
386
336
  })
387
337
  ```
388
338
 
389
- Neither hook needs a cache library; TanStack and SWR are shown because a page
390
- that already uses one should keep it as the one place the value lives.
339
+ ### When a read fails
391
340
 
392
- A read that fails does not stop the polling — the next interval reads again —
393
- and it reaches you two ways: `error` is the state, and `onError` fires per
394
- failed read, for a toast or a log, so a page that keeps its own state does not
395
- have to watch `error` in an effect:
341
+ A failed read doesn't stop polling; the next interval reads again. `error`
342
+ holds the failure, and `onError` fires for each one. `failures` counts the
343
+ failures in a row, and a success resets it:
396
344
 
397
345
  ```tsx
398
346
  usePolling(() => fetchQuery(getSeats), {
@@ -404,29 +352,29 @@ usePolling(() => fetchQuery(getSeats), {
404
352
  })
405
353
  ```
406
354
 
407
- `failures` counts the failed reads in a row and a success resets it, so the
408
- third failure can be a toast where the first was a blip, without the page
409
- keeping a counter of its own.
355
+ ## Checking who is asking
356
+
357
+ A query is a public GET endpoint. `middleware.ts` guards a route, and a query
358
+ has no route, so a query behind a guarded page is not guarded. The visitor's
359
+ cookies and session are there for the call, so the query checks for itself:
410
360
 
411
- **When something can push**, the server sends events instead and the browser
412
- holds one connection per tab. That is a route, not a query:
413
- [a route that streams](/guides/api-routes/#a-route-that-streams). The trade-off
414
- is stated there.
361
+ ```ts
362
+ export const getOrders = query(async () => {
363
+ const user = await currentUser()
415
364
 
416
- ### Where it will not work
365
+ if (!user) throw new Error("Not signed in")
417
366
 
418
- `fetchQuery` only works in the browser. React refuses a server-function call
419
- during the first render, so a component that also renders on the server must not
420
- call it there.
367
+ return db.orders.forUser(user.id)
368
+ })
369
+ ```
421
370
 
422
- You will not hit this through TanStack or SWR — they fetch in an effect, after
423
- hydration.
371
+ Check identity, not arguments. A `getOrder(id)` that trusts the id lets the
372
+ caller read any order.
424
373
 
425
- ## Sharing a check across reads
374
+ ### Sharing a check across reads
426
375
 
427
- A query has no middleware above it, so each one checks for itself. If that means
428
- writing the same check in every file, put it on the client you already use for
429
- actions:
376
+ Instead of repeating the check, put it on the client you use for actions and
377
+ build every query from it:
430
378
 
431
379
  ```ts title="src/server/client.ts"
432
380
  'use server'
@@ -443,41 +391,52 @@ export const client = createActionClient({ onError: report })
443
391
  })
444
392
  ```
445
393
 
446
- ```ts title="src/server/posts.ts"
394
+ ```ts title="src/server/orders.ts"
447
395
  'use server'
448
396
 
449
397
  import { client } from './client'
450
398
 
451
- export const createPost = client.input(schema).handler(async ({ input, ctx }) => …) // POST
452
- export const getPosts = client.input(filter).query(async ({ input, ctx }) => …) // GET
399
+ export const createOrder = client.input(schema).handler(async ({ input, ctx }) => …) // an action, POST
400
+ export const getOrders = client.query(async ({ ctx }) => db.orders.forUser(ctx.user.id)) // a query, GET
453
401
  ```
454
402
 
455
- One client, one set of middleware, one `onError`. `.handler()` makes an action;
456
- `.query()` makes a query. Neither can be added without the check.
403
+ `ctx.user` is typed and never null, because the only way into the handler is
404
+ through the middleware. A query built this way can't be added without the
405
+ check.
406
+
407
+ A query built from `.input(schema)` takes that schema's input and nothing else:
408
+ `getLogs({ team: 1, nonsense: true })` and `getLogs()` both fail the
409
+ typecheck. One without a schema takes no argument.
457
410
 
458
- ### Called with the schema's input
411
+ ### What the endpoint does for you
459
412
 
460
- A query built from `createActionClient().input(schema)` takes that schema's
461
- input, and nothing else: `getLogs({ team: 1, nonsense: true })` and `getLogs()`
462
- both fail the typecheck, not the read. One without a schema takes no argument.
413
+ - **Only `query()` is reachable.** Every other server function is refused, so
414
+ no action can be called over GET. An unknown id and a real action's id get
415
+ the same 404, so ids can't be probed.
416
+ - **It requires the `X-RSC-Query` header.** Without it, any site could trigger
417
+ the read with an `<img>` tag and the visitor's cookies. The header forces a
418
+ browser preflight, which nothing answers.
419
+ - **It refuses a cross-origin request** when an `Origin` is present, and an
420
+ oversized URL with `414` before decoding anything.
421
+ - **It sends `Vary: Cookie`**, so a cached answer is never shared between
422
+ visitors.
463
423
 
464
- ### A query cannot redirect
424
+ None of that decides who may read what. The query does.
465
425
 
466
- A query is read by a cache library, not navigated to, so a `redirect()` in its
467
- middleware has nowhere to go and the read fails. Refuse instead — throw
468
- `ServerAuthenticationError` (a 401) or `ServerAuthorizationError` (a 403) — and
469
- let the cache's error handler send the visitor to sign in. The same refusal in
470
- an action or a page does redirect.
426
+ ### Rules for a query
471
427
 
472
- ### They fail differently, on purpose
428
+ - **Never write.** It's a GET, and a prefetcher, a crawler or a retry will
429
+ repeat it.
430
+ - **Arguments are public.** They travel in the URL, into access logs, browser
431
+ history and referrer headers. A token or a reset code belongs in an action.
432
+ - **Arguments too large for a URL, or containing a `File`,** make the read fall
433
+ back to a POST. It still works, but stops being cacheable, and development
434
+ warns.
473
435
 
474
- An action **returns** its failures, because React strips a thrown message in
475
- production. A query **throws** — every cache library reports failure by
476
- rejection, and one that answered with an error-shaped object would look like a
477
- successful read of something odd.
436
+ ## When a query fails
478
437
 
479
- So a refused read rejects with a real `Error`. A validation failure keeps its
480
- fields:
438
+ A query **throws** on failure, because every cache library reports a failure by
439
+ rejection. A validation failure keeps its fields:
481
440
 
482
441
  ```tsx
483
442
  const { error } = useQuery({ queryKey: ['posts'], queryFn: () => fetchQuery(getPosts, [filter]) })
@@ -486,129 +445,41 @@ error.message // 'Validation failed'
486
445
  error.errors // { title: ['too short'] }
487
446
  ```
488
447
 
489
- ## Securing a query
490
-
491
- A query is a public GET endpoint. Treat it as one.
448
+ An action **returns** its failures instead, because React strips a thrown
449
+ message in production.
492
450
 
493
- ### Route middleware does not run
451
+ ### A query cannot redirect
494
452
 
495
- `middleware.ts` guards a **route**, and a query has no route — it is reachable
496
- whoever is asking and whatever page they came from. A query behind a guarded
497
- page is not guarded.
453
+ A `redirect()` in a query's middleware has nowhere to go, so the read fails.
454
+ Refuse instead: throw `ServerAuthenticationError` (a 401) or
455
+ `ServerAuthorizationError` (a 403), and let the cache's error handler send the
456
+ visitor to sign in. The same refusal in an action or a page does redirect.
498
457
 
499
- What you do get is the request: the visitor's cookies and session are bound for
500
- the call, so a query can check for itself.
458
+ ## Caching the answer
501
459
 
502
- One query is fine written by hand:
460
+ Answers default to `private, no-store`, since a query may read the session. To
461
+ let the browser and a CDN keep a public answer, set `cache`:
503
462
 
504
463
  ```ts
505
- export const getOrders = query(async () => {
506
- const user = await currentUser()
507
-
508
- if (!user) throw new Error("Not signed in")
509
-
510
- return db.orders.forUser(user.id)
511
- })
512
- ```
513
-
514
- Twenty is twenty chances to forget, and the one you forget is the one that
515
- matters. Put the check on the client you already use for actions and build
516
- every read from it:
517
-
518
- ```ts title="src/server/orders.ts"
519
- 'use server'
520
-
521
- import { client } from './client'
522
-
523
- export const getOrders = client.query(async ({ ctx }) => db.orders.forUser(ctx.user.id))
464
+ export const getPricing = query(async () => tiers(), { cache: "public", maxAge: 300 })
524
465
  ```
525
466
 
526
- `ctx.user` is typed and non-null because the only way into the handler was
527
- through the middleware that put it there — so a query **cannot be added without
528
- the check**. Same client, same middleware, same `onError` as your actions;
529
- `.handler()` makes a mutation and `.query()` makes a read. See
530
- [sharing a check across reads](#sharing-a-check-across-reads) below.
531
-
532
- Authorise on **identity, not arguments**. `getOrder(id)` that trusts the id is
533
- the whole of an IDOR: the caller chooses the id.
534
-
535
- ### Only `query()` is reachable
536
-
537
- The endpoint refuses anything that is not a query, which is what keeps every
538
- action you have registered off a GET url. So export the wrapped value, not the
539
- bare function beside it.
540
-
541
- An unknown id and a real-but-unmarked one get the same 404. Telling them apart
542
- would let someone probe for your action ids.
543
-
544
- ### A query must never write
467
+ You probably don't need it. There are two caches:
545
468
 
546
- It is a GET. A prefetcher, a crawler or a retry will repeat it.
547
-
548
- ### What the endpoint does for you
549
-
550
- - **Requires `X-RSC-Query`.** A GET with no unusual header is a *simple*
551
- request, so any page anywhere could trigger one with
552
- `<img src="…/_rsc/query?…">` and it would carry the visitor's cookies — CORS
553
- stops them reading the answer, not the read running. That header is not
554
- CORS-safelisted, so a browser preflights it and nothing here answers a
555
- preflight. It is the same protection a POST carrying `X-RSC-Action` had.
556
- - Refuses a cross-origin request when an `Origin` is present.
557
- - Refuses an oversized url with `414` before decoding anything.
558
- - Sends `Vary: Cookie`, so a cacheable answer is never shared between visitors.
559
-
560
- None of that authorises anything. The query does that.
561
-
562
- ### Arguments are public
563
-
564
- They travel in the url, so they reach access logs, browser history and referrer
565
- headers. Never take a token or a password reset code as a query argument — that
566
- is an action.
567
-
568
- Arguments too large for a url, or containing a `File`, make the read fall back
569
- to a POST rather than failing. It still works; it simply stops being cacheable,
570
- and development warns when it happens.
571
-
572
- ## Caching
573
-
574
- There is no cache in `fetchQuery`, and there will not be one: a client cache
575
- is where "small and ours" goes wrong — a `Map` first, then staleness, then
576
- invalidation, then dedupe across components, and it ends as a worse TanStack
577
- Query that every guide has to teach. What this package owns is the part a
578
- library cannot: whether the answer is cacheable *at all*, which is an HTTP
579
- question. So the choice is a ladder, and most reads stop on the first rung:
580
-
581
- | you need | use |
469
+ | You need | Use |
582
470
  | --- | --- |
583
- | the value, now | `fetchQuery` in a handler and `setState` — every call goes to the server |
584
- | the answer to survive a reload, or a CDN to serve it | `cache` on the query, below — the browser and the CDN hold it, with no code in the page |
471
+ | the value, now | `fetchQuery` in a handler and `setState`; every call goes to the server |
472
+ | the answer to survive a reload, or a CDN to serve it | `cache` on the query |
585
473
  | staleness, background refresh, optimistic updates, one value shared across components | TanStack Query or SWR, with `fetchQuery` as the fetcher |
586
474
 
587
- Answers default to `private, no-store`. A query may read the session, and a
588
- cacheable answer to a personal read is how one visitor is served another's data.
589
-
590
- ```ts
591
- export const getPricing = query(async () => tiers(), { cache: "public", maxAge: 300 })
592
- ```
593
-
594
- ### You probably do not need to change it
595
-
596
- There are two caches and they solve different problems.
597
-
598
- **Your cache library's**, in memory and per tab, decides whether to ask again.
599
- It needs nothing from this option — `no-store` does not stop TanStack or SWR
600
- holding an answer, because they are not an HTTP cache.
601
-
602
- **The HTTP one**, which `cache` controls, decides whether an answer survives a
603
- reload, works offline, or can be shared by a CDN.
604
-
605
- Most apps want only the first. And note that data which is the same for everyone
606
- usually wants [prerendering](/guides/static-generation/) rather than a client
607
- read at all — which is a better answer than any cache. For a personal read you
608
- want across reloads, persist your cache library rather than widening the read.
475
+ `no-store` doesn't stop TanStack or SWR holding an answer in memory; they are
476
+ not an HTTP cache. Data that is the same for everyone usually wants
477
+ [prerendering](/guides/static-generation/) rather than a client read. For a
478
+ personal read you want across reloads, persist your cache library rather than
479
+ widening the read.
609
480
 
610
- ## During a build
481
+ ## Queries during a build
611
482
 
612
- A query is an ordinary function, so it follows the ordinary rule. One reading a
613
- database the build machine can reach runs at build time and the page is frozen
614
- with real data in it. Call `connection()` inside the query to opt out.
483
+ A query is an ordinary function. One that reads a database the build machine
484
+ can reach runs at build time, and the page is stored with that data in it.
485
+ Call `connection()` inside the query to render it per request instead.