# Queries

> Reading from the server over GET, and letting TanStack Query or SWR own everything above it.

A query is a server function that only reads. Wrap it in `query()` and the
browser calls it with a GET instead of a POST:

```ts title="src/queries.ts"
"use server"

import { query } from "@rsc-kit/core/query"

export const getListings = query(async (kind: string) => {
  return db.listings.where({ kind })
})
```

A query has no cache, batching or deduplication of its own.
[TanStack Query](https://tanstack.com/query) and [SWR](https://swr.vercel.app)
already do those, and a query works as their fetcher.

## Defining a query

Put it in a `"use server"` module and wrap it in `query()`. The directive lets
the browser call the function; `query()` says the call only reads. Export the
wrapped value, not the bare function beside it.

A GET is what lets the read be told apart from a write. Access logs and rate
limiters stop counting it as a mutation, a browser cache or a CDN can keep the
answer, and a prefetcher, a crawler or a retrying proxy can safely repeat it.

### The call site picks the method

Only `fetchQuery` sends a GET. Calling the function directly from a client
component still sends a POST, because the browser can't tell a query from an
action:

```tsx
getListings(kind)                  // POST, even though it is a query
fetchQuery(getListings, [kind])    // GET, and [kind] is typed from getListings
```

In development the server warns when a query arrives as a POST, so a forgotten
`fetchQuery` shows up.

A plain server action also works as a cache library's fetcher. It's a fine
place to start; switch to `query()` once a read is hot enough to show up in a
rate limiter, or public enough to cache.

## Reading a query in a server component

Call it. On the server it is an ordinary function, with no HTTP involved:

```tsx
const listings = await getListings("stay")
```

Better, don't await it. Pass the promise to a client component and wrap that
in `<Suspense>`, so the page paints at once and the rows stream into the same
response:

```tsx
export default function Page() {
  const listings = getListings("stay")

  return (
    <Suspense fallback={<Skeleton />}>
      <List listings={listings} />   {/* "use client": use(listings) */}
    </Suspense>
  )
}
```

`use()` is React's. Reach for this first.

## Reading a query from the browser

When the browser decides what to read - a filter, another page, a refresh -
call `fetchQuery`. It goes to the server and returns the typed answer:

```tsx
'use client'

import { useState, useTransition } from 'react'
import { fetchQuery } from '@rsc-kit/core/queryClient'
import { getListings } from '@/queries'

export function Listings({ initial }: { initial: Listing[] }) {
  const [listings, setListings] = useState(initial)   // the server-rendered page one
  const [pending, start] = useTransition()

  const show = (kind: string) =>
    start(async () => setListings(await fetchQuery(getListings, [kind])))

  return (
    <>
      <button onClick={() => show('stay')} disabled={pending}>Stays</button>
      <button onClick={() => show('rent')} disabled={pending}>Rentals</button>
      <List listings={listings} />
    </>
  )
}
```

`useTransition` keeps the old list on screen while the new one loads. The same
call works in a `useEffect`, an `onSubmit`, anywhere in the browser.

`fetchQuery` only works in the browser. React refuses a server-function call
during the first render, so don't call it while a component renders on the
server. TanStack and SWR never do: they fetch in an effect, after hydration.

## Using TanStack Query or SWR

Hand the same call to the library. `fetchQuery` goes to the server every time;
staleness, revalidation and deduplication are the library's:

```tsx
// TanStack Query
useQuery({
  queryKey: ["listings", kind],
  queryFn: () => fetchQuery(getListings, [kind]),
})

// SWR
useSWR(["listings", kind], () => fetchQuery(getListings, [kind]))
```

:::caution[Keep the arrow]
TanStack calls a bare `queryFn` with its own context - `{ client, queryKey,
meta, signal }` - and a server function sends whatever it is handed, so an
unwrapped one would try to put an `AbortSignal` on the wire. The arrow is where
you choose what travels.
:::

### Starting the cache with the server's data

For data the library holds - refetched on focus, polled, paged, refreshed after
an action - the server can read it and the page can carry it, so the library
starts with it instead of fetching it again. Data that is only displayed
doesn't need this; a server component or `use()` is less code.

Write the query's options once, and import them from both sides:

```ts title="src/listings.ts"
import { queryOptions } from '@tanstack/react-query'
import { fetchQuery } from '@rsc-kit/core/queryClient'
import { getListings } from '@/queries'

export const listingsQuery = (kind: string) =>
  queryOptions({
    queryKey: ['listings', kind],
    // On the server it is just a function; in the browser it goes out as a GET.
    queryFn: () => (typeof window === 'undefined' ? getListings(kind) : fetchQuery(getListings, [kind])),
    // Without it, TanStack treats the seeded data as stale and refetches on mount.
    staleTime: 60_000,
  })
```

The server component starts the read and hands the cache down:

```tsx title="src/app/listings/page.tsx"
import { Suspense } from 'react'
import { QueryClient, dehydrate, HydrationBoundary, defaultShouldDehydrateQuery } from '@tanstack/react-query'
import { listingsQuery } from '@/listings'
import { Listings } from './listings'

export default function Page() {
  // A new client per request, never at module scope: a module-level
  // one on the server is shared by every visitor.
  const qc = new QueryClient({
    defaultOptions: {
      // Queries still in flight go along too, as promises the page streams.
      dehydrate: { shouldDehydrateQuery: (q) => defaultShouldDehydrateQuery(q) || q.state.status === 'pending' },
    },
  })

  qc.prefetchQuery(listingsQuery('stay')) // not awaited

  return (
    <HydrationBoundary state={dehydrate(qc)}>
      <Suspense fallback={<Skeleton />}>
        <Listings kind="stay" />
      </Suspense>
    </HydrationBoundary>
  )
}
```

```tsx title="src/app/listings/listings.tsx"
'use client'

import { useSuspenseQuery } from '@tanstack/react-query'
import { listingsQuery } from '@/listings'

export function Listings({ kind }: { kind: string }) {
  const { data } = useSuspenseQuery(listingsQuery(kind))

  return <List listings={data} />
}
```

`HydrationBoundary` needs a `QueryClientProvider` above it, like any TanStack
hook. After that it is plain TanStack: `invalidateQueries(['listings'])` after
an action refetches through `fetchQuery`.

SWR does the same with `fallback`, awaited rather than streamed:

```tsx title="src/app/listings/page.tsx"
import { SWRConfig, unstable_serialize } from 'swr'
import { getListings } from '@/queries'
import { Listings } from './listings'

export default async function Page() {
  const listings = await getListings('stay')

  return (
    <SWRConfig value={{ fallback: { [unstable_serialize(['listings', 'stay'])]: listings } }}>
      <Listings kind="stay" />
    </SWRConfig>
  )
}
```

```tsx title="src/app/listings/listings.tsx"
'use client'

import useSWR from 'swr'
import { fetchQuery } from '@rsc-kit/core/queryClient'
import { getListings } from '@/queries'

export function Listings({ kind }: { kind: string }) {
  // The key must match the one in fallback. revalidateOnMount: false keeps
  // SWR from fetching again the moment the page loads.
  const { data } = useSWR(['listings', kind], () => fetchQuery(getListings, [kind]), { revalidateOnMount: false })

  return <List listings={data ?? []} />
}
```

Either way, loading the page makes no request for the data.

Two things to hold to, since the options file is imported on both sides:

- **Server code stays on the server.** `getListings` comes from a
  `"use server"` module, so the browser gets a reference to call, not its body.
  Don't import server-only code - a database client, `src/env.ts` - into the
  options file itself.
- **The data does reach the browser.** A dehydrated cache or a `fallback` is
  written into the page like a prop. Seed only what the visitor may see, and
  create the `QueryClient` inside the component, per request.

### Paging and polling

Both belong to the library, with `fetchQuery` as the fetcher:

```tsx
// Infinite. The cursor is just an argument.
useInfiniteQuery({
  queryKey: ["feed"],
  queryFn: ({ pageParam }) => fetchQuery(getFeed, [pageParam]),
  initialPageParam: null,
  getNextPageParam: (last) => last.nextCursor,
  initialData: { pages: [first], pageParams: [null] },
  staleTime: 60_000,
})

// Re-read every two seconds.
useQuery({ queryKey: ["seats"], queryFn: () => fetchQuery(getSeats), refetchInterval: 2_000 })
```

Page one comes from a server component; later pages are ordinary reads.
`/infinite`, `/pagination` and `/polling` in the example app show all three.

Set a `staleTime` whenever you seed `initialData`. At TanStack's default of `0`
the seed counts as stale and page one is refetched on mount anyway. SWR's
`fallbackData` has the same catch.

## Live data

To keep a value current while someone watches, read the query again on an
interval with `usePolling`:

```tsx
import { usePolling } from '@rsc-kit/core/usePolling'

const { data: seats } = usePolling(() => fetchQuery(getSeats), { every: 2_000 })
```

It pauses while the tab is hidden, never overlaps two reads, and goes through
the query's `Cache-Control`, so a thousand tabs polling a public seat count are
one origin request per interval at the CDN.

When your own code changes the data, [`refreshOn`](/guides/live-data) refreshes
open tabs without polling. When the server can push values,
[a route that streams](/guides/api-routes/#a-route-that-streams) holds one
connection per tab instead.

### Polling until something finishes

`until` says when a read is the last one, and `onSettled` fires once, on that
read:

```tsx
// Poll a running job, then re-render the page through the server.
usePolling(() => fetchQuery(jobStatus, [id]), {
  every: 2_000,
  enabled: !isTerminal(job),
  until: isTerminal,
  onSettled: () => refresh('page'),
})

// Or drive the page's own state from the final value.
const { data, status } = usePolling(() => fetchQuery(jobStatus, [id]), {
  every: 1_500,
  until: isTerminal,
  onSettled: (final) => dispatch({ type: final.status }),
})
```

Once settled, nothing is read again until `refresh()` starts it over or the
inputs change. To survive a reload, keep the job's id somewhere and pass it
back in; polling starts as soon as the hook mounts with one.

### Keeping the value in your own state

`data` is state already. When the value lives somewhere else, `onData` hands it
every answer:

```tsx
const [seats, setSeats] = useState(initial)
usePolling(() => fetchQuery(getSeats), { every: 2_000, onData: setSeats })            // useState

usePolling(() => fetchQuery(getSeats), {
  every: 2_000,
  onData: (s) => queryClient.setQueryData(['seats'], s),                                 // TanStack
})
```

### When a read fails

A failed read doesn't stop polling; the next interval reads again. `error`
holds the failure, and `onError` fires for each one. `failures` counts the
failures in a row, and a success resets it:

```tsx
usePolling(() => fetchQuery(getSeats), {
  every: 2_000,
  onData: setSeats,
  onError: (e, { failures }) => {
    if (failures === 3) toast.error('Could not refresh seats')
  },
})
```

## Checking who is asking

A query is a public GET endpoint. `middleware.ts` guards a route, and a query
has no route, so a query behind a guarded page is not guarded. The visitor's
cookies and session are there for the call, so the query checks for itself:

```ts
export const getOrders = query(async () => {
  const user = await currentUser()

  if (!user) throw new Error("Not signed in")

  return db.orders.forUser(user.id)
})
```

Check identity, not arguments. A `getOrder(id)` that trusts the id lets the
caller read any order.

### Sharing a check across reads

Instead of repeating the check, put it on the client you use for actions and
build every query from it:

```ts title="src/server/client.ts"
'use server'

import { createActionClient } from '@rsc-kit/core/action'

export const client = createActionClient({ onError: report })
  .use(async ({ next }) => {
    const user = await currentUser()

    if (!user) throw new Error('Not signed in')

    return next({ ctx: { user } })
  })
```

```ts title="src/server/orders.ts"
'use server'

import { client } from './client'

export const createOrder = client.input(schema).handler(async ({ input, ctx }) => …)  // an action, POST
export const getOrders   = client.query(async ({ ctx }) => db.orders.forUser(ctx.user.id)) // a query, GET
```

`ctx.user` is typed and never null, because the only way into the handler is
through the middleware. A query built this way can't be added without the
check.

A query built from `.input(schema)` takes that schema's input and nothing else:
`getLogs({ team: 1, nonsense: true })` and `getLogs()` both fail the
typecheck. One without a schema takes no argument.

### What the endpoint does for you

- **Only `query()` is reachable.** Every other server function is refused, so
  no action can be called over GET. An unknown id and a real action's id get
  the same 404, so ids can't be probed.
- **It requires the `X-RSC-Query` header.** Without it, any site could trigger
  the read with an `<img>` tag and the visitor's cookies. The header forces a
  browser preflight, which nothing answers.
- **It refuses a cross-origin request** when an `Origin` is present, and an
  oversized URL with `414` before decoding anything.
- **It sends `Vary: Cookie`**, so a cached answer is never shared between
  visitors.

None of that decides who may read what. The query does.

### Rules for a query

- **Never write.** It's a GET, and a prefetcher, a crawler or a retry will
  repeat it.
- **Arguments are public.** They travel in the URL, into access logs, browser
  history and referrer headers. A token or a reset code belongs in an action.
- **Arguments too large for a URL, or containing a `File`,** make the read fall
  back to a POST. It still works, but stops being cacheable, and development
  warns.

## When a query fails

A query **throws** on failure, because every cache library reports a failure by
rejection. A validation failure keeps its fields:

```tsx
const { error } = useQuery({ queryKey: ['posts'], queryFn: () => fetchQuery(getPosts, [filter]) })

error.message   // 'Validation failed'
error.errors    // { title: ['too short'] }
```

An action **returns** its failures instead, because React strips a thrown
message in production.

### A query cannot redirect

A `redirect()` in a query's middleware has nowhere to go, so the read fails.
Refuse instead: throw `ServerAuthenticationError` (a 401) or
`ServerAuthorizationError` (a 403), and let the cache's error handler send the
visitor to sign in. The same refusal in an action or a page does redirect.

## Caching the answer

Answers default to `private, no-store`, since a query may read the session. To
let the browser and a CDN keep a public answer, set `cache`:

```ts
export const getPricing = query(async () => tiers(), { cache: "public", maxAge: 300 })
```

You probably don't need it. There are two caches:

| You need | Use |
| --- | --- |
| the value, now | `fetchQuery` in a handler and `setState`; every call goes to the server |
| the answer to survive a reload, or a CDN to serve it | `cache` on the query |
| staleness, background refresh, optimistic updates, one value shared across components | TanStack Query or SWR, with `fetchQuery` as the fetcher |

`no-store` doesn't stop TanStack or SWR holding an answer in memory; they are
not an HTTP cache. Data that is the same for everyone usually wants
[prerendering](/guides/static-generation/) rather than a client read. For a
personal read you want across reloads, persist your cache library rather than
widening the read.

## Queries during a build

A query is an ordinary function. One that reads a database the build machine
can reach runs at build time, and the page is stored with that data in it.
Call `connection()` inside the query to render it per request instead.
