TanStack Query SSE in React: Authenticated Live Updates
Build authenticated Server-Sent Events in React with TanStack Query. Update the cache, resume after disconnects with Last-Event-ID, and avoid polling.
Read the postNovember 26, 2026 · SvelteKit · SSR · Security
A bug in server-side rendering can be more serious than a failed API request: one visitor's authenticated request can accidentally reuse another visitor's credentials.
The risky pattern is familiar. Create an API client once at module scope, attach request cookies or an access token to it, and reuse it for every incoming request. That can work in a browser, where a tab belongs to one signed-in user. It is not a safe default on a Node.js server, where the same module instance can serve many users concurrently.
This guide shows how to structure a SvelteKit app with one browser client and a fresh server client for each request, using the current tanstack-fetch 2.2.1 API.
tanstack-fetch is an independent open-source project. It is not an official TanStack package.
Imagine two requests arriving close together:
/account with cookie session=alice./account with cookie session=bob.If request-specific credentials are stored on that shared object, timing can decide which credentials are sent upstream. The result can be a cross-user data leak.
The rule is simple:
For browser components, create the client without capturing a server request. Read the browser token only when the code runs in the browser:
// src/lib/api.ts
import { browser } from '$app/environment'
import { PUBLIC_API_URL } from '$env/static/public'
import { createFetch } from 'tanstack-fetch'
import { createAuthInterceptor } from 'tanstack-fetch/plugins'
export const api = createFetch({
baseUrl: PUBLIC_API_URL,
interceptors: [
createAuthInterceptor({
getToken: () =>
browser && typeof localStorage !== 'undefined'
? localStorage.getItem('access_token')
: null,
}),
],
})This client is intended for browser-side calls. The browser guard prevents server rendering from trying to read localStorage. Do not use this module-level client to forward a visitor's incoming server cookies.
SvelteKit's Cookies object is request-scoped. Pass it into a factory and create a fresh client for that load or endpoint:
// src/lib/api.server.ts
import { PUBLIC_API_URL } from '$env/static/public'
import type { Cookies } from '@sveltejs/kit'
import { createFetch } from 'tanstack-fetch'
import {
createSsrForwardInterceptor,
createTraceInterceptor,
} from 'tanstack-fetch/plugins'
export const createServerApi = (cookies: Cookies) =>
createFetch({
baseUrl: PUBLIC_API_URL,
source: 'ssr',
incoming: {
cookie: cookies
.getAll()
.map(({ name, value }) => name + '=' + value)
.join('; '),
},
interceptors: [
createTraceInterceptor(),
createSsrForwardInterceptor(),
],
})The important detail is not the helper name. It is where the client is created: inside the factory call for the current request. The cookie string is captured by that request's client, not written to shared module state.
The ssr-forward interceptor copies the incoming cookie header onto the outgoing server request. It skips browser-sourced requests. On the server, use an absolute API baseUrl, not a browser-relative path.
Import the server-only module from a server load file:
// src/routes/account/+page.server.ts
import type { PageServerLoad } from './$types'
import { createServerApi } from '$lib/api.server'
type Account = {
id: string
email: string
}
export const load: PageServerLoad = async ({ cookies }) => {
const api = createServerApi(cookies)
const account = await api.get<Account>('/account')
return { account }
}Each invocation creates its own client with the cookies belonging to that request. The same factory can be used in a +server.ts endpoint by passing that endpoint's event.cookies.
Do not export a single api instance from api.server.ts if that instance contains request-specific cookies or headers. Export a factory instead.
The Svelte adapter has a separate job: making a client available to components through Svelte context.
In a root layout, configure the browser/component client with setFetchClient:
<!-- src/routes/+layout.svelte -->
<script lang="ts">
import { api } from '$lib/api'
import { setFetchClient } from 'tanstack-fetch/svelte'
setFetchClient({ client: api })
</script>
<slot />Then retrieve it inside a component:
<script lang="ts">
import { useFetch } from 'tanstack-fetch/svelte'
import { createQuery } from '@tanstack/svelte-query'
type Project = { id: string; name: string }
const api = useFetch()
const projects = createQuery({
queryKey: ['projects'],
queryFn: ({ signal }) => api.get<Project[]>('/projects', { signal }),
})
</script>
{#if $projects.isPending}
<p>Loading projects…</p>
{:else if $projects.isError}
<p>Could not load projects.</p>
{:else}
<ul>
{#each $projects.data ?? [] as project (project.id)}
<li>{project.name}</li>
{/each}
</ul>
{/if}In SvelteKit server rendering, the adapter relies on component context rather than a module-level fallback. Since 2.2.1, its module fallback is browser-only: a server module is shared across requests, so storing one request's client there could expose its token or cookies to another request.
Important: useFetch() is for component context. In +page.server.ts and +server.ts, use the request-scoped createServerApi(cookies) factory instead.
Version 2.2.1 fixed a Svelte SSR isolation issue. The adapter no longer keeps a module-level fallback client on the server. On the server, the client is resolved from Svelte component context; the module fallback is used only in the browser.
That fix closes an unsafe fallback path inside the adapter. It does not make every application-level singleton safe. If your own server module exports a client that captures a user's cookies, authorization header, or mutable token, you can still create the same class of bug yourself.
The safe application pattern remains:
setFetchClient and useFetch.createServerApi(cookies) per request.A useful regression test should prove that concurrent requests do not share credentials.
At minimum, exercise the server API factory with two different cookie jars and assert that each outgoing request receives only its own cookie:
| Incoming request | Expected upstream cookie |
|---|---|
Alice: session=alice | session=alice |
Bob: session=bob | session=bob |
Run the requests concurrently as well as sequentially. A sequential test can miss a race that appears only when two requests overlap.
Also check that:
localStorage during SSR.The project includes a SvelteKit scaffold:
npx tanstack-fetch migrate --from fetch --framework sveltekit --writeIt creates a browser src/lib/api.ts, a server src/lib/api.server.ts using ssr-forward and cookies, and shared Query options. Review the generated files and keep the browser/server boundary intact when adapting them to your app.
incoming credentials come from that request's cookies object.baseUrl.createSsrForwardInterceptor() is configured on the server client.setFetchClient / useFetch through Svelte context.createServerApi(cookies), not useFetch().For the broader framework setup, see the Svelte & SvelteKit guide, the SSR cookie-forwarding guide, and the SvelteKit fetch comparison.
The takeaway: a client can be reusable without being global. Reuse the factory and configuration; create a fresh authenticated client for each server request.
·6 min read
Build authenticated Server-Sent Events in React with TanStack Query. Update the cache, resume after disconnects with Last-Event-ID, and avoid polling.
·7 min read
Stream NDJSON responses into TanStack Query with experimental_streamedQuery and tanstack-fetch. Learn cancellation, refetch behavior, and reliability trade-offs.
·8 min read
TanStack Query error handling with fetch: why fetch never throws on 404 or 500, typed errors with Register, global toasts, error boundaries, form errors and retry rules.