Build an Angular app on Sp00ky: provideSp00ky, live queries as signals, sign-in, writes, sync status, files, collaborative fields and peer to peer channels.
@spooky-sync/client-angular connects Angular apps to Sp00ky, built on signals. A live query is an
object of read-only signals (posts.data(), posts.isLoading()) that templates, computed() and
effect() track like any other signal. Every write lands in the local database first, and the
engine syncs it with the server and every other tab and device in the background. Reloads paint
from the local cache, and the app keeps working offline.
This guide builds a complete app: setup, queries, sign-in, writes, sync status, files,
collaborative fields and peer to peer channels. It needs Angular 21 or newer, and works with
zoneless and zone.js apps alike.
Browser only
The client runs SurrealDB and SQLite as WebAssembly with IndexedDB / OPFS storage and web
workers, so it only runs in the browser. During a server render provideSp00ky never starts it;
render the components that use it on the client, as shown in
Server-side rendering.
@surrealdb/wasm is installed directly because the app bundles its worker (next step). With
pnpm, hoist the packages whose .wasm files the build copies, so their paths exist:
The client starts web workers and loads .wasm files relative to its own modules. The Angular
CLI’s builder does not bundle a worker started inside a dependency, and does not copy a .wasm
file a dependency references. So the app bundles the worker itself and copies the .wasm files
next to its chunks.
One worker entry for the local database engine, one line long:
src/app/sp00ky-surreal.worker.ts
// The local SurrealDB engine's worker, bundled by the Angular CLI.import '@surrealdb/wasm/worker';
A TypeScript config for workers, as ng generate web-worker creates (exclude
src/**/*.worker.ts from tsconfig.app.json too):
Then, in angular.json, point the build at it, copy the .wasm files, and keep the client’s
packages out of the dev server’s dependency pre-bundling (pre-bundled, they look for their
.wasm files in the wrong folder):
pino is the client’s logger; allowedCommonJsDependencies only silences the CommonJS
warning about it. With localEngine: 'sqlite', add a second worker entry containing
import '@spooky-sync/core/sqlite-worker'; and pass it as database.workers.sqlite; with
localEngine: 'rows', the entry is import '@spooky-sync/core/rows-worker';, passed as
database.workers.rows.
Generate types
spky generate
spky generate writes the schema types for every client, see
Generated types.
Configure the client
src/app/db.ts
import type { SyncedDbConfig } from '@spooky-sync/client-angular';import { schema, SURQL_SCHEMA } from './schema.gen';export const dbConfig: SyncedDbConfig<typeof schema> = { logLevel: 'info', schema, schemaSurql: SURQL_SCHEMA, database: { namespace: 'main', database: 'main', // spky dev exposes SurrealDB on 8666 by default. endpoint: 'ws://localhost:8666/rpc', store: 'indexeddb', workers: { surreal: () => new Worker(new URL('./sp00ky-surreal.worker', import.meta.url), { type: 'module' }), }, },};
database.workers.surreal hands the client the worker the Angular CLI just bundled. Every other
key is documented in Client config.
Provide the client
src/app/app.config.ts
import { type ApplicationConfig, provideBrowserGlobalErrorListeners, provideZonelessChangeDetection,} from '@angular/core';import { provideRouter } from '@angular/router';import { provideSp00ky } from '@spooky-sync/client-angular';import { routes } from './app.routes';import { dbConfig } from './db';export const appConfig: ApplicationConfig = { providers: [ provideBrowserGlobalErrorListeners(), provideZonelessChangeDetection(), provideRouter(routes), provideSp00ky(dbConfig, { // Optional: warm the local cache before the first render. preload: (db) => db.preload(db.query('config').build()), }), ],};
provideSp00ky(config, { preload }) starts the client in an app initializer and runs preload
(best-effort) before the first render. Until then the root element of index.html keeps its
content, so put your splash there:
If the client cannot start, bootstrap fails: handle it on bootstrapApplication(...).catch(...).
config may also be a function, run in the injection context, to build the config from other
providers. The client is closed when the application is destroyed.
Option
Meaning
preload
Awaited before the first render, to warm the local cache. A failure is logged and the app starts anyway.
eager
Render the app at once, before the client is ready. See below.
Rendering before the client is ready
By default the app does not render until the client has opened its local database. With eager
it bootstraps and renders at once:
src/app/app.config.ts
provideSp00ky(dbConfig, { eager: true }),
With localEngine: 'rows', injectQuery then
returns, on its very first read, the rows the query showed the last time the app was open, with
isLoading() false. The query starts as soon as the client is ready and replaces them when its
answer differs. Until then isAuthoritative() is false, as for any query still loading.
What changes for your app is that it starts on a client that is not open yet:
Queries and writes made early wait for the client. Nothing has to be reordered.
Functions that report state (injectSyncStatus, injectFeatureFlag) and db.auth.subscribe
report their not-known-yet value until the client is ready: signed out, the flag’s fallback.
Gate what a signed-out visitor must not see on await db.whenReady(), or on db.isReady.
Bootstrap no longer waits for the client, and no longer fails when it cannot start. The failure
is logged, db.whenReady() rejects, and the queries waiting on the client report it in error().
preload still runs once the client is ready, but no longer holds the first render back.
It is for the browser. A server render never starts the client, with or without eager, so
db.whenReady() never settles there.
db.isReady is a plain getter, not a signal. To show something only once the client is ready,
keep that in a signal:
private readonly db = injectDb<typeof schema>();protected readonly ready = signal(this.db.isReady);constructor() { // Rejects if the client fails to start: provideSp00ky logs that. this.db.whenReady().then( () => this.ready.set(true), () => {} );}
Rows only come back for queries that rendered in the first seconds of an earlier visit, on the
same browser, and only while no write has touched their tables since. That includes writes made
in another tab when sharedTabs is on.
Queries
injectQuery(query, options?) subscribes a component to a live query. It takes a function that
builds the query: the function re-runs when the signals it reads change, and the query is
re-registered only when its identity (its SurrealQL and vars) changes, not on every rebuild. Like
every inject* function it runs in an injection context (a field initializer or the constructor)
and ends with it; pass { injector } to call it anywhere else.
src/app/post-list.ts
import { ChangeDetectionStrategy, Component } from '@angular/core';import { injectDb, injectQuery } from '@spooky-sync/client-angular';import type { schema } from './schema.gen';@Component({ selector: 'app-post-list', templateUrl: './post-list.html', changeDetection: ChangeDetectionStrategy.OnPush,})export class PostList { private readonly db = injectDb<typeof schema>(); protected readonly posts = injectQuery(() => this.db.query('post').related('author').orderBy('created_at', 'desc').limit(20).build() );}
src/app/post-list.html
@if (posts.isLoading()) { <p>Loading…</p>} @else if (posts.isEmpty()) { <p>No posts yet.</p>} @else { <ul> @for (post of posts.data(); track post.id) { <li>{{ post.title }} by {{ post.author?.username }}</li> } </ul>}
Return null from the function (or pass { enabled: () => false }) to skip a query until its
inputs exist. Signal inputs work directly:
src/app/post-detail.ts
export class PostDetail { private readonly db = injectDb<typeof schema>(); readonly postId = input<string | null>(null); protected readonly post = injectQuery(() => { const id = this.postId(); return id ? this.db.query('post').where({ id }).one().build() : null; });}
A query that never changes can be passed as is (injectQuery(this.db.query('tag').build())). The
query builder itself (where, related, orderBy, limit, one) is covered in
Reactive queries.
Call the field, keep the object
Every field is a signal: read it as posts.data() in templates, computed() and effect().
Keep the result object on the component and call fields where you need them; a field read once
in the constructor is a one-time copy.
Result
Every field of the result is a read-only signal:
Field
Meaning
data
Rows, or the row / null for .one(). [] / null before the first result. Structurally shared between updates: unchanged rows keep their object identity, and an update that changes nothing does not notify.
error
Registration or sync error (e.g. SSP 503 during bootstrap). Never thrown; the sync scheduler retries underneath.
isLoading
Cold first load only: nothing painted for this query, the server has not answered, and registration has not failed. A paint from the local cache ends it; the server answering with zero rows ends it too.
isFetching
The sync engine is pulling records for this query (registration, a sync round).
isAuthoritative
data holds the rendered rows of a known membership: the server’s answer, or the one a previous session left on this device. From here data is an answer, not a cache guess.
hasData
data holds something: rows for a list, a row for .one().
isEmpty
Authoritative and no data: the server said “no rows”. Render empty states on this, never on a bare !hasData().
isSettled
Authoritative and idle. The gate for trusting a short window as the end of a list, and for “create it if it is missing”. Not monotonic: a later sync round re-enters isFetching.
When the query’s identity changes, the previous data stays on screen until the new query
answers, while the flags reset. Growing a .limit() therefore never flashes an empty list:
Options: { enabled?: boolean | Signal<boolean>, deregisterOnCleanup?: boolean, injector?: Injector }.
Use deregisterOnCleanup for viewport windows that mount and unmount a query per page, see
Pagination.
Preloading
injectPreload(query) warms the local cache for a query the user is likely to open next, without
subscribing to it. When they navigate, the page paints from the cache immediately:
export class ThreadRow { private readonly db = injectDb<typeof schema>(); readonly id = input.required<string>(); constructor() { injectPreload(() => this.db.query('thread').where({ id: this.id() }).related('comments').one().build() ); }}
Authentication
Sign-in runs through the SurrealDB access methods in your schema, see
Authentication. db.auth.subscribe reports the signed-in user id now and on
every change, which makes a small service for the rest of the app:
src/app/auth.ts
import { computed, DestroyRef, inject, Injectable, signal } from '@angular/core';import { injectDb } from '@spooky-sync/client-angular';import type { schema } from './schema.gen';@Injectable({ providedIn: 'root' })export class Auth { private readonly db = injectDb<typeof schema>(); /** undefined until the client reports, then a user id or null. */ readonly userId = signal<string | null | undefined>(undefined); readonly isChecking = computed(() => this.userId() === undefined); constructor() { // subscribe() answers right away with the current user, then on every // sign-in and sign-out. It returns the unsubscribe, run when the app ends. inject(DestroyRef).onDestroy(this.db.auth.subscribe((id) => this.userId.set(id))); } signIn(username: string, password: string) { return this.db.auth.signIn('account', { username, password }); } signUp(username: string, password: string) { return this.db.auth.signUp('account', { username, password }); } signOut() { return this.db.signOut(); }}
A sign-in form wraps the call in injectSubmission for its pending and error state:
Every live query is scoped by your table permissions, so a user only ever syncs the rows they may
read. db.signOut() ends the session and clears the local data.
Mutations
Writes are plain calls on the client. Each one commits locally, re-renders every query it affects,
and syncs in the background, offline included:
For button pending and error state, wrap the call in injectSubmission. submit never rejects; a
failure lands in error. It only holds signals, so it needs no injection context:
src/app/new-post.ts
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';import { injectDb, injectSubmission } from '@spooky-sync/client-angular';import type { schema } from './schema.gen';@Component({ selector: 'app-new-post', templateUrl: './new-post.html', changeDetection: ChangeDetectionStrategy.OnPush,})export class NewPost { private readonly db = injectDb<typeof schema>(); protected readonly title = signal(''); protected readonly save = injectSubmission((title: string) => this.db.create('post:' + crypto.randomUUID(), { title }) );}
An error there means the local commit failed. Sync failures surface through injectSyncStatus and
injectPendingMutations instead. To track a backend job, query its outbox row: db.run() writes
one with status: 'pending'. See Mutations.
Sync status
injectSyncStatus reports the connection, injectPendingMutations the number of writes not yet on
the server. Together they make the usual offline banner:
None of them needs a component. In a providedIn: 'root' service they live as long as the app,
so one shared instance can serve every component:
src/app/sync-state.ts
import { Injectable } from '@angular/core';import { injectSyncActivity, injectSyncStatus } from '@spooky-sync/client-angular';@Injectable({ providedIn: 'root' })export class SyncState { readonly status = injectSyncStatus(); readonly activity = injectSyncActivity({ downloadDelayMs: 200 });}
Feature flags and releases
injectFeatureFlag(key, options?) reads a feature flag for the
signed-in user and updates live when the assignment changes, so spky flag enable reaches open tabs
without a reload. injectAppRelease tells a running tab that a newer frontend was deployed:
injectFileUpload and injectDownloadFile upload to and read from a
bucket. <sp00ky-bucket-image> renders a bucket file as an image, revealing it only once it is
decoded, with the stored blurhash as a placeholder while it loads. Paths (and bucket names) may be
signals. On a path change the previous object URL stays valid until the next one is ready, so the
image never flashes broken.
The component’s projected content is the bottom placeholder layer; the blurhash paints over it,
and the image crossfades in once its bitmap is decoded. For custom markup, injectBucketImage plus
the sp00kyImageGate directive set the <img>’s src and flip ready on decode, so do not bind
src as well. <canvas [sp00kyBlurhash]="hash"> paints a blurhash on its own:
A string field marked @crdt in the schema can be edited by several people at once.
injectCrdtField(table, id, field) opens its document while the component lives. It returns a
signal holding the CrdtField, or null until it has loaded; show the column’s plain text until
then:
src/app/note-summary.ts
import { ChangeDetectionStrategy, Component, effect, input, signal } from '@angular/core';import { injectCrdtField } from '@spooky-sync/client-angular';@Component({ selector: 'app-note-summary', templateUrl: './note-summary.html', changeDetection: ChangeDetectionStrategy.OnPush,})export class NoteSummary { /** The full record id, e.g. 'note:abc'. */ readonly id = input.required<string>(); /** The column's plain text, shown until the document has loaded. */ readonly summary = input.required<string>(); protected readonly field = injectCrdtField('note', this.id, 'summary'); protected readonly value = signal(''); constructor() { // Follow the document: local and remote edits alike update the textarea. effect((onCleanup) => { const doc = this.field()?.getDoc(); if (!doc) return; const text = doc.getText('summary'); this.value.set(text.toString()); onCleanup(doc.subscribe(() => this.value.set(text.toString()))); }); } protected edit(event: Event): void { const doc = this.field()?.getDoc(); if (!doc) return; doc.getText('summary').update((event.target as HTMLTextAreaElement).value); // minimal diff doc.commit(); }}
Binding a rich text editor and showing remote cursors are covered in CRDT fields.
Peer to peer channels
injectChannel(query, peers) opens a channel for the lifetime of the
component, for fast-changing state such as drafts or cursors that should reach other peers
directly. Both arguments may be signals or functions and are compared by value; a null query
closes the channel.
When an admin impersonates a user, the client shows a warning banner.
To render your own, set impersonationBanner: { mode: 'custom' } in the client config and call
injectImpersonation({ rendersBanner: true }), which tells the client your banner is on screen:
src/app/impersonation-banner.ts
import { ChangeDetectionStrategy, Component } from '@angular/core';import { injectImpersonation } from '@spooky-sync/client-angular';@Component({ selector: 'app-impersonation-banner', templateUrl: './impersonation-banner.html', changeDetection: ChangeDetectionStrategy.OnPush,})export class ImpersonationBanner { protected readonly imp = injectImpersonation({ rendersBanner: true });}
src/app/impersonation-banner.html
@if (imp.impersonation(); as active) { <div class="banner"> Acting as {{ active.target }} <button (click)="imp.stop()">Stop</button> </div>}
Server-side rendering
During a server render, provideSp00ky never starts the client, and every inject* function that
talks to it throws an error that says so. Keep the components that use it out of the server render:
A @defer block renders its @placeholder on the server and its content in the browser. For a
whole route, use renderMode: RenderMode.Client in app.routes.server.ts. The browser paints from
the local cache anyway, so little is lost.
Testing
SyncedDb is the DI token, so a test provides its own client: