Framework guidesNext.js fetch vs tanstack-fetch: SSR cookies and hydration
Use tanstack-fetch in Next.js App Router — ssr-forward cookies, absolute baseUrl on the server, React Query dehydrate/hydrate, SSE, and migrate path.
Read the postOctober 12, 2026 · TanStack Start · Router · Query

Stack
TanStack Start · @tanstack/react-router · @tanstack/react-query · tanstack-fetch
TanStack Start shines when Router + Query share context: loaders call ensureQueryData, components call useQuery with the same queryOptions.
The missing piece is a fetch client that already speaks Query’s language. tanstack-fetch is that client — with ssr-forward on the server and the same options in the browser.
| If you need… | Prefer |
|---|---|
Loaders + components share queryOptions | tanstack-fetch |
Router context queryClient | Start / Router pattern |
| SSR cookies | ssr-forward |
| SPA-only Router | same pattern, no SSR plugin |
| tRPC on the same transport | tanstack-fetch/trpc |
npm install tanstack-fetch @tanstack/react-query @tanstack/react-routerPut queryClient on createRouter({ context }). Put HTTP in createFetch. Never fork “loader fetch” vs “component fetch”.
Contract that matters for Query:
isError works)signal throughexport const Route = createFileRoute('/users')({
loader: async () => {
const res = await fetch('/api/users')
return res.json()
},
component: ({ useLoaderData }) => {
const data = useLoaderData()
// separate from useQuery cache — duplicate requests later
},
})// queries/users.ts
import { queryOptions } from '@tanstack/react-query'
import { api } from '~/lib/api'
export const usersQueryOptions = queryOptions({
queryKey: ['users'],
queryFn: ({ signal }) => api.get<User[]>('/users', { signal }),
})// router.tsx
import { createRouter } from '@tanstack/react-router'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
export const queryClient = new QueryClient()
export const router = createRouter({
routeTree,
context: { queryClient },
Wrap: ({ children }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
),
})export const Route = createFileRoute('/users')({
loader: ({ context }) => context.queryClient.ensureQueryData(usersQueryOptions),
component: () => {
const { data } = useQuery(usersQueryOptions)
return <ul>{data?.map((u) => <li key={u.id}>{u.name}</li>)}</ul>
},
})SSR api (Start):
import { createFetch } from 'tanstack-fetch'
import { createSsrForwardInterceptor } from 'tanstack-fetch/plugins'
export const api = createFetch({
baseUrl: process.env.SSR_ORIGIN ? `${process.env.SSR_ORIGIN}/api` : '/api',
source: typeof window === 'undefined' ? 'ssr' : 'browser',
interceptors: [createSsrForwardInterceptor()], // no-op in the browser
})Nested routes: userQueryOptions(params.userId) in loader + useQuery in component. Prefetch in beforeLoad when you want waterfalls avoided.
Rough relative boilerplate (lower is better) — a map of where teams spend time, not a micro-benchmark.
tanstack-fetchloader-only fetch
| Capability | tanstack-fetch | ad-hoc loader fetch |
|---|---|---|
| Router context Query | First-class | DIY |
| ensureQueryData | Native fit | N/A |
| Same options in component | Yes | Duplicate |
| SSR cookies | ssr-forward | Manual |
| Typed errors | FetchError | DIY |
| tRPC transport | Yes | DIY |
| SSE | useSse | DIY |
import { createFetch } from 'tanstack-fetch'
import {
createAuthInterceptor,
createRefreshTokenInterceptor,
createStatusInterceptor,
} from 'tanstack-fetch/plugins'
let expiresAt = 0
const api = createFetch({
baseUrl: '/api',
interceptors: [
createAuthInterceptor({ getToken: () => localStorage.getItem('access_token') }),
createStatusInterceptor({ 403: () => toast.error('Forbidden') }),
],
})
api.use(
'refresh-token',
createRefreshTokenInterceptor({
refresh: async () => {
const body = await api.post<{ accessToken: string; expiresIn: number }>('/auth/refresh', {
interceptors: { eject: ['refresh-token', 'auth'] },
})
localStorage.setItem('access_token', body.accessToken)
expiresAt = Date.now() + body.expiresIn * 1000
},
before: { getExpiresAt: () => expiresAt, skewMs: 60_000 },
after: { enabled: true },
}),
)The plugin keeps one in-flight refresh and retries the failed call — the usual interceptor queue, without the queue code.
const mutation = useMutation({
mutationFn: (input: CreateUserInput) => api.post<User>('/users', { body: input }),
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['users'] }),
})Invalidations stay on the same queryClient from router context.
Browser EventSource cannot set Authorization. tanstack-fetch/sse streams over fetch.
Use useSse in route components (browser). Loaders stay for initial REST/tRPC; streams are client-only.
Status: connecting | connected | disconnected | error.
Recommended Start pattern: tRPC · TanStack Start with createTRPCOptionsProxy and router context.
npx tanstack-fetch migrate --from fetch --framework react --write
npx tanstack-fetch doctor --dir ./srcMove loader fetch calls into queryOptions + ensureQueryData incrementally.
src/
lib/api.ts
queries/*.ts
router.tsx # context.queryClient
routes/users.tsx # loader + component
routes/users.$id.tsxtanstack-fetchtanstack-fetch/sse + useSsecreateFetch across packagesqueryClient on router contextqueryOptions modulesensureQueryData / prefetchQuerycreateFetch with SSR branchnpm install tanstack-fetch @tanstack/react-query @tanstack/react-router
npx tanstack-fetch doctor --dir ./srcSame deep-dive format for every stack:
Framework guides·3 min read
Use tanstack-fetch in Next.js App Router — ssr-forward cookies, absolute baseUrl on the server, React Query dehydrate/hydrate, SSE, and migrate path.
Framework guides·3 min read
Replace axios unwrap glue with tanstack-fetch — FetchProvider, useFetch, useSse, React Query, refresh-token, migrate CLI, and a full side-by-side comparison.
Tutorials·7 min read
Six TanStack Start 1.0 data fetching patterns: direct fetching, shared loaders, SSR auth, mutations, central error handling and live SSE updates.