Open History to see the last commit
1---
2title: TrailBase Collection
3---
4
5TrailBase collections provide seamless integration between TanStack DB and [TrailBase](https://trailbase.io), enabling real-time data synchronization with TrailBase's self-hosted application backend.
6
7## Overview
8
9[TrailBase](https://trailbase.io) is an easy-to-self-host, single-executable application backend with built-in SQLite, a V8 JS runtime, auth, admin UIs and sync functionality.
10
11The `@tanstack/trailbase-db-collection` package allows you to create collections that:
12- Automatically sync data from TrailBase Record APIs
13- Support real-time subscriptions when `enable_subscriptions` is enabled
14- Handle optimistic updates with automatic rollback on errors
15- Provide parse/serialize functions for data transformation
16
17## Installation
18
19```bash
20npm install @tanstack/trailbase-db-collection @tanstack/react-db trailbase
21```
22
23## Basic Usage
24
25```typescript
26import { createCollection } from '@tanstack/react-db'
27import { trailBaseCollectionOptions } from '@tanstack/trailbase-db-collection'
28import { initClient } from 'trailbase'
29
30const trailBaseClient = initClient(`https://your-trailbase-instance.com`)
31
32const todosCollection = createCollection(
33 trailBaseCollectionOptions({
34 id: 'todos',
35 recordApi: trailBaseClient.records('todos'),
36 getKey: (item) => item.id,
37 })
38)
39```
40
41## Configuration Options
42
43The `trailBaseCollectionOptions` function accepts the following options:
44
45### Required Options
46
47- `id`: Unique identifier for the collection
48- `recordApi`: TrailBase Record API instance created via `trailBaseClient.records()`
49- `getKey`: Function to extract the unique key from an item
50
51### Optional Options
52
53- `schema`: [Standard Schema](https://standardschema.dev) compatible schema (e.g., Zod, Effect) for client-side validation
54- `parse`: Object mapping field names to parsing functions that transform data coming from TrailBase
55- `serialize`: Object mapping field names to serialization functions that transform data going to TrailBase
56- `onInsert`: Handler function called when items are inserted
57- `onUpdate`: Handler function called when items are updated
58- `onDelete`: Handler function called when items are deleted
59
60## Data Transformation
61
62TrailBase uses different data formats for storage (e.g., Unix timestamps). Use `parse` and `serialize` to handle these transformations:
63
64```typescript
65type SelectTodo = {
66 id: string
67 text: string
68 created_at: number // Unix timestamp from TrailBase
69 completed: boolean
70}
71
72type Todo = {
73 id: string
74 text: string
75 created_at: Date // JavaScript Date for app usage
76 completed: boolean
77}
78
79const todosCollection = createCollection<SelectTodo, Todo>(
80 trailBaseCollectionOptions({
81 id: 'todos',
82 recordApi: trailBaseClient.records('todos'),
83 getKey: (item) => item.id,
84 schema: todoSchema,
85 // Transform TrailBase data to application format
86 parse: {
87 created_at: (ts) => new Date(ts * 1000),
88 },
89 // Transform application data to TrailBase format
90 serialize: {
91 created_at: (date) => Math.floor(date.valueOf() / 1000),
92 },
93 })
94)
95```
96
97## Real-time Subscriptions
98
99TrailBase supports real-time subscriptions when enabled on the server. The collection automatically subscribes to changes and updates in real-time:
100
101```typescript
102const todosCollection = createCollection(
103 trailBaseCollectionOptions({
104 id: 'todos',
105 recordApi: trailBaseClient.records('todos'),
106 getKey: (item) => item.id,
107 // Real-time updates work automatically when
108 // enable_subscriptions is set in TrailBase config
109 })
110)
111
112// Changes from other clients will automatically update
113// the collection in real-time
114```
115
116## Mutation Handlers
117
118Handle inserts, updates, and deletes by providing mutation handlers:
119
120```typescript
121const todosCollection = createCollection(
122 trailBaseCollectionOptions({
123 id: 'todos',
124 recordApi: trailBaseClient.records('todos'),
125 getKey: (item) => item.id,
126 onInsert: async ({ transaction }) => {
127 const newTodo = transaction.mutations[0].modified
128 // TrailBase handles the persistence automatically
129 // Add custom logic here if needed
130 },
131 onUpdate: async ({ transaction }) => {
132 const { original, modified } = transaction.mutations[0]
133 // TrailBase handles the persistence automatically
134 // Add custom logic here if needed
135 },
136 onDelete: async ({ transaction }) => {
137 const deletedTodo = transaction.mutations[0].original
138 // TrailBase handles the persistence automatically
139 // Add custom logic here if needed
140 },
141 })
142)
143```
144
145## Complete Example
146
147```typescript
148import { createCollection } from '@tanstack/react-db'
149import { not } from '@tanstack/db'
150import { trailBaseCollectionOptions } from '@tanstack/trailbase-db-collection'
151import { initClient } from 'trailbase'
152import { z } from 'zod'
153
154const trailBaseClient = initClient(`https://your-trailbase-instance.com`)
155
156// Define schema
157const todoSchema = z.object({
158 id: z.string(),
159 text: z.string(),
160 completed: z.boolean(),
161 created_at: z.date(),
162})
163
164type SelectTodo = {
165 id: string
166 text: string
167 completed: boolean
168 created_at: number
169}
170
171type Todo = z.infer<typeof todoSchema>
172
173// Create collection
174export const todosCollection = createCollection<SelectTodo, Todo>(
175 trailBaseCollectionOptions({
176 id: 'todos',
177 recordApi: trailBaseClient.records('todos'),
178 getKey: (item) => item.id,
179 schema: todoSchema,
180 parse: {
181 created_at: (ts) => new Date(ts * 1000),
182 },
183 serialize: {
184 created_at: (date) => Math.floor(date.valueOf() / 1000),
185 },
186 onInsert: async ({ transaction }) => {
187 const newTodo = transaction.mutations[0].modified
188 console.log('Todo created:', newTodo)
189 },
190 })
191)
192
193// Use in component
194function TodoList() {
195 const { data: todos } = useLiveQuery({
196 query: (q) =>
197 q
198 .from({ todo: todosCollection })
199 .where(({ todo }) => not(todo.completed))
200 .orderBy(({ todo }) => todo.created_at, 'desc'),
201 })
202
203 const addTodo = (text: string) => {
204 todosCollection.insert({
205 id: crypto.randomUUID(),
206 text,
207 completed: false,
208 created_at: new Date(),
209 })
210 }
211
212 return (
213 <div>
214 {todos.map((todo) => (
215 <div key={todo.id}>{todo.text}</div>
216 ))}
217 </div>
218 )
219}
220```
221
222## Learn More
223
224- [TrailBase Documentation](https://trailbase.io/documentation/)
225- [TrailBase Record APIs](https://trailbase.io/documentation/apis_record/)
226- [Optimistic Mutations](../guides/mutations.md)
227- [Live Queries](../guides/live-queries.md)