DEV Community

Mohammad Garmabi
Mohammad Garmabi

Posted on Originally published at mohamadgarmabi.github.io

TanStack Query SSE in React: Authenticated Live Updates

TanStack Query SSE in React: authenticated live updates

Polling a dashboard every few seconds is easy to ship. It also means sending requests when nothing has changed and making users wait for the next interval before they see an update.

If the backend already exposes Server-Sent Events (SSE), the browser can receive changes as they happen. The trick is to keep the stream out of your state-management layer:

  • TanStack Query owns the cached server state.
  • SSE delivers one-way updates from the server.
  • Your event handler updates or invalidates the Query cache.

This example uses React, TanStack Query, and tanstack-fetch, an independent community project (not an official TanStack package).

Install and configure the client

npm install tanstack-fetch @tanstack/react-query
Enter fullscreen mode Exit fullscreen mode

The SSE entry includes the normal HTTP methods and api.sse():

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'],
})
Enter fullscreen mode Exit fullscreen mode

This setup is for a browser-only app. Keep browser storage out of server execution in an SSR app.

Load a snapshot first

A stream only contains events sent after it connects. Load the current state with Query:

import { queryOptions } from '@tanstack/react-query'
import { api } from './api'

type Order = { id: string; status: string }

export const ordersOptions = queryOptions({
  queryKey: ['orders'],
  queryFn: ({ signal }) => api.get<Order[]>('/orders', { signal }),
})
Enter fullscreen mode Exit fullscreen mode

Passing Query's signal allows an obsolete HTTP request to be cancelled.

Feed SSE events into the Query cache

Use useSse from tanstack-fetch/react. Wait until the snapshot exists before opening the stream, so a fast event cannot be overwritten by the initial query response.

import { useQuery, useQueryClient } from '@tanstack/react-query'
import { useSse } from 'tanstack-fetch/react'
import { api } from './api'
import { ordersOptions } from './orders'

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

export function useLiveOrders() {
  const queryClient = useQueryClient()
  const query = useQuery(ordersOptions)

  const stream = useSse<OrderEvent>('/orders/stream', {
    client: api,
    enabled: query.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 { ...query, streamStatus: stream.status, close: stream.close }
}
Enter fullscreen mode Exit fullscreen mode

The upsert is idempotent: replaying the same order does not add a duplicate. If an event contains only an ID or a partial payload, invalidate the query instead of guessing the missing data:

void queryClient.invalidateQueries({ queryKey: ['orders'] })
Enter fullscreen mode Exit fullscreen mode

Reconnect needs server-side replay

The sse-resume plugin reconnects after network failures, dropped streams, and 5xx responses. It sends the last received event ID in the Last-Event-ID header. The server must assign ordered IDs and replay events after the supplied cursor.

For example, an SSE event can look like this:

id: 1042
data: {"type":"order.upserted","order":{"id":"order_42","status":"shipped"}}

Enter fullscreen mode Exit fullscreen mode

A reconnect restores the connection, but it cannot recover events unless the server supports replay. The plugin also does not retry 4xx responses such as 401 or 404. Handle an expired token through your auth flow before reconnecting.

Why not native EventSource?

The browser's native EventSource constructor has a withCredentials option, but no general custom headers option. That means it cannot attach a Bearer Authorization header. A fetch-based SSE client can use the same token provider and request configuration as your HTTP calls.

See the MDN EventSource docs for the browser API.

Choose the right transport

  • SSE: server-to-client updates such as notifications and job progress.
  • WebSocket: bidirectional chat, collaboration, or presence.
  • Polling: simple, infrequent updates when a persistent connection is unnecessary.

The Query cache stays the source your components read from. SSE only changes how updates arrive.

Try it: SSE guide · Last-Event-ID recipe · npm · GitHub

Top comments (0)