TanStack Query streamedQuery: NDJSON Streaming in React
Stream NDJSON responses into TanStack Query with experimental_streamedQuery and tanstack-fetch. Learn cancellation, refetch behavior, and reliability trade-offs.
Read the postNovember 29, 2026 · TanStack Query · SSE · React
A dashboard that shows orders, notifications, or job progress usually starts with polling: fetch the same endpoint every few seconds and replace the screen with the latest response.
Polling is simple, but it creates requests when nothing has changed and makes updates wait for the next interval. If the server already emits Server-Sent Events (SSE), the browser can receive changes as they happen.
The useful architecture is not “replace TanStack Query with a stream”. Keep the responsibilities separate:
This tutorial builds that pattern with React, TanStack Query, and tanstack-fetch. tanstack-fetch is an independent community project, not an official TanStack package.
SSE is a good fit when the server needs to push updates but the browser does not need to send messages over the same connection.
| Requirement | Good starting point |
|---|---|
| Load a resource or submit a form | HTTP + TanStack Query |
| Server pushes notifications or status changes | SSE |
| Client and server both send messages | WebSocket |
| Stream newline-delimited JSON from an HTTP request | NDJSON with api.stream() |
For an order dashboard, Query can fetch the current list once. The SSE connection then carries only the changes. The cache remains the single place your React components read from.
Install the HTTP client and Query:
npm install tanstack-fetch @tanstack/react-queryThe SSE API is exported from tanstack-fetch/sse. It includes the regular HTTP methods as well as api.sse():
// src/lib/api.ts
import { createFetch } from 'tanstack-fetch/sse'
export const api = createFetch({
baseUrl: import.meta.env.VITE_API_URL,
getToken: () => localStorage.getItem('access_token'),
plugins: ['sse-resume'],
})This example is for a browser-only client. If your app also renders on the server, do not call browser storage from server execution. Keep the browser client in a client-only boundary, or create a request-scoped server client for SSR.
The getToken callback supplies the current access token for requests. The sse-resume plugin handles reconnects after network failures and dropped streams. We will cover the server-side part of resuming in section 4.
A stream only tells you what happens after it connects. It does not automatically contain the orders that already exist.
Start with a normal query:
// src/queries/orders.ts
import { queryOptions } from '@tanstack/react-query'
import { api } from '../lib/api'
export type Order = {
id: string
status: 'pending' | 'paid' | 'shipped' | 'cancelled'
updatedAt: string
}
export const ordersQueryOptions = queryOptions({
queryKey: ['orders'],
queryFn: ({ signal }) => api.get<Order[]>('/orders', { signal }),
staleTime: 30_000,
})Passing Query's signal lets it cancel an obsolete HTTP request. The query key ['orders'] is also the cache entry that the SSE handler will update.
Define the messages your server sends. In this example, every upsert event contains the complete order, while a delete event contains its ID:
type OrderEvent =
| { type: 'order.upserted'; order: Order }
| { type: 'order.deleted'; orderId: string }Now connect the stream to the same Query cache:
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { useSse } from 'tanstack-fetch/react'
import { api } from '~/lib/api'
import { ordersQueryOptions, type Order } from '~/queries/orders'
type OrderEvent =
| { type: 'order.upserted'; order: Order }
| { type: 'order.deleted'; orderId: string }
export function useLiveOrders() {
const queryClient = useQueryClient()
const ordersQuery = useQuery(ordersQueryOptions)
const stream = useSse<OrderEvent>('/orders/stream', {
client: api,
// Wait for the first HTTP snapshot before applying live events.
enabled: ordersQuery.data !== undefined,
onMessage: (message) => {
if (message.type === 'order.upserted') {
queryClient.setQueryData<Order[]>(['orders'], (current) => {
if (!current) return current
const exists = current.some((order) => order.id === message.order.id)
return exists
? current.map((order) =>
order.id === message.order.id ? message.order : order,
)
: [message.order, ...current]
})
}
if (message.type === 'order.deleted') {
queryClient.setQueryData<Order[]>(['orders'], (current) =>
current?.filter((order) => order.id !== message.orderId),
)
}
},
})
return {
...ordersQuery,
streamStatus: stream.status,
streamError: stream.error,
closeStream: stream.close,
}
}The enabled option is intentional. It prevents an early stream event from racing with the initial HTTP response and then being overwritten by that response.
The cache update is also idempotent for an upsert: receiving the same order twice does not create a duplicate row. If the event contains only an ID or a partial change, do not guess the missing fields. Invalidate the query and let the server return the authoritative state:
void queryClient.invalidateQueries({ queryKey: ['orders'] })Use setQueryData when the event contains enough information to update the cached value. Use invalidation when the server must calculate the new state.
A connection can recover while the client cache is still missing events.
Imagine the browser disconnects for ten seconds. Three orders change during that time. Reopening the stream does not prove that the browser received those three changes.
The sse-resume plugin reconnects after a network error, a mid-stream drop, or a 5xx response. It sends the ID of the last event it received in the Last-Event-ID header. The default retry delay is one second, and the retry budget is maxRetries (default 2), which resets when another event arrives. A 4xx response such as 401 or 404 is not retried.
For replay to work, the server must:
Last-Event-ID request header when a connection opens.A minimal SSE message looks like this:
id: 1042
data: {"type":"order.upserted","order":{"id":"order_42","status":"shipped"}}The SSE client tracks the last event ID from each event. On reconnect, the server can use that cursor to send only the events the client missed.
If the server does not support replay, reconnecting restores the connection but cannot restore missing data. In that case, invalidate the Query key after reconnect or fetch a fresh snapshot.
The native browser EventSource constructor accepts a URL and an optional withCredentials setting. It does not provide a general headers option, so it cannot attach a custom Bearer Authorization header.
That is a problem when your API expects token-based authentication. You can use cookie credentials when your server's cookie and CORS setup supports them, but withCredentials is not a way to add arbitrary headers.
The fetch-based SSE client in tanstack-fetch/sse uses the Fetch API, so it can use the same token provider, headers, and interceptors as your regular HTTP requests. See the MDN EventSource reference for the browser API's constructor options.
One important boundary: the resume plugin deliberately does not retry 4xx responses. If a stream receives 401, handle the expired credential through your auth/refresh flow, then reconnect with a valid token. Repeating the same unauthorized request will not fix it.
The React useSse hook exposes connecting, connected, disconnected, and error states, along with the last message and a close() function:
function OrdersPage() {
const {
data: orders,
isPending,
streamStatus,
streamError,
closeStream,
} = useLiveOrders()
if (isPending) return <p>Loading orders…</p>
return (
<section>
<header>
<span>Live updates: {streamStatus}</span>
<button type="button" onClick={closeStream}>
Stop live updates
</button>
</header>
{streamStatus === 'error' && (
<p role="alert">{streamError?.message}</p>
)}
<ul>
{orders?.map((order) => (
<li key={order.id}>
{order.id}: {order.status}
</li>
))}
</ul>
</section>
)
}The hook closes its subscription when the component unmounts or its connection options change. You can also call closeStream() when the user explicitly turns live updates off.
SSE is not a replacement for Query's cache. It is a way to deliver changes to the cache without repeatedly asking the server whether anything changed.
TanStack Query does not open an SSE connection by itself. Use an SSE client or hook to receive events, then update the Query cache with queryClient.setQueryData or invalidate the relevant query.
The native browser EventSource API does not expose a custom headers option. A fetch-based client such as tanstack-fetch/sse can send an Authorization header through its token provider or request configuration.
No. It gives the server a cursor. The server must store or otherwise be able to replay events after that cursor. Without server-side replay, reconnect only restores the connection.
Only when the event contains enough data to make a correct update. If it contains a partial notification, invalidate the query and let the server provide the complete state.
The rule is simple: let HTTP load the snapshot, let SSE deliver changes, and let TanStack Query remain the source your components read from.
·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.
·5 min read
Build typed React WebSocket updates with TanStack Query: load snapshots, update the cache, reconnect safely, and authenticate browser sockets.