# Add Query Prefetching to a TanStack Router App

Yes. An agent passes your QueryClient into the router, adds a loader per route that warms the cache on hover, removes a duplicate fetch, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-query-prefetching/tanstack-query/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads how data reaches each page today. In a React frontend laid out like the one in fastapi/full-stack-fastapi-template, `src/main.tsx` builds a `QueryClient` whose query and mutation caches redirect to `/login` on a 401 or 403, and calls `createRouter({ routeTree })` with no context, so no route can reach the client outside a component. `src/routes/_layout/items.tsx` defines `getItemsQueryOptions` with the key `["items"]` and reads it with `useSuspenseQuery` inside a `Suspense` boundary whose fallback is `PendingItems`, so every visit to Items shows the skeleton until `ItemsService.readItems` answers. `src/routes/_layout/admin.tsx` does the same for users and, in `beforeLoad`, calls `UsersService.readUserMe` directly, a second request for the data `useAuth` already caches under `["currentUser"]`. The sidebar in `src/components/Sidebar/Main.tsx` renders each entry as a `Link` from `@tanstack/react-router`, and `vite.config.ts` enables the router plugin with `autoCodeSplitting`. The frontend tests are Playwright specs under `tests/`, with `storageState` from `auth.setup.ts`.

It makes the client available to routes first. `src/routes/__root.tsx` switches from `createRootRoute` to `createRootRouteWithContext` typed with `{ queryClient: QueryClient }`, and `main.tsx` passes `context: { queryClient }` to `createRouter` along with `defaultPreload: "intent"`, so hovering or focusing a link starts the route's loader, and `defaultPreloadStaleTime: 0`, so the router hands every preload to the loader and lets Query decide from its own cache whether to fetch.

Then one loader per data route. The agent moves `getItemsQueryOptions` and `getUsersQueryOptions` into `queryOptions` calls in a `src/queries` module so a route file and a component share one definition, and adds `loader: ({ context }) => context.queryClient.ensureQueryData(itemsQueryOptions())` to the Items route and the same for Admin. `ensureQueryData` returns cached data when there is any and fetches otherwise, so the first hover fetches and the click finds the cache warm; the `staleTime` the agent sets on these options decides when a later hover refetches, and it names the value in the pull request. The `currentUser` query gets the same treatment, and Admin's `beforeLoad` reads it through `ensureQueryData` instead of calling the service, so the superuser check and the sidebar share one request. The `AddItem` and `EditItem` mutations already invalidate `["items"]`, so a change made on the page still refetches.

The proof is a Playwright spec beside `tests/items.spec.ts`: it loads the dashboard, hovers the Items entry in the sidebar, waits for the request to `/api/v1/items/` with `page.waitForRequest`, then clicks and asserts the table is visible without the pending skeleton appearing. The agent runs the suite against the backend it starts in its sandbox with a local PostgreSQL, plus `biome check` and the build's `tsc -p tsconfig.build.json`, and keeps the output.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add route-level prefetching with TanStack Router and TanStack Query. Read frontend/src/main.tsx, frontend/src/routes/__root.tsx, frontend/src/routes/_layout.tsx, frontend/src/routes/_layout/items.tsx, frontend/src/routes/_layout/admin.tsx, frontend/src/hooks/useAuth.ts, frontend/src/components/Sidebar/Main.tsx, frontend/src/components/Sidebar/AppSidebar.tsx, frontend/vite.config.ts, frontend/playwright.config.ts and frontend/tests/items.spec.ts first. Type the root route with createRootRouteWithContext carrying the QueryClient, pass it as router context from main.tsx, and set defaultPreload to intent with defaultPreloadStaleTime 0. Move the items, users and currentUser query options into queryOptions definitions in a shared module, add a loader to the Items and Admin routes that calls ensureQueryData, and make Admin's beforeLoad read the current user through the cache instead of calling the service again. Set a staleTime on these options and say why in the pull request. Add a Playwright spec that hovers the Items link, waits for the items request, clicks, and asserts the table shows without the pending skeleton. Run the Playwright suite against a local backend and database, biome check and tsc, and open a pull request with the output.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request that changes `main.tsx`, `__root.tsx`, the Items and Admin routes and `useAuth.ts`, adds the shared query options module and one Playwright spec. The description lists each route and what its loader warms, shows the duplicate `readUserMe` call it removed, and gives the Playwright, lint and type-check output.

The run's record keeps the test run with its network log, so a reviewer can see the items request fire on hover and not again on click. A reviewer checks that the `staleTime` matches how often the team expects items to change between hovers, that invalidation after add and edit still refetches, and that a 401 during a preload still reaches the cache's redirect.

## Run it on every route that fetches on render

A team with several apps on this stack starts one run per repository with one `POST /o/{org}/sessions` each, this prompt as `input` and the repository in `resources`. Each run reads its own routes, so an app that already passes the client as context gets only the loaders it lacks, and one with no Playwright suite gets the change with a description of how the agent checked it in the browser.

Send a `request_id` that is a UUID v5 of the repository's full name so a retried call returns the run it already started. The key's `webhook_url` reports when each run finishes, with `session_url` to read the pull request from.

## Why run it on Rush?

Prefetching is a few lines per route once the client reaches the router, and the lines that matter are the ones that decide when a preload fetches again and which existing calls become duplicates. The agent reads every route in its sandbox, finds the second `readUserMe` request and the invalidation paths, and proves the result with a browser test that watches the network, so the pull request shows the request happening on hover rather than asserting it.

The pull request is one typed context, a shared module and a loader per route, so review is reading the stale time and the spec. A company with several dashboards on this stack runs them all at once, each in its own sandbox with its own pull request.

## Frequently asked questions

### Why defaultPreloadStaleTime 0?

Because the router keeps its own notion of a fresh preload and would skip calling the loader while that holds. With it at zero, every hover reaches the loader, and `ensureQueryData` with the query's own `staleTime` decides whether a request goes out. One cache makes the decision instead of two.

### Will hovering the sidebar hammer the API?

No. `ensureQueryData` returns cached data when the query has any, and only the `staleTime` on the options decides when a later hover refetches. The spec asserts a single items request across hover and click.

### Does this change the Suspense fallbacks?

They stay, because the loader does not block rendering; it warms the cache. A direct visit by URL with an empty cache still shows `PendingItems` while the first request runs, and the spec covers the hover path only.

### What about the 401 redirect?

The redirect lives on the `QueryCache` in `main.tsx`, and a preload goes through the same cache, so an expired token during a hover clears it and sends the user to `/login` as a click would. The agent includes that case in its description.

## More TanStack Query jobs

- [Add Request Cancellation to a TanStack Query App](https://getrush.ai/run/add-request-cancellation/tanstack-query/)
- [Fix "Bad Argument Type. Starting with v5, Only the Object Form Is Allowed" After a TanStack Query Upgrade](https://getrush.ai/run/fix-bad-argument-type-only-object-form-allowed/tanstack-query/)
- [Add Global Error Handling to TanStack Query](https://getrush.ai/run/add-api-error-handling/tanstack-query/)

## More jobs like this: Hand off a long task

- [Add Query Timeouts to a Flask and SQLAlchemy App](https://getrush.ai/run/add-query-timeouts/sqlalchemy/)
- [Add a Queue Consumer to a Cloudflare Worker](https://getrush.ai/run/add-queue-consumer/cloudflare-workers/)
- [Add Rate Limiting to an Actix Web API](https://getrush.ai/run/add-rate-limiting/actix/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
