# Prefetch tRPC Queries on the Server in a Next.js Pages Router App

Yes. An agent adds getServerSideProps with tRPC's server-side helpers so the post page loads with its data and a real 404, proves it with JavaScript off, opens a PR.

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

## What the agent does

The agent begins by reading how pages fetch now. In a Next.js Pages Router app laid out like trpc/examples-next-prisma-starter, `src/utils/trpc.ts` calls `createTRPCNext<AppRouter, SSRContext>` with `ssr: false` and a `getBaseUrl()` that returns an empty string in the browser and the Vercel or Render host on the server. `src/pages/post/[id].tsx` reads `useRouter().query.id`, calls `trpc.post.byId.useQuery({ id })`, renders three `Skeleton` blocks while the query is `pending`, and on `error` shows an `Empty` block whose title is `postQuery.error.data?.httpStatus ?? 500`. So the first HTML a person or a crawler receives is the skeleton, and a missing post answers 200 with a 404 drawn inside it. `src/pages/index.tsx` carries a commented-out `getStaticProps` that calls `createServerSideHelpers` and then `ssg.post.all.fetch()`, a procedure the router no longer has: `src/server/routers/_app.ts` exposes `healthcheck` and `post`, and `post.ts` has `list`, `byId` and `add`.

It then follows the comment in `src/server/context.ts`: `createContextInner` exists so a caller can build a context without Next.js' request and response. In `[id].tsx` the agent adds `getServerSideProps` that builds `createServerSideHelpers({ router: appRouter, ctx: await createContextInner({}), transformer })` from `@trpc/react-query/server`, with the superjson `transformer` from `src/utils/transformer.ts` so the `createdAt` and `updatedAt` dates survive dehydration as the page's comment promises. It calls `helpers.post.byId.fetch({ id })` inside a try/catch: a thrown `TRPCError` with code `NOT_FOUND` becomes `return { notFound: true }`, which makes Next.js serve `src/pages/404.tsx` with a 404 status, and any other error rethrows. On success it returns `{ props: { trpcState: helpers.dehydrate(), id } }`. `trpc.withTRPC(MyApp)` in `src/pages/_app.tsx` hydrates `pageProps.trpcState`, so the existing `useQuery` in the component starts in `success` with the data and the skeleton never renders. `ssr: false` stays as it is: the page prefetches what it needs rather than turning on request-time SSR for every query.

For the index page the agent does the same with `helpers.post.list.prefetchInfinite({ limit: 5 })`, matching the `useInfiniteQuery({ limit: 5 })` in `PostsCard`, and removes the dead `getStaticProps` comment, which names a procedure that does not exist. It uses `getServerSideProps` here too, because a post added through `AddPostCard` must appear on the next load; a `revalidate` window would hide it for that long.

The proof is a Playwright test in `playwright/smoke.test.ts`, which today holds `go to /` and `add a post`. The new test adds a post through the form, follows its link, then opens the same URL in a browser context created with `javaScriptEnabled: false` and expects the title in the page, which only passes if the HTML already carried it. A second test requests `/post/<random uuid>` and expects status 404. The CI `e2e` job in `.github/workflows/main.yml` runs `pnpm prebuild` but never `db-seed`, so the test creates its own post rather than relying on the `First Post` row that `prisma/seed.ts` upserts. In the sandbox the agent installs Postgres, runs `pnpm install`, `pnpm prebuild`, `pnpm typecheck`, `pnpm lint`, `pnpm build` and `pnpm test-e2e`, and quotes each result.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Prefetch tRPC queries on the server for the post page and the index page. Read src/utils/trpc.ts, src/pages/_app.tsx, src/pages/post/[id].tsx, src/pages/index.tsx, src/server/context.ts, src/server/routers/_app.ts and src/server/routers/post.ts first. Add getServerSideProps to the post page using createServerSideHelpers with createContextInner and the superjson transformer, fetch post.byId, return notFound for a NOT_FOUND error and pass trpcState in props. Prefetch post.list with limit 5 on the index page the same way and delete the stale getStaticProps comment. Keep ssr false in createTRPCNext. Add Playwright tests that read a post with JavaScript disabled and expect a 404 status for an unknown id. Run pnpm typecheck, pnpm lint, pnpm build and pnpm test-e2e against a local Postgres, quote the results and open a pull request.",
  "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 with three files changed: `src/pages/post/[id].tsx` and `src/pages/index.tsx` gain a `getServerSideProps` each, and `playwright/smoke.test.ts` gains the two tests. `src/utils/trpc.ts` and the router are untouched. The description quotes the Playwright summary with the new tests named, the `next build` route table showing both pages as server-rendered, and the typecheck and lint results.

The repository's `Testing` workflow runs both of its jobs on the branch, so the pull request shows the `Build + E2E tests` and `Unit tests + typecheck` checks next to the agent's own run. The run's record keeps the HTML the JavaScript-off test received, which is the clearest evidence that the data arrived with the page.

A reviewer decides whether the 404 should keep the custom `Empty` block, which the change replaces with the app's `404.tsx` page and a real status code, and whether the index page should become static with a short `revalidate` instead, trading freshness after `post.add` for a cached response. Both are one-line changes to what the agent wrote.

## Run it on every GitHub issue labelled performance

In the Project that holds the repository, create an automation whose saved prompt is a general version of this page's request and give it a `github` trigger on `issues.labeled` with `performance` in its `labels`. The trigger places the issue after the prompt and fills in nothing, so the prompt tells the run to read the issue that follows, prefetch the queries it names on the server, prove the change with a JavaScript-off test and open a pull request that links the issue. Only labels added by someone who can write to the repository fire it.

An engineer who notices the skeleton on a shared link files the issue naming the page; the run reads the page's queries, adds the prefetch and opens the pull request. A second issue for another page starts a second run on its own branch.

## Why run it on Rush?

Proving server rendering means building the app and reading the HTML before any script runs, which is a build, a database with migrations applied and a browser with JavaScript off. The sandbox does all of that from a clean start and keeps the HTML it got, so the review is about the change, not about whether anyone checked.

The run's record keeps the `next build` output and every Playwright line, so a reviewer sees that the index and post pages moved to server rendering and that the 404 test got a 404. Across many tRPC apps the same request runs at once, each sandbox prefetching its own pages' queries.

## Frequently asked questions

### Why not set ssr: true in createTRPCNext instead?

That renders every query on the server for every page, and the comment in `src/utils/trpc.ts` warns it needs the server's full URL and header forwarding. Prefetching per page with the helpers picks the queries that matter and keeps the client-side behaviour for the rest.

### Do the Date fields survive the trip?

Yes. The helpers are created with the same superjson `transformer` the client uses, so the dehydrated `createdAt` and `updatedAt` rehydrate as `Date` objects and the `toLocaleDateString` calls in the page keep working.

### What happens to the loading skeleton?

It stays in the code for client-side navigations that reach the page before its data, but a direct load arrives with the query already in `success`, so the skeleton is not rendered on the first paint.

### Does the 404 still look like the app?

The change returns `notFound: true`, so Next.js serves `src/pages/404.tsx` with a 404 status. If the team prefers the `Empty` block from the post page, the reviewer can ask the agent to move that markup into `404.tsx` in a follow-up.

## More tRPC jobs

- [Add Structured Logging to a tRPC API](https://getrush.ai/run/add-structured-logging/trpc/)
- [Update the GitHub Actions in a tRPC Project's CI](https://getrush.ai/run/update-github-actions/trpc/)
- [Write Playwright Tests for a tRPC + Next.js App](https://getrush.ai/run/write-playwright-tests/trpc/)

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

- [Split a Pulumi Program Into Stacks Linked by StackReference](https://getrush.ai/run/add-stack-references/pulumi/)
- [Add a Staging Environment to a Cloudflare Worker](https://getrush.ai/run/add-staging-environment/cloudflare-workers/)
- [Add Storybook to an Expo App](https://getrush.ai/run/add-storybook/expo/)

## 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/)
