tanstackstart-db
Schema-first application data helpers for TanStack DB.
@doeixd/tanstackstart-db turns a small entity schema into a typed application
data layer: collections, query helpers, optimistic CRUD actions, reusable views,
live React hooks, route loaders, hydration snapshots, and testing utilities.
It keeps TanStack DB as the data engine and adds the application-level contracts
needed to use that engine consistently across a TanStack Start app.
Status: Pre-release (0.x). The API may change between minor versions.
See GOAL.md for design direction and
docs/ for deep-dive topics.
Why use it?
TanStack DB provides reactive client-side collections, live queries, and
optimistic mutations. Building an application still requires decisions about
schema ownership, query naming, view projection, action conventions, SSR
hydration, route loading, and testing.
This package makes those decisions once:
- Define entities once. Standard Schema-compatible validators drive runtime
validation and TypeScript inference.
- Get a useful API immediately. Every entity receives typed
q.* query
helpers and a.* CRUD actions.
- Keep optimistic writes observable. Actions return awaitable submissions
with transaction, persistence, result, and status state.
- Shape data at component boundaries. Reusable views select fields and
materialize declared relationships.
- Use the right collection engine per entity. Start local, connect TanStack
Query, persist to
localStorage, or wrap an existing sync engine such as
Electric or PowerSync.
- Carry the same model through React and routes. Live-query hooks, Suspense
resources, Router loader builders, confirmed-state hydration, and testing
helpers all use the same schema-backed DB.
- Describe a page in one place. DB file routes collect page views, reusable
fragments, action aliases, pending state, boundaries, and hydration into one
typed TanStack Router contract.
Positioning
This package is TanStack DB with application-level contracts — not a
replacement for TanStack DB and not a Fate-clone. The relationship is:
- Use raw TanStack DB when you want the un-augmented engine: live
queries, differential dataflow, sync adapters, optimistic mutations,
schema validation. Nothing in this package hides those primitives.
- Use this package when you want app-level contracts on top of the
same engine: typed schema → query/action generation, view masking,
route loaders, action aliases, hydration snapshots, React component
builders.
The two are the same data engine. This package layers contracts
(schema-to-CRUD generation, view masking, action aliases, route loader
contracts) on top of TanStack DB. It does not introduce a second
normalized cache, transport, or query planner.
Every abstraction has an escape hatch back to the engine:
db.q.raw({ ... }) builds a DbQuerySpec from a hand-written
native TanStack DB query-builder closure.
db.collections and useCollections() return the typed adapter
map; you can read or write rows directly.
useDb() returns the StartDb so React components can reach the
generated queries and actions.
nativeCollection(key, engine) wraps a pre-existing TanStack DB
Collection (Electric, PowerSync, Query, custom sync engines).
route.useDb() and route.useCollections() expose the route's
bound DB to the component for direct access.
Three levels
The package is structured so you can adopt it one slice at a time. Most
apps will land in Level 2; the deeper patterns are there when you
reach for them.
Level 1: schema to CRUD
Define entities, get a DB, read and write immediately. No views, no
routes, no React. Useful for scripts, server-side rendering helpers,
or the first hour of an app.
import { defineDbSchema, entity, passthrough } from "@doeixd/tanstackstart-db/schema";
import { createStartDbFromSchema } from "@doeixd/tanstackstart-db";
const schema = defineDbSchema({
entities: {
post: entity(passthrough<{ id: string; title: string; likes: number }>(), { key: "id" }),
},
});
const db = createStartDbFromSchema(schema);
await db.a.post.create({ id: "post_1", title: "Hello", likes: 0 });
const post = await db.q.post.byId("post_1").execute();
await db.a.post.patch({ id: "post_1", changes: { likes: 1 } });
Level 2: views, components, and routes
Add view masking, typed component builders, and Router route
contracts. This is the level most apps spend their time in.
const postCard = db.view("post", { id: true, title: true, likes: true });
const PostCard = db.component(postCard)(({ post }) => (
<article>
<h2>{post.title}</h2>
<p>{post.likes} likes</p>
</article>
));
export const Route = createDbFileRoute("/posts/$postId")
.views(({ params, q }) => ({
post: q.post.byId(params.postId).as(postCard).required(),
}))
.actions(({ a, data }) => ({
like: a.post.patch.with({ id: data.post.id }),
}))
.build();
Level 3: custom actions, relationships, adapters, devtools
Add custom action definitions, schema relationships with native
joins, collection adapters for sync engines, and a devtools surface
(planned for v0.2). This is where extendActions, api.one /
api.many, localStorageCollection, syncCollection, and the
createOptimisticAction integration live.
const appDb = db.extendActions(({ action, c }) => ({
post: {
like: action<{ id: string }, void>({
optimistic: ({ input, cache }) => {
cache.post(input.id).patch({ likes: (n: unknown) => Number(n) + 1 });
},
run: ({ input, setTransaction }) => {
const result = c.post.update(input.id, (post) => ({
...post,
likes: post.likes + 1,
}));
setTransaction(result.transaction);
},
}),
},
}));
At a glance
| Concern |
What the package provides |
| Schema |
Standard Schema entities, indexes, and one / many relationships |
| Queries |
Generated byId, all, indexed, and relationship helpers; native TanStack DB execution; live subscriptions; raw query escape hatch |
| Views |
Typed field masks and nested relationship projections, compiled into native selects and joins where possible |
| Actions |
Generated optimistic CRUD, reusable custom actions, pending state, submission history, and rollback behavior |
| Collections |
Local TanStack DB collections, Query Collection, localStorage, and generic sync-engine adapters |
| React |
Provider-backed hooks, live queries, Suspense queries, DB-bound component helpers, and status hooks |
| Routes |
Fluent TanStack Router file-route builders with deferred queries, preload-only queries, route hydration, and cleanup |
| Testing |
Memory-backed DBs, collection seeding, fixtures, action mocks, render helpers, and async utilities |
Quick start
Install the package and TanStack DB:
pnpm add @doeixd/tanstackstart-db @tanstack/db
Define the entities your application works with. Any Standard Schema-compatible
library can be used in place of passthrough.
import { defineDbSchema, entity, passthrough } from "@doeixd/tanstackstart-db/schema";
export const schema = defineDbSchema({
entities: {
user: entity(passthrough<{ id: string; name: string }>(), {
key: "id",
}),
post: entity(passthrough<{ id: string; authorId: string; title: string; likes: number }>(), {
key: "id",
indexes: ["authorId"],
relationships: (api) => ({
author: api.one("user", { local: "authorId", foreign: "id" }),
}),
}),
},
});
Create the DB. With no collection configuration, entities use local TanStack DB
collections and already support generated actions and queries.
import { createStartDbFromSchema } from "@doeixd/tanstackstart-db";
import { schema } from "./schema";
export const db = createStartDbFromSchema(schema);
await db.a.user.create({ id: "user_1", name: "Ada" });
await db.a.post.create({
id: "post_1",
authorId: "user_1",
title: "Hello",
likes: 0,
});
const post = await db.q.post.byId("post_1").execute();
const byAuthor = await db.q.post.byAuthor("user_1").execute();
Schema indexes generate concise helpers such as authorId -> byAuthor(...).
Relationships generate named query helpers and can also be selected in views.
Views
Views describe the shape a component or route needs without leaking the full
entity. Nested views are checked against declared relationships.
const userCard = db.view("user", { id: true, name: true });
const postCard = db.view("post", {
id: true,
title: true,
likes: true,
author: userCard,
});
const post = await db.q.post.byId("post_1").as(postCard).execute();
// { id, title, likes, author: { id, name } }
Simple projections are compiled into native TanStack DB select operations.
Eligible one relationships are folded into native joins. Other nested
relationships are materialized from their related collections after execution
and remain reactive for live queries. See
docs/views.md for the full view contract and
docs/relationships.md for the schema declarations
that views depend on.
Actions and optimistic state
Generated actions expose create, patch, update, and delete for each
entity. An action call immediately returns a DbActionSubmission: a thenable
object that can be awaited like a promise while also exposing mutation state.
const submission = db.a.post.patch({
id: "post_1",
changes: { likes: 1 },
});
submission.status; // "pending" | "persisting" | "completed" | "failed"
submission.transaction; // native TanStack DB transaction when available
await submission.persisted;
const updated = await submission;
Use the DB tracker to drive granular UI feedback:
db.pending.any();
db.pending.action("post.patch", { id: "post_1", changes: { likes: 1 } });
db.pending.field({ id: "post_1" }, "likes");
db.pending.query("post");
db.submissions.latest("post.patch");
Application-specific actions can extend the generated namespace. The action
pipeline supports optimistic work, authorization, affected-query metadata,
invalidation, success/error hooks, and rollback behavior. See
docs/action-aliases.md for .with(...),
.extend(...), and route-level aliasing;
docs/authorization.md for the authorize gate
and DbAuthError; and
docs/optimistic-conflict-offline.md
for the optimistic / conflict / offline failure modes and recovery.
const appDb = db.extendActions(({ action, c, q }) => ({
post: {
like: action<{ id: string }, void>({
affects: ({ input }) => [q.post.byId(input.id).field("likes")],
run: ({ input, setTransaction }) => {
const result = c.post.update(input.id, (post) => ({
...post,
likes: post.likes + 1,
}));
setTransaction(result.transaction);
},
}),
},
}));
await appDb.a.post.like({ id: "post_1" });
Collection adapters
Each entity can choose its own TanStack DB collection engine. The schema key and
validator are forwarded to adapters so generated actions and direct native
mutations share the same rules.
TanStack Query
Use the optional Query Collection entrypoint for server-backed entities:
import { QueryClient } from "@tanstack/query-core";
import { queryCollection } from "@doeixd/tanstackstart-db/query-collection";
const queryClient = new QueryClient();
const db = createStartDbFromSchema(schema, {
collections: () => ({
post: queryCollection("post", {
queryClient,
queryKey: ["posts"],
queryFn: () => api.posts.list(),
mutations: {
insert: (rows) => api.posts.create(rows),
update: (updates) => api.posts.update(updates),
delete: (ids) => api.posts.delete(ids),
},
}),
}),
});
Local storage
Use localStorageCollection for browser-persisted entities. Its storage API is
configurable, which also makes it straightforward to test.
import { localStorageCollection } from "@doeixd/tanstackstart-db/local-storage-collection";
const db = createStartDbFromSchema(schema, {
collections: () => ({
post: localStorageCollection("post", {
storageKey: "app.posts",
}),
}),
});
Existing sync engines
Use syncCollection to wrap an existing TanStack DB Collection, including
collections created for Electric, PowerSync, or a custom synchronization layer.
import { syncCollection } from "@doeixd/tanstackstart-db/sync-collection";
const db = createStartDbFromSchema(schema, {
collections: () => ({
post: syncCollection("post", {
engine: electricEngine,
key: "id",
}),
}),
});
For lower-level integration, nativeCollection(key, engine, options?) wraps any
pre-created official TanStack DB collection directly.
Hydration
Snapshots contain confirmed collection state. Pending optimistic overlays are
excluded by default so SSR payloads and client rehydration do not accidentally
promote unconfirmed writes.
import { dehydrateDb, hydrateDb } from "@doeixd/tanstackstart-db";
const snapshot = dehydrateDb(db);
hydrateDb(db, snapshot);
Snapshot strategies
dehydrateDb accepts a snapshot