Skip to main content
Documentation

Records reference

Providers, hooks, and the data layer for reading and writing records.

On this page

The records API is the primary surface for working with collections. Every hook and provider on this page is imported from deepspace.

import {
  RecordProvider, RecordScope, ScopeRegistryProvider,
  useQuery, useMutations, useUsers, useUserLookup, useRecordContext,
  RecordRoomNotReadyError, type WriteError,
} from 'deepspace'
ts

For schemas and column types, see the worker schemas reference. For RBAC rules, see permissions.

Providers#

<RecordProvider>#

Initializes the WebSocket and in-memory record store. Required ancestor of every records hook.

PropTypeDescription
roomIdstring (optional)Scope ID for the default room (usually app:<APP_ID> - the scaffold's SCOPE_ID, keyed to the immutable app id, not the name). Omit for multi-scope mode and use <RecordScope> to mount scopes instead.
schemasCollectionSchema[] (optional)All collections this provider tree may query.
wsUrlstring (optional)Override the WebSocket URL. Defaults to current origin.
fetchUser() => Promise<UserProfile | null> (optional)Custom user-profile fetcher. Defaults to using the Better Auth session.
allowAnonymousboolean (optional)Connect without a JWT (default false). Required for public pages. See authentication.
getAuthToken() => Promise<string | null> (optional)Custom token fetcher. Defaults to the SDK's.
onWriteError(error: WriteError) => void (optional)Called when the server rejects an optimistic write. See write errors below.
<RecordProvider allowAnonymous>
  <App />
</RecordProvider>
tsx

Write errors (onWriteError)#

Optimistic mutations (create / put / remove) resolve before the server answers, so a denied or invalid write can only surface through onWriteError - it is the only surface where server-rejected optimistic writes appear. If you don't handle it, the app looks like the write worked while the server silently rejected it (the SDK's default handler logs a deduplicated console.error telling you to wire real UI).

interface WriteError {
  /** RBAC denial or data validation/other rejection. */
  kind: 'permission' | 'validation'
  /** Short human-readable summary, safe to show end users. */
  title: string
  /** Longer human-readable explanation; may be empty. */
  detail: string
}
ts

The scaffold wires it to toasts - permission denials as warnings, everything else as errors. Keep this wiring when customizing the layout, and retrofit it into apps scaffolded before the prop existed:

const { error, warning } = useToast()   // scaffold's local toast hook

<RecordProvider
  allowAnonymous
  onWriteError={(e) =>
    e.kind === 'permission' ? warning(e.title, e.detail) : error(e.title, e.detail)
  }
>
  <App />
</RecordProvider>
tsx

When the next step depends on the write being accepted, prefer the confirmed mutation variants - they reject instead of routing through onWriteError.

<RecordScope>#

Mounts a specific scope (Durable Object instance). Nest for additional scopes.

PropTypeDescription
roomIdstringScope ID (e.g. app:app_01HZXYABCDEFGHJKMNPQRSTVWX, conv:abc123).
schemasCollectionSchema[]Collections in this scope.
sharedScopesArray<{ roomId, schemas }>Cross-app scopes to mount alongside the primary. See cross-app shared scopes.
wsUrlstring (optional)Override WebSocket URL.
wsPathPrefixstring (optional)Override path prefix (default /ws).
isolatedbooleanIf true, don't register this scope's collections in the shared scope registry - prevents name collisions with other mounted scopes.

<ScopeRegistryProvider>#

Required once near the root if your app uses shared scopes via sharedScopes. Coordinates routing between cross-app and per-app DOs.

useQuery<T>(collection, options?)#

Subscribes to a collection. Returns a reactive array of envelopes.

function useQuery<T>(
  collection: string,
  options?: {
    where?: Partial<T>
    orderBy?: string
    orderDir?: 'asc' | 'desc'
    limit?: number
  },
): {
  records: Envelope<T>[]
  status: 'loading' | 'ready' | 'error'
  error?: string
}
ts

Subscribe to every record in a collection. The hook re-renders whenever any user mutates a record visible to the caller's permissions.

type Note = { title: string; body: string }

function Notes() {
  const { records, status } = useQuery<Note>('notes')

  if (status === 'loading') return <Skeleton />
  return records.map((r) => <li key={r.recordId}>{r.data.title}</li>)
}
tsx

Envelope shape:

type Envelope<T> = {
  recordId: string
  data: T
  createdBy: string
  createdAt: string
  updatedAt: string
}
ts

useMutations<T>(collection)#

Returns mutation functions for the given collection. Each mutation applies optimistically - the local store updates before the server confirms.

function useMutations<T>(collection: string): {
  /** True once the collection's RecordRoom can accept writes. */
  ready:           boolean
  create:          (data: T)                       => Promise<string>
  put:             (id: string, patch: Partial<T>) => Promise<void>
  remove:          (id: string)                    => Promise<void>
  createConfirmed: (data: T)                       => Promise<string>
  putConfirmed:    (id: string, patch: Partial<T>) => Promise<void>
  removeConfirmed: (id: string)                    => Promise<void>
}
ts

The ready gate#

Every method throws RecordRoomNotReadyError (a Error subclass with code: 'not_ready') when called before the collection's RecordRoom connection is ready - during initial connect and after a disconnect. Disable write controls until ready so users can't trigger the throw:

const { ready, create } = useMutations<Note>('notes')

<button disabled={!ready} onClick={() => create({ title: 'Untitled', body: '', pinned: false })}>
  New note
</button>
tsx

If you do call a mutation from a code path that can run early, catch the error and check err.code === 'not_ready' to distinguish it from a server rejection.

create takes the full row shape and returns the new recordId. The ID is generated on the client (timestamp + random suffix) before the write is sent, so the promise resolves with the ID immediately while the server processes the mutation in the background.

const { create } = useMutations<Note>('notes')

const id = await create({
  title: 'Untitled',
  body: '',
  pinned: false,
})
tsx

If you need to confirm the row was actually persisted (e.g., before navigating away), use createConfirmed instead - it awaits server acknowledgment:

const id = await createConfirmed({ title: 'New', body: '', pinned: false })
navigate(`/notes/${id}`)
tsx
MethodSemanticsReturns
createOptimisticPromise<string> (client-generated recordId)
putOptimistic, mergePromise<void>
removeOptimisticPromise<void>
createConfirmedWaits for DO ackPromise<string>
putConfirmedWaits for DO ackPromise<void>
removeConfirmedWaits for DO ackPromise<void>

useUsers()#

Returns the room's user directory with role-management helpers.

type RoomUser = {
  id: string
  /** Present only for admin callers. */
  email?: string
  name: string
  imageUrl?: string
  role: string
  /** Present only for admin callers. */
  createdAt?: string
  /** Present only for admin callers. */
  lastSeenAt?: string
}

function useUsers(): {
  users: RoomUser[]
  usersLoaded: boolean
  setRole: (userId: string, role: string) => void
  refresh: () => void
}
ts

setRole accepts a free-form role string (e.g. 'admin', 'intern', or any value your schema understands) and dispatches the change without waiting for an ack. The Durable Object enforces who is allowed to call it. See permissions for how roles map onto collection RBAC rules.

The directory privacy contract#

The directory is filtered server-side, in two steps:

  1. Row policy. Anonymous sockets receive no directory at all. For authenticated callers, rows first pass the app's users collection read policy for the caller's role - the fresh scaffold ships member.read: 'own', so a regular member's directory contains only their own row unless the app explicitly broadens the policy.
  2. Field projection. Rows that pass are then projected to public identity for non-admin callers: { id, name, imageUrl?, role }. Admins receive the full fields (email, createdAt, lastSeenAt, plus any custom columns) - which is also why useUserLookup().getEmail only resolves emails for admin callers.

useUserLookup()#

O(1) wrapper around useUsers() for resolving userIds to display fields.

type UserInfo = {
  id: string
  /** Available to admins; ordinary members receive public identity only. */
  email?: string
  name: string
  imageUrl?: string
  role: string
}

function useUserLookup(): {
  users: RoomUser[]
  usersLoaded: boolean
  userMap: Map<string, UserInfo>
  getUser:  (userId: string) => UserInfo | null
  getEmail: (userId: string) => string | null
  getName:  (userId: string) => string | null
}
ts
const { getName } = useUserLookup()
<p>By {getName(message.authorId) ?? 'unknown'}</p>
tsx

There is no getRole or getImageUrl - read those off getUser(id)?.role or getUser(id)?.imageUrl.

getEmail resolves an email only when the caller is an admin - non-admin callers receive the public-identity projection, which carries no email, so getEmail returns null for them. Don't build member-facing UI that depends on it.

useRecordContext()#

Low-level access to the record-store context (WebSocket send/receive primitives, ready state, user profile, etc.). Useful for building custom hooks or imperative reads outside React's render cycle. Most apps never need this.

See also#