Get started with local-first

This guide will help you get started with the Evolu local-first platform.

Requirements: TypeScript 7 or newer with exactOptionalPropertyTypes enabled. Evolu supports the current major version of each tool it works with, such as Vite, Next.js, React, Svelte, Vue, Expo, React Native, Electron and Node.js, as its examples use them. Older versions may work, but aren't supported.

Choose a platform
This selection will apply to all code examples on this page.

Installation

Evolu offers SDKs for a variety of frameworks, including React, Svelte, React Native, Expo, and others.

npm install @evolu/common @evolu/react @evolu/react-web @evolu/web

Define schema

First, define your app database schema—tables, columns, and types.

Evolu uses Type for data modeling. Instead of plain JS types like string or number, we recommend using branded types to enforce domain rules. You can also define columns with any library that implements Standard Schema, such as Zod, Valibot, or ArkType.

import {
  id,
  NonEmptyTrimmedString100,
  nullOr,
  SqliteBoolean,
} from "@evolu/common";

// Primary keys are branded types, preventing accidental use of IDs across
// different tables (e.g., a TodoId can't be used where a UserId is expected).
const TodoId = id("Todo");
type TodoId = typeof TodoId.Output;

// Schema defines the database structure and mutation/query types.
// Validate untrusted input before insert/update/upsert.
const Schema = {
  todo: {
    id: TodoId,
    // Branded type ensuring titles are non-empty and ≤100 chars.
    title: NonEmptyTrimmedString100,
    // SQLite doesn't support the boolean type; it uses 0 and 1 instead.
    isCompleted: nullOr(SqliteBoolean),
  },
};

Evolu automatically adds system columns: createdAt, updatedAt, isDeleted, and ownerId.

Create Evolu

After defining the schema, create one Run for the whole app, with your platform's deps:

import { createEvoluDeps } from "@evolu/react-web";
import { createRun } from "@evolu/web";

const run = createRun(createEvoluDeps());

Then create Evolu. Evolu is multitenant: an app can have several accounts, called AppOwners, on one device, such as a personal one and a work one. createEvoluApp creates them, keeps them on the device, and opens one:

import {
  AppName,
  createEvoluApp,
  NonEmptyTrimmedString100,
} from "@evolu/common";

const app = await run.orThrow(
  createEvoluApp(Schema, {
    appName: AppName.orThrow("your-app-name"),
    auth: { type: "InstantStart" },
    createFirstAppOwner: true,
  }),
);

// The open AppOwner, with its Evolu instance.
const current = app.current.get();
if (current) {
  const evolu = await current.evolu;
  evolu.insert("todo", { title: NonEmptyTrimmedString100.orThrow("Buy milk") });
}

The example sets two options that decide how the app starts: auth and createFirstAppOwner.

Auth

Evolu encrypts not only the data an app syncs but also the data it keeps on the device, because a browser doesn't protect localStorage, IndexedDB, or OPFS from other programs, such as malware. createEvoluApp keeps the AppOwners' secrets in one more database, the device database, so its key protects them all, and auth decides whether malware can read it:

  • DeviceSecret keeps the key where malware can't read it. On React Native, loadDeviceSecret protects it with the iOS Keychain or the Android Keystore. A browser has no such storage, so on the web, createPasskeyAuth unlocks it with a passkey. Unlike on mobile, the user has to confirm it on every start, as the passkey playground shows.
  • InstantStart uses a fixed key that Evolu provides, which is public, so the app starts without a prompt, but malware that can read the app's storage can read the AppOwners' secrets. It suits apps without sensitive data, where a passkey prompt on every start would only annoy users.

Choose the mode before the first release, because an account never moves from InstantStart to DeviceSecret. Local auth shows how to set up each.

createFirstAppOwner

For some apps, mobile ones especially, it makes sense to create the user's account when they first open the app and open it again at every later start. Onboarding is simpler, and because the account is local, it costs nothing. A user who already has an account can restore it from a menu, or the app can ask on the first start, "Already use the app? Restore your account." The empty account can then be removed.

createFirstAppOwner: true does this. Evolu provides it because on the web, creating exactly one account is harder than it looks: the app can run in several tabs at once, and a check in app code, such as in localStorage or IndexedDB, can race and create two AppOwners. Evolu creates the first AppOwner when the device database is created, so the app gets exactly one. An app that starts with a choice, such as to create an account or restore one, sets it to false.

Local auth shows how an app restores, switches, and removes accounts, and why to ask the user to back up the account's mnemonic.

React

In React, EvoluAppProvider from createEvoluBinding takes the app's promise, created once at module scope, such as appPromise from run.orThrow(createEvoluApp(…)), and provides the open AppOwner's instance, so useEvolu and the query hooks read its data. It renders under a Suspense boundary while the app opens, and renders withoutAppOwner while no AppOwner is open, such as after the user removed the last one:

React

import { createEvoluBinding } from "@evolu/react";
import { Suspense, type FC } from "react";

const { EvoluAppProvider, useEvolu, useQuery } =
  createEvoluBinding<typeof Schema>();

export const App: FC = () => (
  <Suspense fallback={<p>Opening…</p>}>
    <EvoluAppProvider value={appPromise} withoutAppOwner={<CreateOrRestore />}>
      <Todos />
    </EvoluAppProvider>
  </Suspense>
);

In Vue, EvoluAppProvider does the same, with composables typed by createEvoluBinding, and in Svelte, evoluAppState follows the open AppOwner and its instance.

Relays

Without transports, Evolu syncs through free.evoluhq.com, a testing relay whose data may be deleted. Set your own relays before release, or pass transports: [] to sync nothing.

Handle errors

Evolu reports problems that stop the app from working, such as local data that needs a newer version of the app or an unexpected failure, in run.deps.evoluError, a store shared by all Evolu instances created from the same deps. Show it, or such a failure goes unnoticed. Render it outside the Suspense boundary that waits for Evolu, because the queries of a database that can't open stay pending:

import { constNull } from "@evolu/common";
import { useSyncExternalStore, type FC } from "react";

export const EvoluErrorAlert: FC = () => {
  const error = useSyncExternalStore(
    run.deps.evoluError.subscribe,
    run.deps.evoluError.get,
    constNull,
  );
  if (!error) return null;
  return <p role="alert">Evolu error: {error.type}</p>;
};

Vue follows the store with useStore, Svelte with storeState, and other frameworks subscribe to it the same way. EvoluError lists each error and what to ask the user. Each one blocks the app: after an UnknownError, for example, Evolu is in an unknown state, so ask the user to close all the app's tabs, or on React Native to restart the app. A problem syncing through a relay is not an EvoluError; the owner's sync status shows it.

Two cases can stop the app as it starts. While another build of the app, running in another tab, keeps the database, the app waits, and evoluError shown outside the Suspense boundary tells the user. When the device database can't open, createEvoluApp rejects, so put an error boundary of your own around the Suspense boundary.

StartupErrorBoundary below is an error boundary of the app's own, which catches createEvoluApp's rejection and shows the failure instead of React unmounting the page:

import { Component, Suspense, type FC, type ReactNode } from "react";

class StartupErrorBoundary extends Component<
  { children: ReactNode },
  { failed: boolean }
> {
  override state = { failed: false };

  static getDerivedStateFromError(): { failed: boolean } {
    return { failed: true };
  }

  override render(): ReactNode {
    if (!this.state.failed) return this.props.children;
    return <p>The app couldn&apos;t start.</p>;
  }
}

export const App: FC = () => (
  <>
    <EvoluErrorAlert />
    <StartupErrorBoundary>
      <Suspense fallback={<p>Opening…</p>}>
        <EvoluAppProvider
          value={appPromise}
          withoutAppOwner={<CreateOrRestore />}
        >
          <Todos />
        </EvoluAppProvider>
      </Suspense>
    </StartupErrorBoundary>
  </>
);

Sync status

Evolu stores changes in the local database before they sync, so sync needs no UI while it works. Show the owner's sync status once, such as below the header, as one quiet line that appears only when no relay can be reached or a relay fails. React and Vue have useOwnerSyncStatus, and Svelte has ownerSyncStatusState. Other frameworks subscribe to run.deps.syncState and pass its value, the database's name, and the owner's ID to syncStateToOwnerSyncStatus. OwnerSyncStatus describes each status and what to show for it.

Mutate data

The examples below use evolu, the open AppOwner's instance.

import { sqliteFalse, sqliteTrue } from "@evolu/common";

const { insert, update } = useEvolu();

const { id: todoId } = insert("todo", {
  title: NonEmptyTrimmedString100.orThrow("New Todo"),
  isCompleted: sqliteFalse,
});

update("todo", { id: todoId, isCompleted: sqliteTrue });

Query data

Evolu uses Kysely, a type-safe SQL query builder for TypeScript, so autocompletion works out of the box.

Let's start with a simple Query.

import { createQueryBuilder } from "@evolu/common";

const createQuery = createQueryBuilder(Schema);
const allTodos = createQuery((db) => db.selectFrom("todo").selectAll());

Once we have a query, we can load or subscribe to it.

// Inside a component, use the useQuery binding created above.
const todos = useQuery(allTodos);

In React, useQuery suspends until its query loads, so render it inside Suspense. To load several queries at once, without a waterfall of suspensions, use useQueries. A query SQLite fails, for example one with a syntax error in a raw SQL fragment, throws to the nearest error boundary, while other queries and mutations keep working. In Vue, an async setup under Suspense awaits waitForRows with the rows its query composables returned, and a failure reaches onErrorCaptured. In Svelte, {#await} awaits loaded of queryState.

Local queries are typically fast, especially with indexes, so preloading is rarely needed. To start loading before a component renders, call evolu.loadQuery; useQuery reuses that load unless a mutation or sync drops it first.

Changes from other devices can arrive in any order, as Sync explains, so a row can be incomplete and a related row can be missing for a while. Queries shows how to write queries that handle that, and how to join and nest related rows.

Delete data

To delete a row, set isDeleted to sqliteTrue (1). Synced tables use soft deletes. Tables prefixed with _ delete the row permanently and have no sync history. In the examples below, todoId is the ID of the row to delete.

const { update } = useEvolu();

// Mark a todo as deleted
update("todo", { id: todoId, isDeleted: sqliteTrue });

When querying, filter out deleted rows:

const activeTodos = createQuery((db) =>
  db
    .selectFrom("todo")
    .selectAll()
    // Filter out deleted rows
    .where("isDeleted", "is not", sqliteTrue)
    .orderBy("createdAt"),
);

Synced tables retain deleted data to support merging across devices and time travel. This is essential for local-first systems where devices sync asynchronously. See Time Travel to learn how to recover deleted data.

Purge data

evolu.deleteDatabase() deletes the instance's local database on this device, and evolu.deleteOwner(owner) deletes the rows of a shard or shared owner from it and stops syncing the owner. Both delete only this device's copy: changes not yet synced are lost, and relays keep the data. With createEvoluApp, app.remove deletes an AppOwner's data and removes it from this device's list, as the full playground does.

To learn more about Evolu, explore our playgrounds and examples.