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