Type-safe PocketBase integration with TanStack DB
A TypeScript library that seamlessly integrates PocketBase with TanStack DB, providing:
- 🔥 Real-time subscriptions with automatic synchronization
- 🎯 Full TypeScript type safety for queries and relations
- ⚡ Reactive collections with TanStack DB
- ✨ Optimistic mutations with insert/update/delete support
- 🎨 React hooks for easy component integration
- 🔗 Type-safe joins and relation fetching into their own collections
- Installation
- Quick Start
- Core Concepts
- API Reference
- Usage Examples
- TypeScript
- Best Practices
- Configuration
npm install pbtsdb pocketbase @tanstack/db @tanstack/react-dbpocketbase>= 0.22.0@tanstack/db>= 0.12.1@tanstack/react-db>= 0.5.5 (optional; only forcreateReactProvider)reactandreact-dom>= 18.0.0 (optional)
All peer dependencies use minimum version constraints; newer versions should work. The
non-React entry point pbtsdb/core needs neither react nor @tanstack/react-db.
Let's build a real-world blog with posts, authors, and comments using pbtsdb.
First, generate your types from PocketBase. Install pocketbase-schema-generator as a PocketBase hook to auto-generate types on schema changes.
// schema.ts - Auto-generated from PocketBase
interface Post {
id: string;
title: string;
content: string;
author: string; // FK to users
published: boolean;
created: string;
updated: string;
}
interface User {
id: string;
username: string;
email: string;
avatar?: string;
created: string;
updated: string;
}
interface Comment {
id: string;
post: string; // FK to posts
author: string; // FK to users
text: string;
created: string;
updated: string;
}
// Schema declaration for pbtsdb
type BlogSchema = {
posts: {
type: Post;
relations: { author?: User };
};
users: {
type: User;
relations: {};
};
comments: {
type: Comment;
relations: {
post?: Post;
author?: User;
};
};
}// app.tsx
import PocketBase from 'pocketbase';
import { createCollection, createReactProvider } from 'pbtsdb';
const pb = new PocketBase('http://localhost:8090');
// Create collections with automatic type inference
const c = createCollection<BlogSchema>(pb);
const users = c('users', {});
export const { Provider, useStore } = createReactProvider({
users,
posts: c('posts', {
omitOnInsert: ['created', 'updated'] as const,
relations: { author: users },
alwaysFetchRelations: ['author'],
}),
comments: c('comments', {
omitOnInsert: ['created', 'updated'] as const,
relations: { author: users },
alwaysFetchRelations: ['author'],
}),
});
export function App() {
return (
<Provider>
<BlogDashboard />
</Provider>
);
}// BlogDashboard.tsx
import { useLiveQuery } from '@tanstack/react-db';
import { eq } from '@tanstack/db';
import { materialize } from 'pbtsdb';
import { useStore } from './app';
export function BlogDashboard() {
const [posts, users] = useStore('posts', 'users');
const { data: allPosts, isLoading } = useLiveQuery((q) =>
q.from({ posts })
.orderBy(({ posts }) => posts.created, 'desc')
.select(({ posts }) => ({
...posts,
author: materialize(
q.from({ u: users }).where(({ u }) => eq(u.id, posts.author)).findOne()
),
}))
);
if (isLoading) return <div>Loading posts...</div>;
return (
<div>
<h1>Blog Posts</h1>
{allPosts?.map(post => (
<article key={post.id}>
<h2>{post.title}</h2>
<p>{post.content}</p>
{/* Author was filed into the users collection by alwaysFetchRelations */}
<small>By {post.author?.username}</small>
</article>
))}
</div>
);
}// PostWithComments.tsx
import { useLiveQuery } from '@tanstack/react-db';
import { eq } from '@tanstack/db';
import { useStore } from './app';
import { materialize, newRecordId } from 'pbtsdb';
export function PostWithComments({ postId }: { postId: string }) {
const [comments, posts, users] = useStore('comments', 'posts', 'users');
// Real-time comments for this post
const { data: postComments } = useLiveQuery((q) =>
q.from({ comments })
.where(({ comments }) => eq(comments.post, postId))
.orderBy(({ comments }) => comments.created, 'desc')
.select(({ comments }) => ({
...comments,
author: materialize(
q.from({ u: users }).where(({ u }) => eq(u.id, comments.author)).findOne()
),
}))
);
const handleAddComment = (text: string, authorId: string) => {
comments.insert({
id: newRecordId(),
post: postId,
author: authorId,
text
});
// Comment appears instantly (optimistic), syncs to PocketBase in background
};
return (
<div>
<h3>Comments ({postComments?.length || 0})</h3>
{postComments?.map(comment => (
<div key={comment.id}>
<strong>{comment.author?.username}:</strong>
<p>{comment.text}</p>
</div>
))}
<CommentForm onSubmit={handleAddComment} />
</div>
);
}That's it! You now have a real-time blog with:
- ✅ Type-safe queries
- ✅ Automatic real-time updates
- ✅ Optimistic mutations
- ✅ Related data read from its own collection, no embedded copies
Collections are reactive data stores that automatically sync with PocketBase:
// Create a collection using the curried API
const c = createCollection<MySchema>(pb);
const booksCollection = c('books', {});
// Collections automatically:
// - Fetch data from PocketBase
// - Subscribe to real-time updates
// - Update React components when data changesCollections manage subscriptions automatically based on query lifecycle:
// Collections are lazy - no subscription until queried
const c = createCollection<MySchema>(pb);
const booksCollection = c('books', {});
// Subscription starts automatically when query becomes active
const { data } = useLiveQuery((q) =>
q.from({ books: booksCollection })
);
// ✅ Subscribed to changes while component is mounted
// ✅ Unsubscribes automatically when component unmountsSubscription Lifecycle:
- Lazy: No subscription starts until the first
useLiveQueryusing the collection renders - Automatic: Subscription starts when first subscriber mounts, stops when last subscriber unmounts
- Shared: Multiple components using the same collection share one subscription
- No manual control needed: The collection handles all subscription management internally
pbtsdb runs its own realtime connection. When the connection drops, it reconnects with backoff and refetches every live query, because PocketBase does not replay events missed during the gap. A server that supports pbtsdb's resume extension (?resume=<clientId>&after=<seq> on the SSE URL, resumed: true in PB_CONNECT, seq on each event) replays the gap instead, and no refetch runs.
pbtsdb's connection is independent of pb.realtime. When pb.authStore changes to another auth record (login, logout, switching users), pbtsdb forgets the connection's server-side session and reconnects at once, re-sending every subscribed topic under the new auth; every ready collection reloads once that POST succeeds, the same as a non-resumed reconnect. A token refresh for the same record changes nothing. PocketBase would otherwise answer the next subscriptions POST with a 403, or keep serving the previous user's data.
Call resetRealtime(pb) yourself for a change the auth store cannot see, such as pointing pb at another server:
import { disconnectRealtime, resetRealtime } from 'pbtsdb';
resetRealtime(pb); // forget the session and re-subscribe every open topic now
disconnectRealtime(pb); // close the connection and keep it closed
resetRealtime(pb); // open it again; every ready collection reloadsdisconnectRealtime(pb) closes the connection and keeps it closed until resetRealtime(pb). Collections keep working over REST and keep their subscriptions registered. Use it at logout, or at startup where realtime is not wanted, such as an embedded view.
After a drop, pbtsdb waits longer between each retry: the delay doubles from 250 ms up to 30 s, with random jitter so many clients do not retry at the same time. Use setRealtimeBackoff(pb, fn) to set your own delays. fn gets the retry number (0 for the first retry after a drop) and returns the delay in milliseconds. undefined restores the default.
A long delay can keep the app offline after the network returns. Call reconnectRealtime(pb) when you know the network is back. It retries at once and keeps the session, so a server with resume support replays the gap. It does nothing unless a retry is waiting.
import { reconnectRealtime, setRealtimeBackoff } from 'pbtsdb';
setRealtimeBackoff(pb, (attempt) => Math.min(60_000, 1000 * 2 ** attempt));
// for example, from a connectivity listener or an app-foreground handler
reconnectRealtime(pb);subscribeTopic(pb, topic, onMessage) listens to a custom realtime topic over the same connection as the collections, with the same reconnect, resume and auth handling. onMessage is called with no argument: a topic message, such as a data-free change signal, says only that something changed, and you fetch what you need. The returned promise resolves once the server has the topic, so subscribe first and fetch after: a change the server reports on the topic cannot fall between the two. It resolves to an unsubscribe function. It rejects an empty topic, and a topic over 2500 characters with RealtimeTopicTooLongError. A message whose data is not JSON is dropped. If the subscriptions request fails with no response, a server error, or a 403, 404, 408 or 429, the promise stays pending: pbtsdb reconnects, and the reconnect sends the topic again. (PocketBase answers 404 when it no longer holds the client, for example after its 30-minute forced close, and 403 when the auth changed.) Another 4xx, such as a 400, rejects it. To stop waiting, pass { signal } as the fourth argument and abort it; the topic is then dropped and the promise rejects with RealtimeSubscribeAbortedError. Both error classes are exported for instanceof checks.
import { subscribeTopic } from 'pbtsdb';
const unsubscribe = await subscribeTopic(pb, 'collection/books', () => void rerun());
await rerun(); // the first fetch, after the topic is confirmed
await unsubscribe();A PocketBase JS hook can send such a signal through $app.subscriptionsBroker(), for example {} on collection/<name> after a write commits, so a client can rerun a custom query without a record-level subscription.
To keep a collection live on such topics, give it liveTopics. PocketBase sends no record events for a view collection, so a view needs this to show changes in the tables it reads:
const authorBookCounts = c('author_book_counts', {
syncMode: 'on-demand',
liveTopics: ['collection/author_book_counts'],
});While the collection syncs, it subscribes to each topic. The first message opens a window of LIVE_TOPIC_WINDOW_MS (100 ms), and the collection reloads once when the window closes. Messages during the window do not extend it, so a steady stream of messages still reloads once per window. When the server confirms a topic after a load started, the collection reloads once more, because a write between that load and the confirmation sends a message that this client does not get. If the subscriptions request fails in one of those ways, the topic stays registered and the reconnect that follows sends it again; the collection then reloads when the server confirms it. A topic the server refuses with another 4xx, such as a 400, is logged and stays off. The topics close when the collection is cleaned up, also while one still waits for the server. An empty topic or a topic over 2500 characters throws when the collection is built.
Use it with a server that sends a message on the view's topic when a source table of the view changes. pbtsdb cannot know which tables a view reads. If the server sends change signals only to signed-in clients, a liveTopics collection on a signed-out page never reloads.
By default pbtsdb opens its realtime connection with the global EventSource. That sends no auth header, and React Native has no global EventSource. Use setRealtimeEventSource(pb, factory) to open the connection your own way. Call it before the first collection subscribes.
pbtsdb calls the factory on each connect, so read the token inside it; a refreshed token is then sent on the next reconnect. The object the factory returns (EventSourceLike) must:
- dispatch each SSE event to the listeners added with
addEventListener(eventName, …), withdataandlastEventIdset; - dispatch
errorthroughaddEventListenerwhen the stream ends for any reason, including a clean close by the server; - not reconnect itself. pbtsdb calls
close()on the firsterror, and opens a new connection through the factory.
The eventsource package meets these rules. It dispatches error when the stream ends, and close() cancels its own retry:
import { setRealtimeEventSource } from 'pbtsdb';
import { EventSource } from 'eventsource';
setRealtimeEventSource(pb, (url) =>
new EventSource(url, {
fetch: (input, init) =>
fetch(input, {
...init,
headers: {
...init.headers,
...(pb.authStore.token ? { Authorization: pb.authStore.token } : {}),
},
}),
})
);react-native-sse (1.2) does not meet them. When the server ends the stream cleanly, it dispatches nothing, and after pollingInterval it opens a new connection itself, with the old URL and headers. Its re-poll calls open(), so a subclass can change that re-poll into an error:
import RNEventSource from 'react-native-sse';
class PbEventSource extends RNEventSource<string> {
private opened = false;
open() {
if (this.opened) {
this.dispatch('error', { type: 'error', message: 'stream ended', xhrState: 4, xhrStatus: 0 });
return;
}
this.opened = true;
super.open();
}
}
setRealtimeEventSource(pb, (url) =>
new PbEventSource(url, {
headers: pb.authStore.token ? { Authorization: pb.authStore.token } : {},
pollingInterval: 1,
})
);Two problems are visible only to pbtsdb: the realtime stream dropping while REST still works, so lists look fine but stop updating; and a query sleeping in its load retry backoff, so a list sits in "loading" with no reason shown. getSyncStatus(pb) reports both, for every collection of one client:
import { getSyncStatus, subscribeSyncStatus } from 'pbtsdb';
const status = getSyncStatus(pb);
// {
// realtime:
// | { state: 'disabled' } // disconnectRealtime(pb), or no collection has subscribed yet
// | { state: 'connecting' } // the first connection of a session is opening
// | { state: 'connected' } // stream open, PB_CONNECT received
// | { state: 'reconnecting'; attempt: number; nextRetryAt: number; since: number },
// loads: {
// retrying: number, // live queries sleeping in loadRetryDelays backoff
// failingSince?: number, // when the oldest of them first failed, epoch ms
// failed: number, // live queries whose load ended in a 4xx that is not retried
// },
// }
const stop = subscribeSyncStatus(pb, status => console.log(status));reconnecting means the stream was up and dropped, or a retry never came up, and the next retry is scheduled; the first connection of a session reports connecting instead. nextRetryAt and since are epoch milliseconds, and nextRetryAt changes only when a new retry is scheduled. disabled is not a problem state: it is what disconnectRealtime(pb) asks for, and what an app sees before login.
retrying counts only demands a live query still holds; a parked subset or an unmounted query is never counted. failed is separate because a 403 or 404 is an answer, not an outage; the count drops when the query reloads or unmounts.
The snapshot is stable: getSyncStatus(pb) returns the same object, with the same nested objects, until a value changes. The React entry point wraps it in useSyncStatus(pb):
import { useSyncStatus } from 'pbtsdb';
function SyncNotice() {
const { realtime, loads } = useSyncStatus(pb);
if (realtime.state === 'reconnecting') return <p>Live updates paused, reconnecting…</p>;
if (loads.retrying > 0) return <p>Retrying {loads.retrying} queries…</p>;
return null;
}The shape of SyncStatus is public and changes only in a major release.
In on-demand mode a live query's subset is released when the last subscriber unmounts, after a grace window of subsetGcTime milliseconds (default 5000). A query with an equal request that mounts within the window reuses the rows with no request. A query with a limit or a cursor (a page) reuses the rows too, but fetches its window again before it resolves: a row deleted or changed while the subset was parked can leave a gap that only the server can fill. Realtime keeps the parked rows fresh, and rows a parent filed through a relation stay for the same window, so a panel that mounts and unmounts quickly costs no refetch. collection.reload() releases every parked subset, and a subset whose reload fetch is cancelled by an unmount is released too, so the next mount fetches. An auth change releases every waiting subset and every accepted row at once and reloads every live subset under the new auth, whether or not realtime is connected, so a load right after a logout never reuses the previous user's rows and the order of authStore.clear() and disconnectRealtime(pb) does not matter. Set subsetGcTime: 0 to release a subset as soon as it unloads; 0 also keeps accepted rows until a reload or idle instead of expiring them.
A subset load that fails is retried with backoff (loadRetryDelays, default 1, 2, 4, 8, 15 and then every 30 seconds) until it succeeds, so a live query stays loading through an outage instead of entering an error state it cannot leave. A collection.reload() or a realtime reconnect retries at once, also while another reload is running. A response the server gave on purpose, a 4xx other than 401, 408 or 429, is not retried and reports its error. A 401 waits for the next auth change and then retries. Delays carry a little jitter so many queries do not retry in lockstep.
A live query that reports a non-retryable error stays in the error state: collection.reload() refetches the rows, but TanStack DB does not clear the query's error. To retry, build a new query. With useLiveQuery, add a counter to the dependency array and increment it on retry:
const [attempt, setAttempt] = useState(0);
const query = useLiveQuery((q) => q.from({ posts }), [attempt]);
const retry = () => setAttempt((n) => n + 1);Every collection is either eager (the default) or on-demand:
const authors = c('authors', {}); // eager: one full fetch, then realtime
const books = c('books', { syncMode: 'on-demand' }); // on-demand: fetch what queries ask forAn eager collection loads all of its rows on first use and answers every query
from memory. An on-demand collection translates each live query's where,
orderBy, and limit into a PocketBase request, so only the rows a query asks
for enter the store, and different filters are cached under different keys.
Use on-demand for large collections; realtime keeps both modes current once rows
are loaded.
An on-demand where can use these TanStack DB operators. Any other operator throws.
| Operator | PocketBase filter |
|---|---|
eq, gt, gte, lt, lte |
=, >, >=, <, <= |
inArray |
= joined with ` |
like, ilike |
~ (case-insensitive on the server) |
isNull, isUndefined |
= null |
and, or |
&&, ` |
not |
Negates the operator inside it, for example not(eq(...)) gives != |
An on-demand query with orderBy and limit fetches one page of that size.
When TanStack DB needs more rows (setWindow, or a window past what is loaded)
it hands the sync layer a cursor on the sort field and the count of rows it
already has. pbtsdb conjoins the cursor to the fetch filter and fetches only the
delta; an offset without a cursor becomes a PocketBase page.
const { data, collection } = useLiveQuery((q) =>
q.from({ b: books }).where(({ b }) => eq(b.author, id)).orderBy(({ b }) => b.page_count).limit(20)
);
// fetches only the rows past what is loaded: one cursor request plus a boundary tie-check
collection.utils.setWindow({ offset: 20, limit: 20 });Realtime stays on the base where: every page of one query shares one
subscription, and a new row that sorts into the window arrives on its own. A
query whose where holds its own boundary (lt(b.page_count, cursor))
subscribes to that slice only, which is the shape for numbered pages: page one
has no boundary and receives every new row. A join's or include's key batch
keeps its own filter, so lazily loaded rows stay covered.
TanStack applies offset in memory after loading, so .offset(n) on the
builder still loads the first n + limit rows. Put a page boundary in the
where when a deep page must not load what comes before it.
The built-in handlers write PocketBase's response into the collection before they return: server-assigned fields like created and updated, and any values rewritten by PocketBase hooks. A built-in delete removes the row the same way. TanStack DB drops a mutation's optimistic state when its handler settles, and rows written while the handler runs publish together with that drop, so the settled row is the server's row with no gap. The realtime echo that follows changes nothing.
By default, pbtsdb does not refetch after a successful insert, update, or delete. Set refetchOnMutation: true to refetch the collection's active queries before the handler settles — for example, when a server-side hook changes other rows you must read right after the mutation:
const collection = c('books', {
refetchOnMutation: true,
});The option only affects the built-in default handlers. A custom onInsert, onUpdate, or onDelete controls write-back itself:
- TanStack DB drops the optimistic state when your handler returns. Until the realtime echo arrives, the row shows its previous server value: an updated row reverts, an inserted row disappears, and a deleted row comes back.
- For an insert or an update,
await collection.accept(serverRows)before you return. This closes the gap. - For a delete,
await collection.evict(ids)before you return. Without it, the deleted row shows again until the delete echo arrives. - In on-demand mode, when realtime goes idle (no live query on the collection), rows held only by an accepted write-back are released. A row written back while nothing is mounted is fetched again on the next mount.
- The handler returns
void. Core no longer reads a{ refetch }result; callcollection.reload()yourself if the handler needs a refetch.
batch sends the mutations of one or more collections to PocketBase in one request and one database transaction. All of them are saved, or none.
import { batch, BatchMutationError, newRecordId } from 'pbtsdb'
try {
await batch(() => {
orders.update(orderId, draft => { draft.status = 'placed' })
lines.insert({ id: newRecordId(), order: orderId, quantity: 2 })
lines.delete(oldLineId)
})
} catch (error) {
if (error instanceof BatchMutationError) {
// error.index, error.collection, error.recordId name the failed
// operation; error.response is its PocketBase error body.
}
}- The callback is synchronous. Do not
awaitin it: the calls only record the mutations and apply them optimistically. The one request is sent when the callback returns. - The Promise resolves when the server accepted the batch and the returned rows are in their collections. On failure every optimistic change is rolled back and the Promise rejects.
- The PocketBase server must have the batch API enabled (Settings → Batch API), with
maxRequestsat or above the largest batch you send. - All collections in one batch must come from the same PocketBase client.
- A collection with a custom
onInsert/onUpdate/onDelete, or with that operation disabled, cannot take that operation in a batch. - File uploads are not supported in a batch. The batch is sent as JSON.
- A batch does not detect a stale editor. It only makes the write atomic.
stagedBatch applies the mutations at once, as optimistic changes, and sends the request only when you call commit(). Use it when the user must see a change immediately but its request must wait, for example until an earlier request that the server must receive first has returned.
import { stagedBatch, newRecordId } from 'pbtsdb'
const staged = stagedBatch(() => {
cards.insert({ id: newRecordId(), title })
})
// The card is in the collection now. No request was sent.
await earlierCreate
await staged.commit()commit()sends the one batch request. It resolves and rejects asbatchdoes, and a failed commit rolls the changes back.rollback()removes the optimistic changes and sends nothing.- Call
commit()once. Until then the rows have$hasPendingWrites. - When the callback throws, the changes are rolled back and
stagedBatchthrows the error. - The rules for
batchabove apply here too.
collection.accept(rows) lands rows the server returned, for example the response of a custom endpoint, as confirmed state. A row older than the stored one is ignored. Use it when the screen must update before the realtime echo arrives. It resolves when the rows are accepted, so a custom mutation handler can await it.
collection.evict(ids) removes rows the server deleted, for example after a custom endpoint deleted them. The rows leave every holder, and a fetch in flight does not put them back. It resolves when the removal is accepted, so a custom delete handler can await it.
collection.reload() refetches every live query's subset. Then it releases the realtime-topic and accepted holders of the rows the results do not confirm. A row that a parent filed through a relation stays. Use it when the server state changed with no realtime event, such as after a user loses access to rows.
All three are also on collection.utils.
Full TypeScript support with compile-time type checking:
const { data } = useLiveQuery((q) =>
q.from({ books: booksCollection })
);
// TypeScript knows:
// - data[0].title is a string
// - data[0].genre is 'Fiction' | 'Non-Fiction' | 'Science Fiction'
// - data[0].author is a string (FK)The main function for creating type-safe collections. Uses a curried API for better type inference.
const c = createCollection<Schema>(
pb: PocketBase,
factoryOptions?: CreateCollectionFactoryOptions
);
const collection = c(collectionName: string, options?: CreateCollectionOptions);Parameters:
pb- PocketBase instancefactoryOptions- Optional configuration applied to every collection this factory builds (see Subscription Options)collectionName- Name of the PocketBase collectionoptions- Optional configuration
Options:
relations?: Record<string, Collection>- Collections that receive expanded records for each relation; declares whatalwaysFetchRelationsandcollection.fetchRelations()may namealwaysFetchRelations?: readonly string[]- Expand paths fetched with every request and filed into theirrelationstargets; never kept on the rowomitOnInsert?: readonly string[]- Fields to make optional during insert (e.g.,['created', 'updated'] as const)syncMode?: 'eager' | 'on-demand'- Data fetching strategy (default:'eager')realtime?: 'collection' | 'query'- Which rows the realtime subscription covers (default:'collection';'query'requiressyncMode: 'on-demand'; see Realtime Scope)liveTopics?: readonly string[]- Custom realtime topics whose messages reload the collection, coalesced overLIVE_TOPIC_WINDOW_MS(100 ms); each topic is 1 to 2500 characters (see Change signals)onInsert?: InsertMutationFn | false- Custom insert handler orfalseto disableonUpdate?: UpdateMutationFn | false- Custom update handler orfalseto disableonDelete?: DeleteMutationFn | false- Custom delete handler orfalseto disablerefetchOnMutation?: boolean- Refetch the collection after a built-in insert/update/delete succeeds (default:false; see Mutations and Refetch)collectionOptions?: object- Additional TanStack DB collection options passed through directly (see Collection Options Passthrough)
Returns: Fully-typed Collection instance with subscription capabilities
Examples:
Basic collection (lazy, subscribes automatically on first query):
const c = createCollection<MySchema>(pb);
const booksCollection = c('books', {});PocketBase expand is used only to bring related records into their own
collections. Rows never carry expand; read related records from the target
collection.
const c = createCollection<MySchema>(pb);
const authors = c('authors', { syncMode: 'on-demand' });
const tags = c('tags', { syncMode: 'on-demand' });
const books = c('books', {
relations: { author: authors, tags }, // where expanded records are filed
alwaysFetchRelations: ['author'], // fetched with every books request
});Every books request expands author; the expanded authors are filed into
authors (an on-demand target has its sync started) and removed from the
book rows. Read them through materialize() in a query or through a join,
inside the useLiveQuery that needs them:
import { eq } from '@tanstack/db';
import { materialize } from 'pbtsdb';
const { data } = useLiveQuery((q) =>
q.from({ b: books }).select(({ b }) => ({
...b,
author: materialize(
q.from({ a: authors }).where(({ a }) => eq(a.id, b.author)).findOne()
),
}))
);
// data[0].author?.name is Authors | undefined and updates when the author changesBecause the authors are already in the store, that include makes no request:
an id-only load (eq(id, x), inArray(id, [...]), or an or of those) is
served from the synced store when every id is present, except when the query
reads through a fetchRelations() view, whose fetch goes to PocketBase so its
paths get filed; anything else is fetched in one batched request. An empty
inArray(id, []) yields no rows and no request.
Do not read a related row with authors.get(book.author) in a component. A
get() is a one-time read: the component does not re-render when the author
changes, and the row can leave the store while the component still shows it,
because a filed row stays only as long as a live query holds the parent row
that filed it. A useLiveQuery with materialize() or a join holds the rows
it reads and re-renders when they change. get() is for code outside React
that needs a value right now, such as a mutation handler or a test.
Fetch a relation for one query only with fetchRelations(); the view shares the
collection's store, realtime subscription, and mutations, and only its fetches
add the expand parameter:
const { data } = useLiveQuery((q) => q.from({ b: books.fetchRelations('tags') }));
// tags referenced by these books are now in the tags collectionPaths can be nested through a target collection's own relations
('book.author'). While a query fetches into a target, that target keeps its
realtime subscription, so get() reads stay fresh.
Back-relations work the same way and go one step further. PocketBase names them
<collection>_via_<field>; fetching one files every child that references the
parent, and pbtsdb records that the child subset for that parent is complete,
so a child query filtered by the foreign key is served from the store:
const comments = c('comments', { syncMode: 'on-demand' });
const cards = c('cards', { syncMode: 'on-demand', relations: { comments_via_card: comments } });
const { data } = useLiveQuery((q) =>
q.from({ card: cards.fetchRelations('comments_via_card') })
.where(({ card }) => eq(card.id, cardId))
.select(({ card }) => ({
...card,
comments: materialize(q.from({ cm: comments }).where(({ cm }) => eq(cm.card, card.id))),
}))
);
// one request; the comments include reads from the storeA subset stays marked while the child collection is subscribed (the parent holds it live) and is forgotten when a child row is pruned from the store, when the child's realtime subscription stops, or when the collection is cleaned up. PocketBase caps a back-relation expand at 1000 records, and a capped expand is never treated as complete.
Pass any TanStack DB BaseCollectionConfig option directly via collectionOptions. This is useful for configuring indexing, garbage collection, and other collection-level settings:
const c = createCollection<MySchema>(pb);
const booksCollection = c('books', {
collectionOptions: {
gcTime: 60000, // 1 minute GC
startSync: true, // Start syncing immediately
}
});pbtsdb defaults autoIndex to 'eager' with defaultIndexType: BTreeIndex, so
orderBy + limit queries page lazily instead of loading the whole subset (and
TanStack DB does not warn about a missing index). Pass autoIndex: 'off' or a
different defaultIndexType in collectionOptions to change that per collection.
The following fields are managed by pbtsdb and excluded from collectionOptions: getKey, syncMode, onInsert, onUpdate, onDelete, schema, utils.
Creates a React Provider and useStore hook from a collections map.
const { Provider, useStore } = createReactProvider(collections: CollectionsMap);Parameters:
collections- Object mapping keys to Collection instances
Returns:
Provider- React Context Provider componentuseStore- Hook to access collections (variadic args, returns typed tuple)
Example:
import { createCollection, createReactProvider } from 'pbtsdb';
const c = createCollection<MySchema>(pb);
const collections = {
authors: c('authors', {}),
books: c('books', {
omitOnInsert: ['created', 'updated'] as const
}),
};
const { Provider, useStore } = createReactProvider(collections);
// Wrap your app
<Provider>
<App />
</Provider>With custom collection key:
const collections = {
myBooks: c('books', {}) // Key 'myBooks', PocketBase collection 'books'
};
const { Provider, useStore } = createReactProvider(collections);
// Access via custom key
const [myBooks] = useStore('myBooks');Access collections from the provider. Uses variadic arguments and returns a typed tuple.
Single collection:
const [collection] = useStore('key')Multiple collections:
const [col1, col2, col3] = useStore('key1', 'key2', 'key3')Examples:
function BooksList() {
const [books] = useStore('books'); // ✅ Typed automatically!
const { data } = useLiveQuery((q) =>
q.from({ books })
);
return <div>{/* ... */}</div>;
}
function BooksWithAuthors() {
const [books, authors] = useStore('books', 'authors'); // ✅ Variadic!
const { data } = useLiveQuery((q) =>
q.from({ book: books })
.join(
{ author: authors },
({ book, author }) => eq(book.author, author.id),
'left'
)
);
return <div>{/* ... */}</div>;
}Collections manage real-time subscriptions to PocketBase automatically. No manual subscription management is needed for normal usage.
// Subscriptions start automatically when useLiveQuery renders
function MyComponent() {
const [books] = useStore('books');
const { data } = useLiveQuery((q) => q.from({ books }));
// ✅ Subscription active while this component is mounted
// ✅ Automatically stops when component unmounts
}Check if a collection has an active subscription.
const isSubbed = collection.isSubscribed(); // booleanWait for subscription to be established (useful in tests).
await collection.waitForSubscription(); // Wait with default 5s timeout
await collection.waitForSubscription(10000); // Wait with custom timeout (ms)By default a collection subscribes to every row (realtime: 'collection').
An on-demand collection can instead subscribe per active query, using the
same filter its fetch sends:
const books = c('books', { syncMode: 'on-demand', realtime: 'query' });
// subscribes with filter genre = "Fantasy"
useLiveQuery((q) => q.from({ b: books }).where(({ b }) => eq(b.genre, 'Fantasy')));One PocketBase subscription is opened per distinct filter string and closed
when the last query using it unmounts. A query with no where subscribes to
the whole collection. While any whole-collection subscription is open, the
filtered ones stay closed.
PocketBase caps a realtime subscription topic at 2500 characters. An id
subset is split into smaller chunks for realtime than for fetches, one
subscription per chunk. A filter whose topic is still too long (a long
non-subset where, or one combined with a factory subscribeOptions filter)
is not sent. The collection logs a warning and subscribes to every row while
that filter is in use.
A 'query' collection held live as a relation target subscribes only to the
rows the parent filed into it: the expanded records' ids for a forward
relation (author), or field = parentId for a back-relation
(books_via_author), so new children still arrive. A 'collection' target
subscribes to every row while held, as before.
Override the mode for one query with withRealtime(), which returns a view
and composes with fetchRelations() in either order:
useLiveQuery((q) => q.from({ b: books.withRealtime('collection') }));
useLiveQuery((q) => q.from({ b: books.fetchRelations('author').withRealtime('query') }));Known limit. PocketBase checks an update against the row's state after
the change. An update that moves a row out of every active filter sends no
event, so the row stays in the store until its query refetches. Deletes and
creates are delivered correctly. Use 'collection' mode where that matters.
Realtime events are applied in the order they arrive. An event that files expanded relations first lands asynchronously, and later events wait for it.
A held 'query' target keeps the ids filed into it until the parent
collection is cleaned up, so a long session with many distinct filed ids
opens many subscriptions, one per id chunk.
Pass subscribeOptions as the third createCollection argument to attach extra
options — headers, filter, expand, fields — to every real-time
subscription the factory creates.
const c = createCollection<Schema>(pb, {
subscribeOptions: () => {
const token = getShareToken();
return token ? { headers: { 'X-Share-Token': token } } : undefined;
},
});It is a getter, not a static object, and that matters. Subscriptions restart on reconnect and whenever the subscriber count rises from zero, so a value read once would go stale exactly when it counts — for example when a visitor authenticates mid-session and should stop presenting an anonymous token.
Returning undefined subscribes with no extra options, identical to omitting
the option entirely.
The common use is authorizing anonymous access. PocketBase snakecases header
names the same way for real-time as for REST, so X-Share-Token is readable in
a collection rule as @request.headers.x_share_token — a single rule covers
both transports:
@request.auth.id != "" || @request.headers.x_share_token = "..."
Setting the matching header on REST requests remains the application's job, via
pb.beforeSend. Requires pocketbase >= 0.22.0.
An expand you add here is yours: pbtsdb strips only the paths it requested
through alwaysFetchRelations and fetchRelations(), so records expanded by
this option stay on the echoed rows, untyped.
getSyncStatus(pb: PocketBase): SyncStatusThe current sync status of pb's collections. The returned object is stable until a value changes.
subscribeSyncStatus(pb: PocketBase, listener: (status: SyncStatus) => void): () => voidCalls listener with each new snapshot. Returns the unsubscribe function.
useSyncStatus(pb: PocketBase): SyncStatusReact hook over the two functions above, built on useSyncExternalStore. Exported from pbtsdb, not from pbtsdb/core.
Generate a PocketBase-compatible record ID (15-character alphanumeric string).
import { newRecordId } from 'pbtsdb';
const id = newRecordId(); // "a1b2c3d4e5f6g7h"
// Use when creating records
const newBook = {
id: newRecordId(),
title: 'New Book',
// ... other fields
};
booksCollection.insert(newBook);Returns: string - 15-character lowercase alphanumeric ID
pbtsdb re-exports commonly used TanStack DB utilities so you don't need to depend on @tanstack/db directly:
import {
// Includes helpers
materialize,
toArray,
createEffect,
// Index types (for collectionOptions.defaultIndexType)
BasicIndex,
BTreeIndex,
ReverseIndex,
// Types
type DeltaEvent,
type DeltaType,
type EffectConfig,
type EffectContext,
type IndexConstructor,
} from 'pbtsdb';// TaskBoard.tsx
import { useLiveQuery } from '@tanstack/react-db';
import { eq, and } from '@tanstack/db';
import { useStore } from './app';
export function TaskBoard({ userId }: { userId: string }) {
const [tasks] = useStore('tasks');
// Filter tasks by assignee and status - updates in real-time
const { data: myTasks } = useLiveQuery((q) =>
q.from({ tasks })
.where(({ tasks }) => and(eq(tasks.assignee, userId), eq(tasks.status, 'in_progress')))
.orderBy(({ tasks }) => tasks.due_date, 'asc')
);
const handleComplete = (taskId: string) => {
tasks.update(taskId, (draft) => { draft.status = 'done'; });
};
return (
<div>
<h2>My Tasks ({myTasks?.length || 0})</h2>
{myTasks?.map(task => (
<div key={task.id}>
{task.title}
<button onClick={() => handleComplete(task.id)}>Complete</button>
</div>
))}
</div>
);
}// ProductCatalog.tsx
import { useLiveQuery } from '@tanstack/react-db';
import { and, eq, lte } from '@tanstack/db';
import { useStore } from './app';
export function ProductCatalog() {
const [products] = useStore('products');
const [category, setCategory] = useState<string | null>(null);
const [maxPrice, setMaxPrice] = useState(1000);
// Dynamic filtering - updates reactively
const { data: filteredProducts } = useLiveQuery((q) => {
let query = q.from({ products })
.where(({ products }) => and(
eq(products.in_stock, true),
lte(products.price, maxPrice)
));
if (category) {
query = query.where(({ products }) => eq(products.category, category));
}
return query.orderBy(({ products }) => products.rating, 'desc');
});
return (
<div>
<select onChange={(e) => setCategory(e.target.value || null)}>
<option value="">All Categories</option>
<option value="electronics">Electronics</option>
</select>
<input type="range" max="1000" value={maxPrice}
onChange={(e) => setMaxPrice(+e.target.value)} />
{filteredProducts?.map(product => (
<ProductCard key={product.id} product={product} />
))}
</div>
);
}// SocialFeed.tsx
import { useLiveQuery } from '@tanstack/react-db';
import { eq } from '@tanstack/db';
import { useStore } from './app';
import { materialize, newRecordId } from 'pbtsdb';
export function SocialFeed({ currentUserId }: { currentUserId: string }) {
const [posts, likes, users] = useStore('posts', 'likes', 'users');
const { data: feedPosts } = useLiveQuery((q) =>
q.from({ posts })
.orderBy(({ posts }) => posts.created, 'desc')
.select(({ posts }) => ({
...posts,
author: materialize(
q.from({ u: users }).where(({ u }) => eq(u.id, posts.author)).findOne()
),
}))
);
const { data: userLikes } = useLiveQuery((q) =>
q.from({ likes }).where(({ likes }) => eq(likes.user, currentUserId))
);
const likedPostIds = new Set(userLikes?.map(l => l.post) || []);
const handleLike = (postId: string) => {
if (likedPostIds.has(postId)) {
const like = userLikes?.find(l => l.post === postId);
if (like) likes.delete(like.id);
} else {
likes.insert({ id: newRecordId(), post: postId, user: currentUserId });
}
};
return (
<div>
{feedPosts?.map(post => (
<div key={post.id}>
<strong>{post.author?.username}</strong>
<p>{post.content}</p>
<button onClick={() => handleLike(post.id)}>
{likedPostIds.has(post.id) ? '❤️' : '🤍'} {post.likes_count}
</button>
</div>
))}
</div>
);
}// CollaborativeTodoList.tsx
import { useLiveQuery } from '@tanstack/react-db';
import { eq } from '@tanstack/db';
import { useStore } from './app';
import { newRecordId } from 'pbtsdb';
export function CollaborativeTodoList({ listId, userId }: { listId: string; userId: string }) {
const [todos] = useStore('todos');
const [newText, setNewText] = useState('');
// Real-time todos - updates when any user adds/edits
const { data: allTodos } = useLiveQuery((q) =>
q.from({ todos })
.where(({ todos }) => eq(todos.list_id, listId))
.orderBy(({ todos }) => todos.created, 'asc')
);
const handleAdd = () => {
if (!newText.trim()) return;
todos.insert({ id: newRecordId(), text: newText, completed: false, list_id: listId, created_by: userId });
setNewText('');
};
return (
<div>
<input value={newText} onChange={(e) => setNewText(e.target.value)}
onKeyPress={(e) => e.key === 'Enter' && handleAdd()} />
<ul>
{allTodos?.map(todo => (
<li key={todo.id}>
<input type="checkbox" checked={todo.completed}
onChange={() => todos.update(todo.id, d => { d.completed = !d.completed; })} />
{todo.text}
<button onClick={() => todos.delete(todo.id)}>×</button>
</li>
))}
</ul>
</div>
);
}Real-time collaboration works automatically - when User A adds/edits a todo, User B sees it instantly.
// CreateBookForm.tsx
import { useStore } from './app';
import { newRecordId } from 'pbtsdb';
export function CreateBookForm() {
const [books] = useStore('books');
const [title, setTitle] = useState('');
const [error, setError] = useState<string | null>(null);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
try {
// Optimistic insert - appears instantly
const tx = books.insert({ id: newRecordId(), title, author: 'author_id' });
await tx.when('settled');
if (tx.state === 'completed') setTitle('');
else setError('Failed to create book');
} catch (err) {
const failure = err as { data?: Record<string, unknown>; message?: string };
setError(failure.data ? Object.values(failure.data).join(', ') : failure.message ?? 'Failed');
}
};
return (
<form onSubmit={handleSubmit}>
{error && <div className="error">{error}</div>}
<input value={title} onChange={(e) => setTitle(e.target.value)} required />
<button type="submit">Add Book</button>
</form>
);
}Optimistic updates show changes instantly; automatic rollback on server errors.
// ProjectDashboard.tsx
import { useLiveQuery } from '@tanstack/react-db';
import { eq } from '@tanstack/db';
import { useStore } from './app';
export function ProjectDashboard({ projectId }: { projectId: string }) {
const [projects, tasks, teamMembers, users] = useStore('projects', 'tasks', 'team_members', 'users');
const { data: projectList } = useLiveQuery((q) =>
q.from({ projects }).where(({ projects }) => eq(projects.id, projectId))
);
const { data: projectTasks } = useLiveQuery((q) =>
q.from({ tasks }).where(({ tasks }) => eq(tasks.project, projectId))
);
// Join team members with users
const { data: team } = useLiveQuery((q) =>
q.from({ member: teamMembers })
.where(({ member }) => eq(member.project, projectId))
.join({ user: users }, ({ member, user }) => eq(member.user, user.id), 'left')
.select(({ member, user }) => ({ id: member.id, role: member.role, name: user?.name }))
);
const completed = projectTasks?.filter(t => t.completed).length || 0;
const total = projectTasks?.length || 0;
return (
<div>
<h1>{projectList?.[0]?.name}</h1>
<p>Progress: {completed}/{total} tasks</p>
<p>Team: {team?.map(m => m.name).join(', ')}</p>
</div>
);
}Demonstrates variadic useStore(), client-side aggregations, and TanStack DB joins.
TanStack DB 0.6.0 introduces includes — nested subqueries within select() that project normalized data into hierarchical shapes. This is useful when you want to compose related data from multiple collections reactively.
Wrap a findOne() subquery in materialize() to get a plain T | undefined
value that updates when the child changes. Without it, the include is a live
sub-collection rather than a value.
import { useLiveQuery, eq } from '@tanstack/react-db';
import { materialize } from 'pbtsdb';
const { data: booksWithAuthors } = useLiveQuery((q) =>
q.from({ b: booksCollection }).select(({ b }) => ({
id: b.id,
title: b.title,
author: materialize(
q.from({ a: authorsCollection })
.where(({ a }) => eq(a.id, b.author))
.select(({ a }) => ({ id: a.id, name: a.name }))
.findOne()
),
}))
);
// booksWithAuthors[0].author?.nameimport { useLiveQuery, eq, toArray } from '@tanstack/react-db';
// Or: import { toArray } from 'pbtsdb';
const { data: booksWithTags } = useLiveQuery((q) =>
q.from({ b: booksCollection }).select(({ b }) => ({
id: b.id,
title: b.title,
tags: toArray(
q.from({ bt: bookTagsCollection })
.where(({ bt }) => eq(bt.book, b.id))
.join({ t: tagsCollection }, ({ bt, t }) => eq(bt.tag, t.id))
.select(({ t }) => ({ id: t.id, name: t.name }))
),
}))
);Use PocketBase's expand to file a relation into its target collection, then use includes to query from it. Because the rows are already in the store, the include makes no request:
const authorsCollection = c('authors', { syncMode: 'on-demand' });
const tagsCollection = c('tags', { syncMode: 'on-demand' });
const bookTagsCollection = c('book_tags', { syncMode: 'on-demand' });
const booksCollection = c('books', {
syncMode: 'on-demand',
relations: { author: authorsCollection }, // where expanded authors are filed
alwaysFetchRelations: ['author'],
});
const { data } = useLiveQuery((q) =>
q.from({ b: booksCollection }).select(({ b }) => ({
id: b.id,
title: b.title,
// Reads from authorsCollection with no request; the rows are already filed
author: materialize(
q.from({ a: authorsCollection })
.where(({ a }) => eq(a.id, b.author))
.select(({ a }) => ({ id: a.id, name: a.name }))
.findOne()
),
tags: toArray(
q.from({ bt: bookTagsCollection })
.where(({ bt }) => eq(bt.book, b.id))
.join({ t: tagsCollection }, ({ bt, t }) => eq(bt.tag, t.id))
.select(({ t }) => ({ id: t.id, name: t.name }))
),
}))
);pbtsdb is fully type-safe. Here's what you need to know:
Use the simple schema format shown in the Quick Start:
type MySchema = {
collection_name: {
type: RecordInterface; // Your record type
relations: {
field_name: RelatedType; // Related record types
};
};
}Pro tip: Use pocketbase-schema-generator to auto-generate types from your PocketBase database.
Always create collections with proper type parameters:
// ✅ Good - full type safety
const c = createCollection<MySchema>(pb);
const books = c('books', {
omitOnInsert: ['created', 'updated'] as const
});
// ✅ Good - with always-fetched relations
const authors = c('authors', {});
const books = c('books', {
relations: { author: authors },
alwaysFetchRelations: ['author'],
});Define all collections once at app initialization:
// ✅ Do this - centralized, type-safe
const c = createCollection<MySchema>(pb);
export const { Provider, useStore } = createReactProvider({
posts: c('posts', { omitOnInsert: ['created', 'updated'] as const }),
users: c('users', {}),
comments: c('comments', { omitOnInsert: ['created', 'updated'] as const })
});When declaring relations, create the target collection first:
// ✅ Good - authors exists before books references it
const c = createCollection<MySchema>(pb);
const authors = c('authors', {});
const books = c('books', {
relations: { author: authors }, // authors is already created
alwaysFetchRelations: ['author'],
});
// ❌ Bad - can't reference what doesn't exist yet
const books = c('books', {
relations: {
author: ??? // Where is authors?
},
alwaysFetchRelations: ['author'],
});Don't manually subscribe - just use useLiveQuery:
// ✅ Do this
const { data } = useLiveQuery((q) => q.from({ posts }));
// ❌ Don't do this
useEffect(() => {
posts.subscribe();
return () => posts.unsubscribe();
}, []);Always check loading and error states:
const { data, isLoading, error } = useLiveQuery((q) => q.from({ posts }));
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
if (!data?.length) return <div>No posts found</div>;
return <PostsList posts={data} />;alwaysFetchRelations costs one request but carries the related record once
per parent row, on every fetch of the parent:
const c = createCollection<MySchema>(pb);
const authors = c('authors', {});
const posts = c('posts', {
relations: { author: authors },
alwaysFetchRelations: ['author'], // expanded on every posts request
});
const { data } = useLiveQuery((q) => q.from({ posts }));A join or a materialize() include costs one batched request per query
(fetching each distinct related row once, however many parent rows reference
it) and, once the rows are filed, subsequent queries make no request at all.
Prefer alwaysFetchRelations when the parent is the only path by which those
rows enter an on-demand collection; otherwise let the query load them.
By default, pbtsdb logs debug messages to the console in development mode. You can integrate with your own logging service (Sentry, LogRocket, etc.) using setLogger:
import { setLogger } from 'pbtsdb';
// Example: Send errors to Sentry
setLogger({
debug: (msg, context) => {
// Custom debug handling (e.g., only log in dev)
if (process.env.NODE_ENV === 'development') {
console.debug('[pbtsdb]', msg, context);
}
},
warn: (msg, context) => {
console.warn('[pbtsdb]', msg, context);
// Optional: Send to monitoring service
myMonitoringService.warn(msg, context);
},
error: (msg, context) => {
console.error('[pbtsdb]', msg, context);
// Send errors to error tracking service
Sentry.captureMessage(msg, {
level: 'error',
extra: context,
});
},
});Disable logging completely:
import { setLogger } from 'pbtsdb';
setLogger({
debug: () => {},
warn: () => {},
error: () => {},
});Reset to default logger:
import { resetLogger } from 'pbtsdb';
resetLogger();MIT
Contributions welcome! Please open an issue or PR.
Prerequisites:
- Node.js 20+
- Git
- The PocketBase binary on your
PATH(the test server uses it)
Clone and Install:
git clone https://github.com/nathanstitt/pbtsdb
cd pbtsdb
npm installTests use a real PocketBase instance with fully automated infrastructure:
npm test # Auto-resets DB → Starts server → Runs tests → Stops serverThe npm test command automatically:
- Resets the test database to a clean state
- Applies migrations and creates test collections
- Starts PocketBase server on port 8210
- Runs all Vitest tests
- Stops the server when complete
No manual server setup required! All test infrastructure is automated.
Advanced (for watch mode or debugging):
# Start test server manually
npm run test:server
# Run tests against running server (in another terminal)
npm run test:run
# Just reset database without starting server
npm run db:resetnpm run checks # Run TypeScript type checking and linting
npm run lint:fix # Auto-fix linting issues
npm run typecheck # TypeScript only- See AGENTS.md for comprehensive development guidelines
- See test/README.md for detailed testing documentation
Built with:
- PocketBase - Backend-as-a-Service
- TanStack DB - Reactive database
- TypeScript - Type safety