Svelte guide
Build a local-first Svelte 5 app with Sp00ky: provider, live queries on runes, auth, mutations, sync status, files, CRDT fields and channels.
@spooky-sync/client-svelte connects Svelte 5 apps to Sp00ky, built on runes. A live query is an
object of reactive getters (posts.data, posts.isLoading) that markup, $derived and $effect
track like any other state. 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 Svelte 5.29 or newer.
The client runs SurrealDB and SQLite as WebAssembly with IndexedDB / OPFS storage and web
workers, so it only runs in the browser. <Sp00kyProvider> renders its fallback during a
server render; in SvelteKit, turn server rendering off as shown below.
Setup
- Install
- Configure Vite
The client loads its engines as WebAssembly and starts web workers, both found next to its own files. Keep the client’s packages out of dependency pre-bundling (pre-bundled, they look in the wrong folder), pre-bundle the core’s CommonJS dependencies instead, and build for
esnext:vite.config.tsIn SvelteKit, use
sveltekit()from@sveltejs/kit/viteinstead ofsvelte(), and turn server rendering off:src/routes/+layout.tsSee Client config for why each package is excluded.
- Generate types
This writes
schema.gen.tsfrom your.surqlschema: the table types every query and write is checked against. See Generated types. - Configure the clientsrc/lib/db.ts
Every key is documented in Client config.
- Mount the providersrc/routes/+layout.svelte
<Sp00kyProvider>creates the client, opens the local database and connects to the server, rendering thefallbacksnippet until it is ready. Its props:Prop Meaning configThe client config. Read once when the provider mounts; to switch databases, wrap the provider in a {#key}block.fallbackSnippet rendered until the client is ready. preloadAwaited before the children render, to warm the local cache. A failure is logged and the UI is revealed anyway. onReadyCalled with the client once it is ready. onErrorCalled if the client fails to start. eagerRender the children at once, before the client is ready. See below. A client that was handed to the tree is deliberately not closed when the provider is destroyed.
Rendering before the client is ready
By default nothing below the provider renders until the client has opened its local database.
With eager the children render at once:
With localEngine: 'rows', useQuery then holds,
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 tree is that it mounts on a client that is not open yet:
- Queries and writes made early wait for the client. Nothing has to be reordered.
- Hooks that report state (
useSyncStatus,useFeatureFlag) anddb.auth.subscribereport 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 onawait db.whenReady(), or ondb.isReadyin a handler (it is a plain getter, not reactive state). fallbackis never rendered, andpreloadno longer holds the UI back.- It is for client-rendered trees. A server render still produces the fallback.
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
useQuery(query, options?) subscribes a component to a live query. It takes a getter that builds
the query: the getter re-runs when the state it reads changes, and the query is re-registered only
when its identity (its SurrealQL and vars) changes, not on every rebuild.
Return null from the getter (or pass { enabled: () => false }) to skip a query until its inputs
exist:
A query that never changes can be passed as is (useQuery(db.query('tag').build())), and
useQuery(db, query, options?) takes the client explicitly, for code outside a provider. The query
builder itself (where, related, orderBy, limit, one) is covered in
Reactive queries.
Every field is a getter. const { data } = useQuery(...) copies data once and never updates.
Keep the object and read fields where you need them, in markup or in $derived:
Result
Every field of the result is a reactive getter:
| Field | Meaning |
|---|---|
data | Rows, or the row / null for .one(). [] / null before the first result. Structurally shared between updates. |
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 | (() => boolean), deregisterOnCleanup?: boolean }. Use
deregisterOnCleanup for viewport windows that mount and unmount a query per page, see
Pagination.
Preloading
usePreload(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:
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 helper for the rest of the app:
A sign-in form wraps the call in useSubmission 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. A $state object can be written directly:
For button pending and error state, wrap the call in useSubmission. submit never rejects; a
failure lands in error. It needs no component and no provider:
An error there means the local commit failed. Sync failures surface through useSyncStatus and
usePendingMutations instead. To track a backend job, query its outbox row: db.run() writes one
with status: 'pending'. See Mutations.
Sync status
useSyncStatus reports the connection, usePendingMutations the number of writes not yet on the
server. Together they make the usual offline banner:
| Hook | Returns |
|---|---|
useSyncStatus() | status, isHealthy, isDegraded, isOffline, isReconnecting, everConnected, connection, health |
usePendingMutations() | .current: the number of local writes waiting to sync |
useSyncActivity(options?) | isDownloading, isUploading, fetchingQueries, pendingMutations, debounced for a traffic indicator |
useStorageStatus() | status, isPersistent, isMemoryFallback, health for the local database |
What to show for each state is covered in Offline & sync health.
useSyncStatus, useStorageStatus and usePendingMutations need no component: they also take
the client as their argument, so one shared instance can live in a .svelte.ts module. Hooks that
open something (useQuery, useCrdtField, useChannel, the file hooks) or own timers
(useSyncActivity) must run while a component initialises, or inside $effect.root.
Feature flags and releases
useFeatureFlag(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. useAppRelease tells a running tab that a newer frontend was deployed:
Files and images
useFileUpload and useDownloadFile upload to and read from a bucket.
<BucketImage> renders a bucket file as an image, revealing it only once it is decoded, and
<Blurhash> / useBlurhash paint a placeholder while it loads. Paths are getters, the components
take class / imgClass, and the placeholder is a fallback snippet. On a path change the
previous object URL stays valid until the next one is ready, so the image never flashes broken.
For custom markup, useBucketImage returns a gate attachment. It sets the <img>’s src itself
and flips ready once the bitmap is decoded, so do not bind src as well:
Collaborative fields
A string field marked @crdt in the schema can be edited by several people at once.
useCrdtField(table, id, field) opens its document while the component is mounted. Its .current
is the CrdtField, or null until it has loaded; show the column’s plain text until then:
Binding a rich text editor and showing remote cursors are covered in CRDT fields.
Peer to peer channels
useChannel(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 getters and are compared by value; a null query closes the
channel.
Admin impersonation
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 read
useImpersonation({ rendersBanner: true }), which tells the client your banner is on screen:
SvelteKit without the provider
To create the client yourself (for example in a SvelteKit load), init() it and put it in
context with setDbContext; every hook below that layout then finds it through useDb():
To render before the client is ready with this setup,
create it with new SyncedDb(dbConfig, { eager: true }) and start init() without awaiting it.
No provider reports a failed init() then, so handle its rejection yourself.