Skip to content

TanStack Query SSR and SWR: put fetched data in server HTML

Why TanStack Query and SWR pages server-render a skeleton, and how prefetching with dehydrate, HydrationBoundary or SWR cacheData puts the data in the raw HTML.

By Crawlito · 7 min read

In short

  • A useQuery or useSWR call that is not prefetched on the server only starts fetching in the browser, so the server HTML contains the loading state, not the data.
  • TanStack Query's documented fix is to fetch on the server with queryClient.query, pass dehydrate(queryClient) to a HydrationBoundary, and read the same query key in the client component.
  • SWR's Next.js guide passes server-fetched data to SWRConfig through cacheData, using preload in Server Components; the API reference still lists the fallback option as well.
  • TanStack Query recommends a default staleTime above zero with SSR, such as 60 seconds, so the client does not refetch the data immediately after hydration.
  • Check the fix by fetching the page with curl and searching the response for a string that only appears in the fetched data.
On this page

If you fetch with TanStack Query's useQuery or SWR's useSWR and your raw HTML shows a skeleton, the framework is server-rendering correctly. The data is the part that is missing. Both libraries fetch in the browser unless you give them data on the server first, so the server renders the loading state. The fix is to prefetch on the server and hand the result to the client cache: dehydrate and HydrationBoundary in TanStack Query, cacheData (or the older fallback) on SWRConfig in SWR.

This post covers only that data layer. If your whole page is an empty <div id="root">, start with the empty HTML problem or React SPAs and AI crawlers instead.

Why useQuery and useSWR render a skeleton on the server

A server-rendered React page runs your components once on the server and sends the resulting HTML. React's useEffect reference is blunt about what does not happen there: Effects only run on the client and do not run during server rendering. Client data libraries start their requests from the browser side of that line.

TanStack Query's SSR guide says it directly: queries that are not prefetched are not server rendered and are fetched on the client after the application is interactive. SWR's Next.js guide describes the same default for client-side fetching: show the page without data first, then fetch in the browser.

So a component like this:

tsx
'use client'
import { useQuery } from '@tanstack/react-query'

export function ProductDetails({ id }: { id: string }) {
  const { data, isPending } = useQuery({
    queryKey: ['product', id],
    queryFn: () => fetch(`/api/products/${id}`).then((r) => r.json()),
  })

  if (isPending) return <div className="skeleton" aria-busy="true" />
  return (
    <article>
      <h1>{data.name}</h1>
      <p>{data.description}</p>
    </article>
  )
}

produces server HTML with the skeleton div and nothing else. A crawler that reads only the raw response, without running JavaScript, gets a page with no product name and no description. Google renders JavaScript, so the same page can look fine in Search Console's rendered view; raw vs rendered HTML explains why the two differ.

How to confirm the data layer is the problem

Pick a string that only exists in the fetched data, such as a product name, a price or the first sentence of an article. Then fetch the page without a browser:

bash
curl -s https://www.example.com/products/blue-kettle | grep -c "Blue enamel kettle"

A result of 0 while the browser shows the text means the content arrives after load. Look at what the HTML does contain:

bash
curl -s https://www.example.com/products/blue-kettle | grep -o 'aria-busy="true"\|class="skeleton[^"]*"' | head

If your headings, navigation and footer are present but the main block is a skeleton, the framework is fine and the query is the gap. See your page as an AI crawler with curl has more variations, including sending a crawler's user agent.

Fix it in TanStack Query: prefetch, dehydrate, HydrationBoundary

The documented pattern has three parts: fetch on the server into a QueryClient, serialise its cache with dehydrate, and wrap the client tree in HydrationBoundary so the client cache starts with that data. A useQuery with the same key then has data on its first render, on the server and in the browser.

Next.js App Router

From TanStack Query's Advanced Server Rendering guide, adapted to the product example:

tsx
// app/products/[id]/page.tsx (Server Component)
import { dehydrate, HydrationBoundary, QueryClient } from '@tanstack/react-query'
import { ProductDetails } from './product-details'
import { getProduct } from '@/lib/products'

export default async function ProductPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params
  const queryClient = new QueryClient()

  await queryClient
    .query({ queryKey: ['product', id], queryFn: () => getProduct(id) })
    .catch(() => {})

  return (
    <HydrationBoundary state={dehydrate(queryClient)}>
      <ProductDetails id={id} />
    </HydrationBoundary>
  )
}

This assumes the app is already wrapped in a QueryClientProvider from a 'use client' providers file, as the guide sets up first. The client component stays as it was. Because the key ['product', id] is already in the cache, isPending is false during server rendering and the article markup is in the HTML.

Two details from the docs matter here:

  • queryClient.query() versus prefetchQuery(). At the time of writing (v5.107), the QueryClient reference marks prefetchQuery as deprecated in favour of queryClient.query(options), and says you can swallow errors with .catch(noop). Older code and tutorials use prefetchQuery, which still works until the next major version.
  • Set a default staleTime. The library default is 0, so data from the server counts as stale immediately and the client refetches on mount. The guides set staleTime: 60 * 1000 in the shared client options to avoid that.

Pages Router and other loaders

The same idea works in any framework that has a server loader. In the Pages Router, do the fetch in getServerSideProps or getStaticProps, return dehydratedState: dehydrate(queryClient) as a prop, and wrap the page in <HydrationBoundary state={dehydratedState}>. The SSR guide also warns against creating the QueryClient at the root of a module in _app.tsx: on the server that cache is shared between all requests, so every user's data can reach every other user. Create it inside the component (the guide uses useState) so each request gets its own cache.

The streaming trap with pending queries

Since v5.40.0 you can skip the await, dehydrate pending queries and let a useSuspenseQuery pick up the promise on the client. That streams the data inside a Suspense boundary instead of in the initial HTML. The Advanced SSR guide also notes that if a plain useQuery reads a pending prefetch, Next.js does not suspend and the component renders in pending status, which opts that part out of server-rendered content. For the content you want crawlers to read, await the query. How each AI crawler treats content streamed after the first chunk is not documented; React streaming SSR and bots covers the options.

Fix it in SWR: cacheData, preload and fallback

SWR's hooks cannot run in Server Components, but SWRConfig, preload and unstable_serialize can be imported there, according to the SWR Next.js guide.

App Router with preload and cacheData

The current guide recommends starting the fetch with preload in a Server Component and passing the result through the cacheData option of SWRConfig:

tsx
// app/products/[id]/page.tsx (Server Component)
import { preload, SWRConfig } from 'swr'
import { ProductDetails } from './product-details'
import { getProduct } from '@/lib/products'

export default async function ProductPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params
  const cacheData = preload(`/api/products/${id}`, () => getProduct(id))

  return (
    <SWRConfig value={{ cacheData }}>
      <ProductDetails id={id} />
    </SWRConfig>
  )
}

The client component calls useSWR('/api/products/' + id, fetcher) with the same key. SWR uses the server result for the first render, writes it to the client cache during hydration and skips the duplicate initial request. The guide labels cacheData experimental and says it needs SWR 2.5.0-beta.1 or later. It also offers a strictServerPrefetchWarning option that logs a console warning for any key rendered without pre-filled data, which is a quick way to find the queries you missed.

Pages Router, and fallback on older versions

The current guide uses the same cacheData option in the Pages Router: return a map of keys to data as a prop from getStaticProps (or getServerSideProps) and pass it to SWRConfig. When you build that map by hand, serialise array or function keys with unstable_serialize so they match the hook's key.

tsx
export async function getServerSideProps({ params }) {
  const product = await getProduct(params.id)
  return {
    props: { id: params.id, cacheData: { [`/api/products/${params.id}`]: product } },
  }
}

export default function Page({ id, cacheData }) {
  return (
    <SWRConfig value={{ cacheData }}>
      <ProductDetails id={id} />
    </SWRConfig>
  )
}

Before cacheData, the guide used the fallback option of SWRConfig for the same map, and on SWR versions before 2.5 that is still the route. The SWR API reference still lists fallback (many keys) and fallbackData (one hook).

Before and after: what the raw HTML should show

Run the same curl from the check section after deploying. The difference looks like this (trimmed, illustrative markup):

html
<!-- Before: client-only query -->
<main>
  <div class="skeleton" aria-busy="true"></div>
</main>

<!-- After: query fetched on the server and dehydrated -->
<main>
  <article>
    <h1>Blue enamel kettle</h1>
    <p>A 1.7 litre stovetop kettle with a stay-cool handle...</p>
  </article>
</main>

You will also see a larger inline script near the end of the document. That is the serialised cache (the RSC payload in the App Router, __NEXT_DATA__ in the Pages Router). It is expected, but keep an eye on its size, because every prefetched query adds its full JSON response to the page that prefetches it.

Which queries are worth prefetching

Prefetching costs server time and HTML weight. TanStack Query's guides say it is fine to mix prefetched and client-only queries, and SWR's strictServerPrefetchWarning exists to help you adopt server prefetching gradually. A practical split:

DataPrefetch on the server?Why
Main article, product or listing contentYesThis is what crawlers and AI search tools need to read
Titles, prices, specs, FAQ answersYesShort, factual text that should be in the page itself
Breadcrumbs and category linksYesGives crawlers real <a href> links to follow
Reviews below the fold, related itemsOptionalUseful, but can load later without losing the core page
User-specific data: cart, account, recommendationsNoNot meant for crawlers, and risky to cache across requests
Data behind a click or tabNoFetch on interaction, as the TanStack docs suggest

If the server and client render different markup from the same cache, React reports hydration mismatches; React hydration errors and crawlers explains what that does to the page.

Frequently asked questions

Does useQuery fetch on the server during SSR?

No. A query only has data on the server if you fetched it there first and passed it in, for example through dehydrate and HydrationBoundary. Otherwise it starts fetching in the browser.

Is initialData enough instead of dehydrate?

It works for simple cases, but TanStack Query's SSR guide lists drawbacks: you must pass the data down to every useQuery that needs it, and initialData never overwrites existing cache data, even when the new data is fresher. The hydration APIs avoid both.

Why does my page refetch right after it loads?

With the default staleTime of 0, server data is stale as soon as it arrives, so the client refetches on mount. Set a default staleTime above zero, such as 60 seconds, in the query client options.

Will prefetching get my pages cited in AI answers?

No one can promise that. Prefetching puts your content in the HTML that crawlers fetch, which removes one technical barrier; whether an assistant cites a page depends on many factors outside the markup.

Check the HTML crawlers receive

After you move your main queries to the server, run the free check on a key page to see whether its text is present in the raw HTML that AI crawlers fetch. For a site with many templates, an audit checks rendering, crawler access and structure across up to 500 pages with evidence for each finding.

Filed under Rendering and content. Topics: react, nextjs, ssr, rendering, raw-html