Github|...

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.

Browser only

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

  1. Install
    pnpm add @spooky-sync/core @spooky-sync/client-svelte
    pnpm add -D vite-plugin-wasm
  2. 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.ts
    import { defineConfig } from 'vite';
    import { svelte } from '@sveltejs/vite-plugin-svelte';
    import wasm from 'vite-plugin-wasm';
    
    export default defineConfig({
      plugins: [svelte(), wasm()],
      optimizeDeps: {
        // Served as is: pre-bundled, these look for their .wasm files and
        // workers in the wrong folder.
        exclude: [
          '@spooky-sync/client-svelte',
          '@spooky-sync/core',
          '@spooky-sync/ssp-wasm',
          '@surrealdb/wasm',
          '@surrealdb/wasm-native',
          '@sqlite.org/sqlite-wasm',
        ],
        // The excluded core's CommonJS dependencies, pre-bundled for it.
        include: ['@spooky-sync/core > pino', '@spooky-sync/core > fast-json-patch'],
      },
      // The client uses top-level await.
      build: { target: 'esnext' },
    });

    In SvelteKit, use sveltekit() from @sveltejs/kit/vite instead of svelte(), and turn server rendering off:

    src/routes/+layout.ts
    // The client is browser-only (WebAssembly, IndexedDB, workers).
    export const ssr = false;

    See Client config for why each package is excluded.

  3. Generate types
    # Driven by the clientTypes entries in sp00ky.yml
    spky generate

    This writes schema.gen.ts from your .surql schema: the table types every query and write is checked against. See Generated types.

  4. Configure the client
    src/lib/db.ts
    import type { SyncedDbConfig } from '@spooky-sync/client-svelte';
    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',
      },
    };

    Every key is documented in Client config.

  5. Mount the provider
    src/routes/+layout.svelte
    <script lang="ts">
      import { Sp00kyProvider } from '@spooky-sync/client-svelte';
      import { dbConfig } from '$lib/db';
    
      let { children } = $props();
    </script>
    
    <Sp00kyProvider
      config={dbConfig}
      preload={async (db) => {
        // Optional: warm the local cache before the UI is revealed.
        await db.preload(db.query('config').build());
      }}
      onError={(err) => console.error('Failed to initialize database:', err)}
    >
      {#snippet fallback()}
        <div>Initializing database…</div>
      {/snippet}
      {@render children()}
    </Sp00kyProvider>

    <Sp00kyProvider> creates the client, opens the local database and connects to the server, rendering the fallback snippet until it is ready. Its props:

    PropMeaning
    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:

src/routes/+layout.svelte
<Sp00kyProvider config={dbConfig} eager>
  {@render children()}
</Sp00kyProvider>

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) 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 in a handler (it is a plain getter, not reactive state).
  • fallback is never rendered, and preload no 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.

src/lib/PostList.svelte
<script lang="ts">
  import { useDb, useQuery } from '@spooky-sync/client-svelte';
  import type { schema } from './schema.gen';

  const db = useDb<typeof schema>();
  const posts = useQuery(() =>
    db.query('post').related('author').orderBy('created_at', 'desc').limit(20).build()
  );
</script>

{#if posts.isLoading}
  <div>Loading…</div>
{:else if posts.isEmpty}
  <div>No posts yet.</div>
{:else}
  <ul>
    {#each posts.data as post (String(post.id))}
      <li>{post.title} by {post.author?.username}</li>
    {/each}
  </ul>
{/if}

Return null from the getter (or pass { enabled: () => false }) to skip a query until its inputs exist:

<script lang="ts">
  let { postId }: { postId: string | null } = $props();

  const db = useDb<typeof schema>();
  const post = useQuery(() =>
    postId ? db.query('post').where({ id: postId }).one().build() : null
  );
</script>

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.

Do not destructure a result

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:

// Wrong: a one-time copy that never updates.
const { data } = useQuery(() => db.query('post').build());

// Right: keep the object, read fields where they are used.
const posts = useQuery(() => db.query('post').build());
const count = $derived(posts.data.length);

Result

Every field of the result is a reactive getter:

FieldMeaning
dataRows, or the row / null for .one(). [] / null before the first result. Structurally shared between updates.
errorRegistration or sync error (e.g. SSP 503 during bootstrap). Never thrown; the sync scheduler retries underneath.
isLoadingCold 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.
isFetchingThe sync engine is pulling records for this query (registration, a sync round).
isAuthoritativedata 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.
hasDatadata holds something: rows for a list, a row for .one().
isEmptyAuthoritative and no data: the server said “no rows”. Render empty states on this, never on a bare !hasData.
isSettledAuthoritative 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:

<script lang="ts">
  let limit = $state(20);
  const posts = useQuery(() =>
    db.query('post').orderBy('created_at', 'desc').limit(limit).build()
  );
</script>

<button disabled={!posts.isSettled} onclick={() => (limit += 20)}>Load more</button>

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:

<script lang="ts">
  import { useDb, usePreload } from '@spooky-sync/client-svelte';

  let { id }: { id: string } = $props();
  const db = useDb<typeof schema>();
  usePreload(() => db.query('thread').where({ id }).related('comments').one().build());
</script>

<a href={'/thread/' + id}>Open</a>

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:

src/lib/auth.svelte.ts
import { useDb } from '@spooky-sync/client-svelte';
import type { schema } from './schema.gen';

export function useAuth() {
  const db = useDb<typeof schema>();
  // undefined until the client reports, then a user id or null.
  let userId = $state<string | null | undefined>(undefined);

  // subscribe() answers right away with the current user, then on every
  // sign-in and sign-out. It returns the unsubscribe the effect tears down with.
  $effect(() => db.auth.subscribe((id) => (userId = id)));

  return {
    get userId() {
      return userId;
    },
    get isChecking() {
      return userId === undefined;
    },
    signIn: (username: string, password: string) =>
      db.auth.signIn('account', { username, password }),
    signUp: (username: string, password: string) =>
      db.auth.signUp('account', { username, password }),
    signOut: () => db.signOut(),
  };
}

A sign-in form wraps the call in useSubmission for its pending and error state:

src/lib/SignIn.svelte
<script lang="ts">
  import { useSubmission } from '@spooky-sync/client-svelte';
  import { useAuth } from '$lib/auth.svelte';

  const auth = useAuth();
  let username = $state('');
  let password = $state('');
  const signIn = useSubmission(auth.signIn);
</script>

{#if auth.userId}
  <button onclick={() => auth.signOut()}>Sign out</button>
{:else if !auth.isChecking}
  <form
    onsubmit={(e) => {
      e.preventDefault();
      void signIn.submit(username, password);
    }}
  >
    <input bind:value={username} />
    <input type="password" bind:value={password} />
    <button disabled={signIn.pending}>Sign in</button>
    {#if signIn.error}<p>{signIn.error.message}</p>{/if}
  </form>
{/if}

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:

import { RecordId } from '@spooky-sync/client-svelte';

// Create takes a full record id and the row.
await db.create('post:' + crypto.randomUUID(), {
  title: 'Hi',
  author: new RecordId('user', userId),
});

// Update merges only the listed fields.
await db.update('post', 'post:xyz', { title: 'Edited' });

// Delete takes an id string or the RecordId a live row carries.
await db.delete('post', row.id);

// Run a backend job through the outbox.
await db.run('backend', 'sendMail', { to });

// A $state object is copied before it reaches the engine's workers.
let draft = $state({ title: '', tags: [] as string[] });
await db.create('post:' + crypto.randomUUID(), draft);

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:

<script lang="ts">
  import { useDb, useSubmission } from '@spooky-sync/client-svelte';

  const db = useDb<typeof schema>();
  let title = $state('');
  const save = useSubmission((t: string) =>
    db.create('post:' + crypto.randomUUID(), { title: t })
  );
</script>

<form
  onsubmit={(e) => {
    e.preventDefault();
    void save.submit(title);
  }}
>
  <input bind:value={title} />
  <button disabled={save.pending}>Save</button>
  {#if save.error}<p>{save.error.message}</p>{/if}
</form>

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:

src/lib/ConnectionBanner.svelte
<script lang="ts">
  import { useSyncStatus, usePendingMutations } from '@spooky-sync/client-svelte';

  const sync = useSyncStatus();
  const pending = usePendingMutations();
</script>

{#if sync.isDegraded}
  <div class="banner">Can't reach the server, {pending.current} change(s) queued.</div>
{/if}
HookReturns
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:

<script lang="ts">
  import { useAppRelease, useFeatureFlag } from '@spooky-sync/client-svelte';

  const newEditor = useFeatureFlag('new-editor', { fallback: 'off' });
  const release = useAppRelease({ app: 'web', currentVersion: __APP_VERSION__ });
</script>

{#if newEditor.enabled}
  <NewEditorButton />
{:else}
  <EditorButton />
{/if}

{#if release.updateAvailable}
  <button onclick={() => release.reload()}>Update to {release.latestVersion}</button>
{/if}

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.

<script lang="ts">
  import { BucketImage, useFileUpload } from '@spooky-sync/client-svelte';

  let { path }: { path: string | null } = $props();
  const files = useFileUpload('avatars');
</script>

<BucketImage bucket="avatars" {path} class="h-12 w-12 rounded-full" alt="">
  {#snippet fallback()}<div class="h-full w-full bg-neutral-200"></div>{/snippet}
</BucketImage>

<input
  type="file"
  disabled={files.isUploading}
  onchange={(e) => {
    const file = e.currentTarget.files?.[0];
    if (file) void files.upload(crypto.randomUUID() + '.png', file);
  }}
/>

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:

<script lang="ts">
  import { useBucketImage } from '@spooky-sync/client-svelte';

  let { coverKey }: { coverKey: string | null } = $props();
  const image = useBucketImage('covers', () => coverKey);
</script>

<img {@attach image.gate} alt="" style:opacity={image.ready ? 1 : 0} />

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:

<script lang="ts">
  import { useCrdtField } from '@spooky-sync/client-svelte';

  // id is the full record id, e.g. 'note:abc'; summary is the column's plain text.
  let { id, summary }: { id: string; summary: string } = $props();
  const field = useCrdtField('note', () => id, 'summary');
  let value = $state('');

  // Follow the document: local and remote edits alike update the textarea.
  $effect(() => {
    const doc = field.current?.getDoc();
    if (!doc) return;
    const text = doc.getText('summary');
    value = text.toString();
    return doc.subscribe(() => (value = text.toString()));
  });
</script>

<textarea
  value={field.current ? value : summary}
  readonly={!field.current}
  oninput={(e) => {
    const doc = field.current?.getDoc();
    if (!doc) return;
    doc.getText('summary').update(e.currentTarget.value); // minimal diff
    doc.commit();
  }}
></textarea>

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.

import { useChannel } from '@spooky-sync/client-svelte';

const ch = useChannel(
  () => db.query('message').where({ conversation: convoId }),
  () => [me, other]
);
// ch.status: 'idle' | 'connecting' | 'connected' | 'failed' | 'unsupported'
await ch.update('message', id, { draft: text });

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:

<script lang="ts">
  import { useImpersonation } from '@spooky-sync/client-svelte';

  const imp = useImpersonation({ rendersBanner: true });
</script>

{#if imp.impersonation}
  <div class="banner">
    Acting as {imp.impersonation.target}
    <button onclick={() => void imp.stop()}>Stop</button>
  </div>
{/if}

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():

// src/lib/db.ts
import { SyncedDb } from '@spooky-sync/client-svelte';
export const db = new SyncedDb(dbConfig);

// src/routes/+layout.ts
export const ssr = false;
export const load = async () => {
  await db.init();
};
src/routes/+layout.svelte
<script lang="ts">
  import { setDbContext } from '@spooky-sync/client-svelte';
  import { db } from '$lib/db';

  let { children } = $props();
  setDbContext(db);
</script>

{@render children()}

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.

Next