Skip to content

TanStack Query SSE in React: authenticated live updates ​

November 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:

  • TanStack Query owns the cached server state and the initial HTTP snapshot.
  • SSE delivers one-way updates from the server.
  • Your event handler applies each update to the Query cache or invalidates it when the event is incomplete.

This tutorial builds that pattern with React, TanStack Query, and tanstack-fetch. tanstack-fetch is an independent community project, not an official TanStack package.

When should you use SSE with TanStack Query? ​

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.

RequirementGood starting point
Load a resource or submit a formHTTP + TanStack Query
Server pushes notifications or status changesSSE
Client and server both send messagesWebSocket
Stream newline-delimited JSON from an HTTP requestNDJSON 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.

1. Install and create an authenticated SSE client ​

Install the HTTP client and Query:

bash
npm install tanstack-fetch @tanstack/react-query

The SSE API is exported from tanstack-fetch/sse. It includes the regular HTTP methods as well as api.sse():

ts
// 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.

2. Load the initial snapshot with TanStack Query ​

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:

ts
// 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.

3. Update the Query cache when an SSE event arrives ​

Define the messages your server sends. In this example, every upsert event contains the complete order, while a delete event contains its ID:

ts
type OrderEvent =
  | { type: 'order.upserted'; order: Order }
  | { type: 'order.deleted'; orderId: string }

Now connect the stream to the same Query cache:

tsx
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:

ts
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.

4. Reconnect is not the same as replay ​

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:

  1. Give each event a stable, ordered ID.
  2. Read the Last-Event-ID request header when a connection opens.
  3. Replay events after that ID before sending new live events.

A minimal SSE message looks like this:

text
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.

5. Why not use the native EventSource API? ​

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.

6. Show the connection state and close the stream ​

The React useSse hook exposes connecting, connected, disconnected, and error states, along with the last message and a close() function:

tsx
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.

When should you choose SSE, WebSocket, or polling? ​

  • Choose SSE for notifications, order status, job progress, and dashboards where the server pushes changes in one direction.
  • Choose WebSocket when the client also needs to send messages over the same live connection, as in chat or collaboration.
  • Choose polling when updates are infrequent, a live connection is unnecessary, or the server does not expose a streaming endpoint.

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.

Frequently asked questions ​

Can TanStack Query consume SSE directly? ​

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.

Does SSE support authentication headers in React? ​

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.

Does Last-Event-ID guarantee that no event is lost? ​

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.

Should every SSE message update the cache? ​

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.

Try the pattern ​

The rule is simple: let HTTP load the snapshot, let SSE deliver changes, and let TanStack Query remain the source your components read from.

MIT Licensed · Created by Mohammad Garmabi · Not an official TanStack package