Supabase collections provide seamless integration between TanStack DB and Supabase, keeping your UI in sync with Postgres through PostgREST queries, mutations, and Realtime subscriptions.
Experimental. The Realtime integration is still being stabilized and may consume more Realtime messages than expected.
Test in orgs on the free plan or with a spend cap. Set realtime: false on individual collections to opt out. To narrow a subscription to only send the needed messages and cut Realtime traffic, try the experimental realtimeUseFilter: true option (see Real-time Subscriptions).
Supabase is an open source Postgres development platform with auto-generated REST APIs (PostgREST), Realtime, Auth, and Row Level Security (RLS).
The @tanstack/supabase-db-collection package allows you to create collections that:
Collections work with your Supabase project as it is and respect Row Level Security. Your Supabase database remains the source of truth: Postgres, RLS, Auth, and the rest of your stack stay unchanged, and no migration is required.
To see a working app, open the example Todo app.
npm install @tanstack/supabase-db-collection @tanstack/react-db @tanstack/query-core @supabase/supabase-js@supabase/supabase-js and @tanstack/query-core are peer dependencies. You also need an existing Supabase project with the client library and environment variables configured. If you have not set that up yet, follow the Supabase getting started guide.
The examples on this page use React. TanStack DB also supports Vue, Angular, Solid, Svelte, and vanilla JavaScript; swap @tanstack/react-db for the package that matches your framework.
Tip: The Supabase UI Library provides a TanStack DB block that generates zod schemas and collections for every table in your database, so you do not have to write them by hand.
Realtime is optional, but required if you want changes from other clients to appear automatically.
Enable Realtime for your table in the Supabase Table Editor, or run this in the SQL Editor:
alter publication supabase_realtime add table "public"."todos";In TanStack DB, a collection corresponds to a Postgres table. Create one collection for each table you want to access from your frontend:
import { createCollection } from '@tanstack/react-db'
import { supabaseCollectionOptions } from '@tanstack/supabase-db-collection'
import { createClient } from '@supabase/supabase-js'
import { z } from 'zod'
const supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY)
const todoSchema = z.object({
id: z.string(),
title: z.string(),
completed: z.boolean(),
})
export const todosCollection = createCollection(
supabaseCollectionOptions({
tableName: 'todos',
schema: todoSchema,
keys: ['id'], // should match your primary key(s)
supabase,
realtime: true,
})
)Query collections with useLiveQuery. Mutations are methods on the collection, so call collection.insert, collection.update, or collection.delete directly. No hooks or mutation objects are required.
import { useLiveQuery, eq } from '@tanstack/react-db'
// todosCollection is the collection created in Basic Usage.
function Todos() {
const { data: todos, isLoading } = useLiveQuery({
query: (q) =>
q
.from({ todo: todosCollection })
.where(({ todo }) => eq(todo.completed, false)),
})
// These apply instantly in the UI and roll back if the server rejects them
const insertTodo = (title: string) => {
todosCollection.insert({ id: crypto.randomUUID(), title, completed: false })
}
const completeTodo = (id: string) => {
todosCollection.update(id, (draft) => {
draft.completed = true
})
}
const deleteTodo = (id: string) => {
todosCollection.delete(id)
}
if (isLoading) return <p>Loading...</p>
return (
<div>
<button onClick={() => insertTodo('Buy milk')}>Add todo</button>
<ul>
{todos.map((todo) => (
<li key={todo.id}>
{todo.title}
<button onClick={() => completeTodo(todo.id)}>Complete</button>
<button onClick={() => deleteTodo(todo.id)}>Delete</button>
</li>
))}
</ul>
</div>
)
}The supabaseCollectionOptions function accepts the following options:
| Option | Type | Default | Description |
|---|---|---|---|
| syncMode | 'on-demand' | 'eager' | 'on-demand' | Controls what is loaded into the collection. 'on-demand' loads only the rows that live queries need, pushing where, orderBy, and limit to PostgREST. 'eager' loads the whole table up front, paging past the PostgREST row cap, and evaluates queries against the local copy. See How Sync Works. |
| realtime | boolean | false | When true, subscribes to Postgres changes and reconciles inserts, updates, and deletes from other clients into the collection. |
| realtimeUseFilter | boolean | false | Experimental. Only applies when realtime is true. When true, each active query's WHERE clause is pushed to the Realtime subscription as a postgres_changes filter for INSERT and UPDATE, so the channel receives the changes those queries care about plus one unfiltered UPDATE listener for rows the collection already holds and one unfiltered DELETE listener; the collection applies its own membership check to those. When false, the collection subscribes to every change on the table and filters client-side. Queries whose WHERE cannot be expressed as a Realtime filter (e.g. or(...)) transparently fall back to the unfiltered subscription. |
| queryClient | QueryClient | shared client | TanStack Query client. If omitted, the browser uses one shared client and the server creates a new client for each collection. When a DbClient materializes the collection, the client's queryClient dependency is used instead. |
| defaultStringCollation | StringCollationConfig | TanStack DB default | Controls how string columns are compared when ordering, so the local order can match your database collation. StringCollationConfig is exported by @tanstack/db. |
| parse | { [column]: (value) => … } | none | Converts a column value received from PostgREST or Realtime into the value your schema describes. PostgREST speaks JSON, so a timestamptz arrives as a string: use parse to turn it into a Date. Applies to rows read, rows returned by inserts and updates, and Realtime payloads. Not called for null values. |
| serialize | { [column]: (value) => … } | none | The reverse of parse: converts a column value held by the collection into the JSON value sent to PostgREST in insert and update bodies, and used to match rows by key on update and delete. Not called for null values. |
PostgREST returns a bigint as a JSON number, which JavaScript rounds to the nearest double above Number.MAX_SAFE_INTEGER (9007199254740991). Values that large cannot round-trip through a bigint column; store them in a text column and convert them with parse and serialize. A Date keeps milliseconds only, so a timestamptz key column with microseconds cannot address its row after parse to a Date; keep such a key as a string.
supabaseCollectionOptions({
tableName: 'events',
keys: ['id'],
schema: eventSchema, // startsAt: z.date()
supabase,
parse: { startsAt: (value) => new Date(value as string) },
serialize: { startsAt: (value) => value.toISOString() },
})The onInsert, onUpdate, and onDelete handlers are provided by the adapter and write through PostgREST; they are not configurable.
Use one active collection per table name on each QueryClient. The table name identifies cached queries on that client. After a collection completes cleanup, a replacement can use the same table name. Its own Supabase client and Realtime options govern the new subscription. Use separate QueryClients when connecting to projects with overlapping table names.
Supabase collections are built on top of Query Collection. Each live query is translated into PostgREST requests, the results are cached with TanStack Query, and Realtime events are merged into the same collection.
Most query operations are translated to PostgREST filters and run server-side. A handful of operations run client-side instead.
| Operation | Notes |
|---|---|
| FROM | Maps to the PostgREST table endpoint. |
| WHERE (eq, gt, gte, lt, lte, inArray, like, ilike, not, isNull) | Translated to PostgREST filter syntax. |
| AND (multiple conditions or chained .where) | Translated to PostgREST filter syntax. A conjunct that cannot be pushed is dropped on its own; the request returns a superset and the client re-filters it. |
| OR and nested AND/OR | Translated to PostgREST's or=(…) syntax. All-or-nothing: if any branch cannot be pushed the whole or is dropped, because dropping one branch would narrow the result and lose matching rows. |
| ORDER BY (on source columns) | Translated to PostgREST ordering. |
| LIMIT | Pushed when PostgREST can apply the filter and ordering for the window. |
| JOIN | Each table is fetched separately. The join key is pushed as an in filter on the second query. |
like and ilike use TanStack's SQL wildcards: % matches any sequence and _ matches one character (for example, ilike(user.name, '%alice%')). Patterns containing a literal * are evaluated client-side because PostgREST interprets * as a wildcard. Filter values containing commas, parentheses, quotes, or backslashes are escaped automatically.
These operations fetch the required rows and process them in memory:
When a window needs local filtering or ordering, the adapter pages through the provider rows needed to compute it. The Collection applies the window after evaluating the local expressions. Bounded requests keep intersecting inArray conditions even when a long request is split into chunks.
PostgREST caps every response at its db-max-rows setting (1000 by default on Supabase). Collection reads, including those made by experimental_queryOnce, page past this cap automatically: the adapter loops with offset, using a one-time count=exact on the first request to fetch the complete matching set (or the caller's limit).
Known limitations of the paging loop:
With realtime: true, the collection subscribes to Postgres changes for its table and reconciles inserts, updates, and deletes made by other clients. The table must be added to the supabase_realtime publication (see Basic Usage).
const todosCollection = createCollection(
supabaseCollectionOptions({
tableName: 'todos',
schema: todoSchema,
keys: ['id'],
supabase,
realtime: true,
// Experimental: only receive changes that match active queries
realtimeUseFilter: true,
})
)Row Level Security applies to Realtime INSERT and UPDATE events, so clients only receive those changes for rows they are allowed to read. Supabase does not apply RLS to Realtime DELETE events: a client can receive the key of a deleted row it could not select, and the collection ignores a delete for a row it does not hold. If the Supabase client has no channel method, realtime is a no-op.
With realtimeUseFilter: true, a query that compares a parsed column or uses a string range makes the adapter subscribe to all table changes the client can read. The live query evaluates its predicate on the Collection's values.
Known limitation: the initial fetch does not wait for the Realtime channel to finish subscribing. A row written in the window between the fetch and the subscription going live can be missed by both.
When the Realtime socket drops, realtime-js rejoins the channel on its own, and the collection keeps its rows and subscription across the outage. While the outage lasts, the collection reports each failed attempt, a channel error or a rejoin that timed out, in its health tree and clears them when the channel rejoins. Changes committed while the socket was down are not replayed, and the rejoin does not refetch. Call collection.reload() or invalidate the collection's queries if an outage can hide changes you need.
insert, update, and delete on the collection apply to the UI immediately, then are sent to Supabase through PostgREST. The adapter owns the persistence handlers:
If the server rejects a mutation (for example, because an RLS policy denies it), the optimistic change is rolled back automatically.
// Applies instantly; rolls back if Postgres or RLS rejects it
todosCollection.update('todo-1', (draft) => {
draft.completed = true
})See Optimistic Mutations for more on mutation lifecycles, transactions, and error handling.
A DbClient gives each request, test, or tenant its own collections and its own QueryClient. Wrap the options in collectionOptions to create a descriptor, then materialize it from a client. A Supabase collection reads through the client's queryClient dependency, so its queries live in that client's cache.
import { QueryClient } from '@tanstack/query-core'
import { DbClient, collectionOptions } from '@tanstack/db'
import { supabaseCollectionOptions } from '@tanstack/supabase-db-collection'
export const todosDescriptor = collectionOptions(
supabaseCollectionOptions({
tableName: 'todos',
schema: todoSchema,
keys: ['id'],
supabase,
})
)
export function createRequestClients() {
const queryClient = new QueryClient()
const dbClient = new DbClient({ queryClient })
return { queryClient, dbClient }
}
const { dbClient } = createRequestClients()
const todos = dbClient.collection(todosDescriptor)
await todos.preload()dbClient.collection(descriptor) returns one collection per descriptor and client. A second DbClient materializes its own collection with its own QueryClient. See Request-scoped QueryClient and SSR and Hydration for how descriptors and clients fit together.
experimental_queryOnce(callback, supabase) runs a TanStack DB query once against Supabase and resolves with the result. It is non-reactive: it does not subscribe to changes. Use it for one-shot fetches such as API routes or form submissions where live updates are not needed.
It is experimental because it reads TanStack DB's internal query representation, which can change between releases.
import { count, eq } from '@tanstack/db'
import { experimental_queryOnce } from '@tanstack/supabase-db-collection'
const [summary] = await experimental_queryOnce(
(q) =>
q
.from({ todo: todosCollection })
.where(({ todo }) => eq(todo.completed, true))
.select(({ todo }) => ({ completed: count(todo.id) })),
supabase
)
// `summary` is undefined when no todo matches
const completedCount = summary?.completed ?? 0It returns a Promise that resolves to exactly what TanStack DB's own queryOnce resolves to for the same query, typed from the query you built.
When the query only computes count, sum, or avg, the server computes it in a single PostgREST request. This applies when all of these are true:
This path needs PostgREST aggregate functions, which are off by default. Enable them once per project:
alter role authenticator set pgrst.db_aggregates_enabled = 'true';
notify pgrst, 'reload config';The result follows TanStack DB's aggregate rules, not SQL's:
Any other query, including min, max, groupBy, and having, runs through TanStack DB's queryOnce over the collections. Their loads push filters, ordering, and limit to PostgREST, and the remaining operations run client-side. The supabase argument is not used on this path.
import { createCollection, useLiveQuery, eq } from '@tanstack/react-db'
import { supabaseCollectionOptions } from '@tanstack/supabase-db-collection'
import { createClient } from '@supabase/supabase-js'
import { z } from 'zod'
const supabase = createClient(SUPABASE_URL, SUPABASE_PUBLISHABLE_KEY)
// Define the schema for a single row
const todoSchema = z.object({
id: z.string(),
title: z.string(),
completed: z.boolean(),
})
type Todo = z.infer<typeof todoSchema>
// Create the collection
export const todosCollection = createCollection(
supabaseCollectionOptions({
tableName: 'todos',
schema: todoSchema,
keys: ['id'],
supabase,
syncMode: 'on-demand',
realtime: true,
})
)
// Use in a component
function TodoList() {
const { data: todos, isLoading } = useLiveQuery({
query: (q) =>
q
.from({ todo: todosCollection })
.where(({ todo }) => eq(todo.completed, false))
.orderBy(({ todo }) => todo.title, 'asc'),
})
const addTodo = (title: string) => {
const todo: Todo = { id: crypto.randomUUID(), title, completed: false }
todosCollection.insert(todo)
}
const toggleTodo = (todo: Todo) => {
todosCollection.update(todo.id, (draft) => {
draft.completed = !draft.completed
})
}
const removeTodo = (id: string) => {
todosCollection.delete(id)
}
if (isLoading) return <p>Loading...</p>
return (
<div>
<button onClick={() => addTodo('Buy milk')}>Add todo</button>
<ul>
{todos.map((todo) => (
<li key={todo.id}>
<input
type="checkbox"
checked={todo.completed}
onChange={() => toggleTodo(todo)}
/>
{todo.title}
<button onClick={() => removeTodo(todo.id)}>Delete</button>
</li>
))}
</ul>
</div>
)
}Will this work with my RLS policies?
Yes. Supabase collections go through PostgREST and Realtime, so your existing RLS policies apply automatically.
What if I do not use RLS?
Without RLS, all Realtime changes broadcast to every client. Depending on whether your app is public or private, that may not be what you want.
Can I use a Supabase collection and supabase-js in parallel?
Yes. The collection uses supabase-js under the hood, so they are compatible. Data fetched directly through supabase-js will not appear in the collection.
Use supabase-js as a fallback for features TanStack DB does not cover, such as database functions through .rpc or complex GROUP BY queries.
Will this work with a custom API server?
This package targets Supabase and PostgREST tables. For custom backends, use Query Collection or write your own collection with the Collection Options Creator guide.