Skip to content

TrailBase Collection

TrailBase collections provide seamless integration between TanStack DB and TrailBase, enabling real-time data synchronization with TrailBase's self-hosted application backend.

Overview

TrailBase is an easy-to-self-host, single-executable application backend with built-in SQLite, a V8 JS runtime, auth, admin UIs and sync functionality.

The @tanstack/trailbase-db-collection package allows you to create collections that:

  • Automatically sync data from TrailBase Record APIs
  • Support real-time subscriptions when enable_subscriptions is enabled
  • Handle optimistic updates with automatic rollback on errors
  • Provide parse/serialize functions for data transformation

Installation

shell
npm install @tanstack/trailbase-db-collection @tanstack/react-db trailbase

Basic Usage

ts
import { createCollection } from '@tanstack/react-db'
import { trailBaseCollectionOptions } from '@tanstack/trailbase-db-collection'
import { initClient } from 'trailbase'

const trailBaseClient = initClient(`https://your-trailbase-instance.com`)

const todosCollection = createCollection(
  trailBaseCollectionOptions({
    id: 'todos',
    recordApi: trailBaseClient.records('todos'),
    getKey: (item) => item.id,
  })
)

Configuration Options

The trailBaseCollectionOptions function accepts the following options:

Required Options

  • id: Unique identifier for the collection
  • recordApi: TrailBase Record API instance created via trailBaseClient.records()
  • getKey: Function to extract the unique key from an item

Optional Options

  • parse: Object mapping field names to parsing functions that transform data coming from TrailBase
  • serialize: Object mapping field names to serialization functions that transform data going to TrailBase

Data Transformation

TrailBase uses different data formats for storage (e.g., Unix timestamps). Use parse and serialize to handle these transformations:

ts
type SelectTodo = {
  id: string
  text: string
  created_at: number // Unix timestamp from TrailBase
  completed: boolean
}

type Todo = {
  id: string
  text: string
  created_at: Date // JavaScript Date for app usage
  completed: boolean
}

const todosCollection = createCollection(
  trailBaseCollectionOptions<Todo, SelectTodo>({
    id: 'todos',
    recordApi: trailBaseClient.records('todos'),
    getKey: (item) => item.id,
    // Transform TrailBase data to application format
    parse: {
      created_at: (ts) => new Date(ts * 1000),
    },
    // Transform application data to TrailBase format
    serialize: {
      created_at: (date) => Math.floor(date.valueOf() / 1000),
    },
  })
)

Real-time Subscriptions

TrailBase supports real-time subscriptions when enabled on the server. The collection automatically subscribes to changes and updates in real-time:

ts
const todosCollection = createCollection(
  trailBaseCollectionOptions({
    id: 'todos',
    recordApi: trailBaseClient.records('todos'),
    getKey: (item) => item.id,
    // Real-time updates work automatically when
    // enable_subscriptions is set in TrailBase config
  })
)

// Changes from other clients will automatically update
// the collection in real-time

Mutation Handlers

TrailBase collections provide built-in handlers for insert, update, and delete. Each handler keeps the optimistic state until the backend request succeeds and a fresh change event for every affected key reaches that sync run. An older event for the same key cannot confirm a later mutation, including a mutation started by a public change callback while that older event publishes.

If the change stream closes or fails, a handler whose backend response has arrived rejects promptly when confirmation is missing. A new handler also rejects when its sync run has already stopped. Graceful closure first drains buffered events. If the stream stays healthy but supplies no confirmation, the handler rejects after its 120-second confirmation timeout.

A fresh event already accepted before stream closure or cleanup remains valid when the backend response arrives later. Cleanup and restart cannot let an old request use a replacement run's event. A failed handler removes its optimistic state; rejection does not promise cancellation or rollback of an in-flight backend request.

Complete Example

ts
import { createCollection, useLiveQuery } from '@tanstack/react-db'
import { not } from '@tanstack/db'
import { trailBaseCollectionOptions } from '@tanstack/trailbase-db-collection'
import { initClient } from 'trailbase'

const trailBaseClient = initClient(`https://your-trailbase-instance.com`)

type SelectTodo = {
  id: string
  text: string
  completed: boolean
  created_at: number
}

type Todo = Omit<SelectTodo, 'created_at'> & { created_at: Date }

// Create collection
export const todosCollection = createCollection(
  trailBaseCollectionOptions<Todo, SelectTodo>({
    id: 'todos',
    recordApi: trailBaseClient.records('todos'),
    getKey: (item) => item.id,
    parse: {
      created_at: (ts) => new Date(ts * 1000),
    },
    serialize: {
      created_at: (date) => Math.floor(date.valueOf() / 1000),
    },
  })
)

// Use in component
function TodoList() {
  const { data: todos } = useLiveQuery({
    query: (q) =>
      q
        .from({ todo: todosCollection })
        .where(({ todo }) => not(todo.completed))
        .orderBy(({ todo }) => todo.created_at, 'desc'),
  })

  const addTodo = (text: string) => {
    todosCollection.insert({
      id: crypto.randomUUID(),
      text,
      completed: false,
      created_at: new Date(),
    })
  }

  return (
    <div>
      {todos.map((todo) => (
        <div key={todo.id}>{todo.text}</div>
      ))}
    </div>
  )
}

Learn More