### Install and Run TodoMVC Example
Source: https://github.com/livestorejs/livestore/blob/main/examples/web-todomvc-sync-cf/README.md
Installs project dependencies and starts the local development server for the TodoMVC example. This command is used for local development and testing.
```bash
pnpm install
pnpm --filter examples/web-todomvc-sync-cf dev
```
--------------------------------
### Install Example Workflows
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/sustainable-open-source/contributing/monorepo.mdx
Install dependencies and set up for example workflows within the LiveStore project.
```bash
dt examples:install
```
--------------------------------
### Install Dependencies and Run Development Server
Source: https://github.com/livestorejs/livestore/blob/main/examples/web-todomvc-react-router/README.md
Installs project dependencies and starts the development server for the React Router TodoMVC example. Access the application at http://localhost:60001.
```bash
pnpm install
pnpm --filter livestore-example-web-todomvc-react-router dev
```
--------------------------------
### Install and Run TodoMVC Locally
Source: https://github.com/livestorejs/livestore/blob/main/examples/web-todomvc/README.md
Install project dependencies and start the development server.
```bash
pnpm install
pnpm dev
```
--------------------------------
### Install Dependencies and Run Development Server
Source: https://github.com/livestorejs/livestore/blob/main/examples/web-todomvc-redwood/README.md
Installs project dependencies and starts the RedwoodJS development server for the TodoMVC example. Watch the terminal for the correct development URL.
```bash
pnpm install
pnpm --filter livestore-example-web-todomvc-redwood dev
```
--------------------------------
### Solid Store Setup
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/framework-integrations/solid-integration.mdx
Example of setting up a LiveStore for use with Solid. This snippet demonstrates the basic store definition.
```typescript
import { createStore } from "solid-js/store";
import { createLiveStore } from "@livestore/core";
export const [store, setStore] = createLiveStore(
createStore({
count: 0,
})
);
```
--------------------------------
### Minimal React Store Setup
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/framework-integrations/react-integration.mdx
A basic example demonstrating the minimal setup for using LiveStore in a React application.
```jsx
import React from 'react';
import { StoreRegistryProvider } from '@livestore/react';
function App() {
return (
{/* Your application components here */}
);
}
```
--------------------------------
### Install Dependencies and Start Local Development Server
Source: https://github.com/livestorejs/livestore/blob/main/examples/web-linearlite/README.md
Installs project dependencies and starts the Vite development server for local iteration. The dev server handles both UI and Cloudflare Sync worker.
```bash
pnpm install
pnpm --filter livestore-example-web-linearlite run dev
```
--------------------------------
### Run Example Deployments
Source: https://github.com/livestorejs/livestore/blob/main/contributor-docs/examples-cloudflare.md
Commands to build and deploy LiveStore examples to Cloudflare Workers. Use `--example-filter` to target specific examples or `--prod` for stable releases.
```bash
direnv exec . mono examples deploy # build + deploy all configured examples
```
```bash
direnv exec . mono examples deploy --example-filter web-
```
```bash
direnv exec . mono examples deploy --prod # stable release versions only
```
```bash
direnv exec . mono examples validate-links # verify published prod/dev demo URLs
```
--------------------------------
### Main Server-Side Client Example (TypeScript)
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/patterns/server-side-clients.mdx
This snippet demonstrates the core setup for a server-side client using the @livestore/adapter-node. It shows how to initialize LiveStore with the adapter and define event handlers.
```typescript
import { createClient } from "@livestore/adapter-node";
// Initialize the server-side client
const client = createClient({
// Configuration for the adapter
// e.g. database path, event handlers, etc.
});
// Example of reacting to state changes on the server side
client.onStateChange((state) => {
console.log("Server-side state updated:", state);
// e.g. send emails, push notifications, etc.
});
// Example of committing events on the server side
async function handleSensitiveOperation(data: any) {
await client.commitEvent("sensitive_operation", data);
}
// Start the client
client.start();
```
--------------------------------
### Deploy Example Workflows
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/sustainable-open-source/contributing/monorepo.mdx
Deploy the example workflows for the LiveStore project.
```bash
dt examples:deploy
```
--------------------------------
### Contrib CI Setup Steps
Source: https://github.com/livestorejs/livestore/blob/main/context/repo-architecture/spec.md
Example of composing setup atoms with contrib-specific identifiers in the Contrib CI workflow. This avoids reusing core-specific cache names and pnpm state keys.
```typescript
installNixStep(...)
applyMegarepoLockStep(...)
restorePnpmStateStep({ keyPrefix: 'livestore-contrib-pnpm-state-v1' })
cachixStep({ name: 'livestore-contrib', ... })
```
--------------------------------
### Start LiveStore MCP Server
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/building-with-livestore/tools/mcp.mdx
Use this command to start the MCP server for AI assistant integration. Ensure you have the LiveStore CLI installed.
```bash
bunx @livestore/cli mcp
```
--------------------------------
### Test Example Workflows
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/sustainable-open-source/contributing/monorepo.mdx
Run tests for the example workflows within the LiveStore project.
```bash
dt examples:test
```
--------------------------------
### Manage Examples with mono CLI
Source: https://github.com/livestorejs/livestore/blob/main/CLAUDE.md
Execute example workflows such as running, deploying, or testing them using the mono CLI.
```bash
mono examples
```
--------------------------------
### Start LiveStore MCP Server
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/building-with-livestore/tools/cli.mdx
Shows how to start the MCP server for AI assistant integration and lists available subcommands like 'coach' and 'tools'.
```bash
# Start MCP server
livestore mcp
# Available subcommands
livestore mcp coach # AI coaching assistant (requires API key env var)
livestore mcp tools # Development tools server
# Coach command requires API key - check implementation for specific variable name
# Example: OPENAI_API_KEY=your_key livestore mcp coach
```
--------------------------------
### Install Web Adapter and WA-SQLite
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/platform-adapters/web-adapter.mdx
Install the necessary packages for the LiveStore web adapter and its SQLite backend.
```bash
npm install @livestore/adapter-web @livestore/wa-sqlite
```
--------------------------------
### Install and Build Demo Project
Source: https://github.com/livestorejs/livestore/blob/main/packages/@local/astro-twoslash-code/README.md
Installs dependencies and builds the demo project for the Astro Twoslash Code integration.
```bash
pnpm install
pnpm --filter @local/astro-twoslash-code-demo snippets:build
pnpm --filter @local/astro-twoslash-code-demo dev
```
--------------------------------
### Install Dependencies with Bun
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/getting-started/vue.mdx
Use this command to install LiveStore and related dependencies using Bun. Ensure you have Bun 1.2 or higher installed.
```sh
bun install @livestore/livestore@latest @livestore/wa-sqlite@latest @livestore/adapter-web@latest @livestore/utils@latest @livestore/peer-deps@latest @livestore/devtools-vite@latest slashv/vue-livestore@latest vue@latest @vitejs/plugin-vue@latest vite-plugin-vue-devtools@latest
```
--------------------------------
### Install and Run LiveStore CLI
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/building-with-livestore/tools/cli.mdx
Shows different ways to install and run the LiveStore CLI, including recommended bunx usage and alternative npm/npx methods.
```bash
# Recommended: Use bunx (no installation needed)
bunx @livestore/cli --help
# Alternative options:
npm install -g @livestore/cli # Global install
npm install -D @livestore/cli # Project install
npx @livestore/cli --help # Use with npx
```
--------------------------------
### Install Cloudflare Adapter
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/platform-adapters/cloudflare-durable-object-adapter.mdx
Install the Cloudflare adapter and sync provider packages using pnpm.
```bash
pnpm add @livestore/adapter-cloudflare @livestore/sync-cf
```
--------------------------------
### Install LiveStore Packages (Default)
Source: https://github.com/livestorejs/livestore/blob/main/release/release-notes.md
Install the core LiveStore package along with web and React adapters.
```bash
pnpm add @livestore/livestore @livestore/adapter-web @livestore/wa-sqlite @livestore/react
```
--------------------------------
### Start Local Development Server
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/sync-providers/cloudflare.mdx
Command to start the local development server using Wrangler.
```bash
npx wrangler dev
```
--------------------------------
### Install Cloudflare Sync Provider
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/sync-providers/cloudflare.mdx
Install the Cloudflare sync provider package using pnpm.
```bash
pnpm add @livestore/sync-cf
```
--------------------------------
### Install Dependencies with Bun
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/getting-started/node.mdx
Install project dependencies using Bun. This is the recommended package manager for reliability.
```sh
bun install
```
--------------------------------
### Verify Example Worker Deployment
Source: https://github.com/livestorejs/livestore/blob/main/contributor-docs/examples-cloudflare.md
Locally verify that a new example Worker deploys correctly using the `--example-filter` flag.
```bash
direnv exec . mono examples deploy --example-filter
```
--------------------------------
### LiveStore CLI Configuration File Example
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/building-with-livestore/tools/cli.mdx
Example configuration file for LiveStore CLI, defining schema and syncBackend for MCP and sync commands.
```typescript
import { defineConfig } from '@livestore/cli'
export default defineConfig({
schema: {},
syncBackend: {},
})
```
--------------------------------
### Basic WebSocket Client Example
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/sync-providers/cloudflare.mdx
A straightforward example of a WebSocket client for LiveStore synchronization. Useful for simple real-time applications.
```typescript
import { LiveStore } from '@livestore/core'
import { createCloudflareSyncClient } from '@livestore/sync-cf'
const client = createCloudflareSyncClient({
transport: 'ws',
})
const liveStore = new LiveStore({ sync: client })
// Use liveStore as usual
```
--------------------------------
### Start MCP Server
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/building-with-livestore/tools/mcp.mdx
Run the MCP server locally using the LiveStore CLI. This command starts the server that AI assistants can connect to.
```bash
bunx @livestore/cli mcp server
```
--------------------------------
### Sync Backend Implementation Example
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/platform-adapters/expo-adapter.mdx
An example of how to implement a custom sync backend for the Expo adapter. This allows for real-time data synchronization across devices.
```typescript
import { SyncBackend } from '@livestore/core';
class MySyncBackend implements SyncBackend {
async sync(data: any) {
// Implement your synchronization logic here
console.log('Syncing data:', data);
}
async getChanges() {
// Implement logic to retrieve changes from the backend
return [];
}
}
const adapter = new ExpoAdapter({
syncBackend: new MySyncBackend()
});
```
--------------------------------
### Install LiveStore DevTools (bun)
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/tutorial/3-read-and-write-todos-via-livestore.mdx
Install the LiveStore DevTools package for the bun package manager. This is a prerequisite for using the DevTools.
```sh
bun add @livestore/devtools-vite@0.4.0-dev.14
```
--------------------------------
### Todo App Example
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/overview/introduction.mdx
A basic example of a Todo application using LiveStore. This demonstrates how to manage a list of todos and their completion status.
```typescript
import { useLiveQuery } from '@live/react';
import { Schema } from './schema';
function TodoApp() {
const todos = useLiveQuery();
return (
);
}
```
--------------------------------
### ElectricSQL Client Setup
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/sync-providers/electricsql.mdx
Basic client setup for syncing LiveStore with ElectricSQL. This code should be placed in your worker or server code.
```typescript
import { LiveStore } from '@livestore/core'
import { ElectricSync } from '@livestore/sync-electric'
const db = await new ElectricSync().init({
// ElectricSQL client configuration
// See: https://electric-sql.com/docs/api/clients/typescript
// ...
})
const store = new LiveStore(db)
// Use the store as usual
console.log(store.get('todos'))
```
--------------------------------
### Minimal Cloudflare Worker Setup
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/sync-providers/cloudflare.mdx
A minimal example of a Cloudflare Worker configured to use the LiveStore sync provider. This serves as a basic starting point.
```typescript
import { LiveStore } from '@livestore/core'
import { createCloudflareSyncClient } from '@livestore/sync-cf'
// Initialize LiveStore with a sync client
const liveStore = new LiveStore({
sync: createCloudflareSyncClient({ transport: 'http' }),
})
// Export a fetch handler for the worker
export default {
async fetch(request: Request): Promise {
// Handle incoming requests using the LiveStore sync client
return liveStore.sync.handleRequest(request)
},
}
```
--------------------------------
### Create Starter Project with Bun
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/tutorial/1-setup-starter-project.mdx
Use this command to create a new LiveStore project using the tutorial starter template with Bun as the package manager.
```sh
bunx @livestore/cli@dev create \
--example tutorial-starter livestore-todo-app
```
--------------------------------
### Develop Documentation Locally
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/sustainable-open-source/contributing/monorepo.mdx
Start a local development server for the project's documentation.
```bash
dt docs:dev
```
--------------------------------
### Create Starter Project with pnpm
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/tutorial/1-setup-starter-project.mdx
Use this command to create a new LiveStore project using the tutorial starter template with pnpm as the package manager.
```sh
pnpm dlx @livestore/cli@dev create \
--example tutorial-starter livestore-todo-app
```
--------------------------------
### Install LiveStoreJS Dependencies (pnpm)
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/getting-started/react-web.mdx
Manually install LiveStoreJS dependencies using pnpm. Ensure you have the correct dependency string from your project setup.
```sh
pnpm add
```
--------------------------------
### Install Dependencies with pnpm
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/getting-started/vue.mdx
Use this command to install LiveStore and related dependencies using pnpm. This is a recommended package manager for reliable dependency setup.
```sh
pnpm add @livestore/livestore@latest @livestore/wa-sqlite@latest @livestore/adapter-web@latest @livestore/utils@latest @livestore/peer-deps@latest @livestore/devtools-vite@latest slashv/vue-livestore@latest vue@latest @vitejs/plugin-vue@latest vite-plugin-vue-devtools@latest
```
--------------------------------
### Dry-run DevTools Artifact Repack (No Install)
Source: https://github.com/livestorejs/livestore/blob/main/contributor-docs/release-workflows.md
Use this command for a dry-run of the DevTools artifact repack when the setup has already been completed in the current CI job or local shell. This avoids redundant installation steps.
```bash
release:devtools-artifact:repack-dryrun:no-install
```
--------------------------------
### LiveStore Store Definition
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/framework-integrations/react-integration.mdx
Defines a LiveStore store with a simple counter. This example demonstrates basic store setup and usage.
```ts
import { Store } from '@livestore/core'
interface State {
count: number
}
export const store = new Store({
count: 0,
})
```
--------------------------------
### SQL Initialization and Query
Source: https://github.com/livestorejs/livestore/blob/main/packages/@livestore/wa-sqlite/demo/hello/hello.html
Example SQL statements to create a table, insert data, and select from it. This is a basic demonstration of SQL operations.
```sql
CREATE TABLE IF NOT EXISTS t(x PRIMARY KEY); INSERT OR REPLACE INTO t VALUES ('foo'), ('bar'); SELECT * FROM t;
```
--------------------------------
### Worker Adapter - Worker Thread
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/platform-adapters/node-adapter.mdx
Example of the worker thread setup for the Node.js worker adapter. This code runs in a separate worker thread.
```typescript
import { makeWorker } from '@livestore/node-adapter';
await makeWorker();
console.log('Worker thread started');
```
--------------------------------
### Get Name of Bound Parameter
Source: https://github.com/livestorejs/livestore/blob/main/packages/@livestore/wa-sqlite/docs/interfaces/SQLiteAPI.html
Retrieves the name of a bound parameter at a specific index in a prepared statement. Binding indices start at 1.
```javascript
sqlite3.bind_parameter_name(stmt, i);
```
--------------------------------
### LiveStore Atoms Setup for Effect
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/patterns/effect.mdx
Example of setting up LiveStore atoms within an Effect application context. This snippet demonstrates the basic structure for integrating LiveStore's state management with Effect's core functionalities.
```typescript
import { effect } from '@effect/io'
import { LiveStore } from '@livestore/core'
// Assume 'schema' is defined elsewhere
// const schema = ...
export const store = new LiveStore(schema)
export const atoms = {
// Define your atoms here
counter: store.atom({
key: 'counter',
default: 0,
}),
}
export type Atoms = typeof atoms
```
--------------------------------
### Build Documentation
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/sustainable-open-source/contributing/monorepo.mdx
Generate a static build of the project's documentation.
```bash
dt docs:build
```
--------------------------------
### Install Dependencies with npm
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/getting-started/vue.mdx
Use this command to install LiveStore and related dependencies using npm. Ensure you have Node.js {MIN_NODE_VERSION} or higher installed.
```sh
npm install @livestore/livestore@latest @livestore/wa-sqlite@latest @livestore/adapter-web@latest @livestore/utils@latest @livestore/peer-deps@latest @livestore/devtools-vite@latest slashv/vue-livestore@latest vue@latest @vitejs/plugin-vue@latest vite-plugin-vue-devtools@latest
```
--------------------------------
### Create a New LiveStore Project
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/building-with-livestore/tools/cli.mdx
Demonstrates creating a new LiveStore project using the CLI, including interactive selection, specifying an example and path, and using a specific branch.
```bash
# Interactive selection
livestore new-project
# Specify example and path
livestore new-project --example web-todomvc my-project
# Use specific branch
livestore new-project --branch main
```
--------------------------------
### Render Expo Examples with CardGrid
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/examples/expo-adapter.mdx
This snippet demonstrates how to dynamically render a list of Expo examples using Astro's CardGrid component. It maps over an array of example data, fetching demo links and displaying each example's details within a Card.
```astro
import { Card, CardGrid } from '@astrojs/starlight/components';
import { Image } from 'astro:assets';
import { contribExamplesUrl, expoExamples, getExampleDemoLinks } from '../../../data/examples.ts';
{expoExamples.map((example) => {
const { url, label } = getExampleDemoLinks(example);
return (
{example.image ? (
) : (
);
})}
```
--------------------------------
### Example deployment output with pnpm
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/tutorial/2-deploy-to-cloudflare.mdx
This is the expected output when running the 'deploy' script with pnpm, showing build progress and Cloudflare deployment details.
```text
➜ livestore-todo-app git:(main) ✗ pnpm run deploy
> livestore-todo-app@0.0.0 deploy /Users/nikolasburk/Projects/LiveStore/plain-react-tutorial/livestore-todo-app
> pnpm run build && wrangler deploy
> livestore-todo-app@0.0.0 build /Users/nikolasburk/Projects/LiveStore/plain-react-tutorial/livestore-todo-app
> tsc -b && vite build
vite v7.1.12 building for production...
✓ 29 modules transformed.
dist/.assetsignore 0.02 kB
dist/index.html 0.47 kB │ gzip: 0.30 kB
dist/wrangler.json 1.15 kB │ gzip: 0.56 kB
dist/assets/index-DEkdisv2.css 9.64 kB │ gzip: 2.74 kB
dist/assets/index-COIOT0yp.js 196.04 kB │ gzip: 61.45 kB
✓ built in 319ms
⛅️ wrangler 4.45.1
───────────────────
Using redirected Wrangler configuration.
- Configuration being used: "dist/wrangler.json"
- Original user's configuration: "wrangler.toml"
- Deploy configuration file: ".wrangler/deploy/config.json"
🌀 Building list of assets...
✨ Read 7 files from the assets directory /Users/nikolasburk/Projects/LiveStore/plain-react-tutorial/livestore-todo-app/dist
🌀 Starting asset upload...
🌀 Found 4 new or modified static assets to upload. Proceeding with upload...
+ /index.html
+ /assets/index-COIOT0yp.js
+ /livestore.svg
+ /assets/index-DEkdisv2.css
Uploaded 1 of 4 assets
Uploaded 2 of 4 assets
Uploaded 4 of 4 assets
✨ Success! Uploaded 4 files (2.67 sec)
Total Upload: 0.34 KiB / gzip: 0.23 KiB
Uploaded livestore-todo-app (13.40 sec)
Deployed livestore-todo-app triggers (4.40 sec)
https://livestore-todo-app.nikolas-burk.workers.dev
Current Version ID: 37ce16a4-0bfd-4ecb-829e-a2737c84d9cf
```
--------------------------------
### Install Dependencies with npm
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/getting-started/node.mdx
Install project dependencies using npm.
```sh
npm install
```
--------------------------------
### App Setup with StoreRegistryProvider and Suspense
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/framework-integrations/react-integration.mdx
Sets up the main application component with StoreRegistryProvider, Suspense for loading states, and ErrorBoundary for error handling.
```jsx
import React, { Suspense } from 'react';
import { StoreRegistryProvider } from '@livestore/react';
import { ErrorBoundary } from 'react-error-boundary';
import { useMyStore } from './useMyStore'; // Assuming useMyStore is defined elsewhere
function App() {
return (
Something went wrong}>
Loading...}>
);
}
function MyComponent() {
const myStore = useMyStore();
// Use myStore here
return
My Component
;
}
```
--------------------------------
### Main Web Adapter Usage
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/platform-adapters/web-adapter.mdx
Basic example demonstrating the main functionality of the web adapter.
```typescript
import { WebAdapter } from '@livestore/adapter-web';
const adapter = new WebAdapter();
// Use the adapter...
await adapter.open();
```
--------------------------------
### LiveStore Materializer Example
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/building-with-livestore/state/materializers.mdx
A basic example demonstrating the structure and usage of a LiveStore materializer.
```typescript
import type { Materializer } from '@effect/platform-node/Http/Server';
export const myMaterializer: Materializer<{
id: string;
name: string;
}> = (ctx, event) => {
// ... materializer logic here
return {
id: event.data.id,
name: event.data.name.toUpperCase(),
};
};
```
--------------------------------
### SQLiteAPI Instantiation and Usage
Source: https://github.com/livestorejs/livestore/blob/main/packages/@livestore/wa-sqlite/docs/interfaces/SQLiteAPI.html
Demonstrates how to import the wa-sqlite module, instantiate the SQLite API, and open a database connection using either the synchronous or asynchronous build.
```APIDOC
## SQLiteAPI Instantiation and Usage
### Description
This section outlines the steps to create an instance of the SQLite API and begin interacting with a database. It covers importing the necessary modules and factory functions, instantiating the API, and opening a database.
### Usage
```javascript
// Import an ES6 module factory function from one of the package builds,
// either 'wa-sqlite.mjs' (synchronous) or 'wa-sqlite-async.mjs' (asynchronous).
// You should only use the asynchronous build if you plan to use an
// asynchronous VFS or module.
import SQLiteESMFactory from 'wa-sqlite/dist/wa-sqlite.mjs';
// Import the Javascript API wrappers.
import * as SQLite from 'wa-sqlite';
// Use an async function to simplify Promise handling.
(async function() {
// Invoke the ES6 module factory to create the SQLite Emscripten module.
// This will fetch and compile the .wasm file.
const module = await SQLiteESMFactory();
// Use the module to build the API instance.
const sqlite3 = SQLite.Factory(module);
// Use the API to open and access a database.
const db = await sqlite3.open_v2('myDB');
// Further database operations can be performed on the 'db' object.
})();
```
### Notes
- The `wa-sqlite.mjs` build is synchronous, while `wa-sqlite-async.mjs` is asynchronous.
- The asynchronous build should be used if you plan to utilize an asynchronous VFS or module.
- Function signatures are slightly modified from the C API to be more JavaScript-friendly.
- For C functions returning an error code, the JavaScript wrapper will throw an exception with a `code` property on error.
- Some functions return a `Promise` to accommodate both synchronous and asynchronous SQLite builds, typically those involved in opening/closing a database or executing a statement.
### See Also
[https://sqlite.org/c3ref/funclist.html](https://sqlite.org/c3ref/funclist.html)
```
--------------------------------
### Complete Frontmatter Example
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/sustainable-open-source/contributing/docs.md
Illustrates a more complete frontmatter configuration, including 'title', 'description', and 'sidebar' options for navigation and SEO.
```yaml
---
title: Getting started with LiveStore + React
description: How to use LiveStore with React on the web.
sidebar:
label: React web
order: 1
---
```
--------------------------------
### Example Schema Definition
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/building-with-livestore/state/sqlite-schema.mdx
This snippet shows a basic example of defining a schema with a table and columns.
```typescript
import { State } from '@livestore/state';
export const schema = {
tables: {
users: State.SQLite.object({
id: State.SQLite.primaryKey('string'),
name: State.SQLite.text(),
email: State.SQLite.text({ isUnique: true }),
age: State.SQLite.integer({ isOptional: true }),
registeredAt: State.SQLite.datetime(),
}),
},
};
export type Schema = typeof schema;
```
--------------------------------
### Set up LiveStore Root Registry
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/getting-started/react-web.mdx
Initialize a `StoreRegistry` and provide it using `` to manage store lifecycles across your application. Wrap the provider in a `Suspense` boundary to handle initial loading states.
```typescript
import React, { Suspense } from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { StoreRegistryProvider } from "livestore-js/react";
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
Loading...
}>
);
```
--------------------------------
### Complete Usage Example: App and Route Components
Source: https://github.com/livestorejs/livestore/blob/main/contributor-docs/rfcs/0001-multi-store-api-design.md
Demonstrates a full implementation of the multi-store API within a React application. It shows how to set up the StoreRegistryProvider, define and use singleton and multi-instance stores, and manage state within components.
```tsx
import { useState, useMemo, Suspense } from 'react'
import { unstable_batchedUpdates as batchUpdates } from 'react-dom'
import { StoreRegistry, storeOptions } from '@livestore/livestore'
import { StoreRegistryProvider, useStoreRegistry, useStore } from '@livestore/react'
import {
workspaceSchema,
workspaceAdapter,
workspaceEvents,
selectWorkspaceQuery,
selectWorkspaceIssueIdsQuery,
} from './workspace'
import { issueSchema, issueAdapter, issueEvents, selectIssueQuery } from './issue'
// Workspace store (singleton)
export const workspaceStoreOptions = storeOptions({
storeId: 'workspace-root',
schema: workspaceSchema,
adapter: workspaceAdapter,
unusedCacheTime: Number.POSITIVE_INFINITY, // Disable automatic disposal
boot: (store) => {
// Callback triggered when the store is first loaded
},
})
// Issue store (multi-instance)
export const issueStoreOptions = (issueId: string) =>
storeOptions({
storeId: `issue-${issueId}`,
schema: issueSchema,
adapter: issueAdapter,
unusedCacheTime: 20_000,
boot: (issueStore) => {
// Callback triggered when the store is first loaded
},
})
function App({ children }: { children: React.ReactNode }) {
const [storeRegistry] = useState(
() =>
new StoreRegistry({
defaultOptions: {
batchUpdates,
syncPayload: { authToken: 'insecure-token-change-me' },
},
}),
)
return {children}
}
type RouterLoaderContext = {
storeRegistry: StoreRegistry
}
export async function RouteLoader({ context }: { context: RouterLoaderContext }) {
context.storeRegistry.preload(workspaceStoreOptions)
}
export default function Route() {
const workspaceStore = useStore(workspaceStoreOptions) // Suspends
const [workspace] = workspaceStore.useQuery(selectWorkspaceQuery)
const issueIds = workspaceStore.useQuery(selectWorkspaceIssueIdsQuery(workspace.id))
const createIssue = () => {
workspaceStore.commit(workspaceEvents.issueCreated({ title: `Issue ${issueIds.length + 1}` }))
}
const [selectedIssueId, setSelectedIssueId] = useState()
const storeRegistry = useStoreRegistry()
const preloadIssue = (issueId: string) =>
storeRegistry.preload({
...issueStoreOptions(issueId),
unusedCacheTime: 5 * 1000,
})
return (
<>
>
)
}
```
--------------------------------
### Creating a SQLiteAPI Instance
Source: https://github.com/livestorejs/livestore/blob/main/packages/@livestore/wa-sqlite/docs/interfaces/SQLiteAPI.html
Demonstrates how to import and instantiate the SQLite API from wa-sqlite. This example shows the process for both synchronous and asynchronous builds, including fetching the WASM module and opening a database.
```javascript
import SQLiteESMFactory from 'wa-sqlite/dist/wa-sqlite.mjs';
import * as SQLite from 'wa-sqlite';
(async function() {
const module = await SQLiteESMFactory();
const sqlite3 = SQLite.Factory(module);
const db = await sqlite3.open_v2('myDB');
...
})();
```
--------------------------------
### Start Long-Running Processes
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/sustainable-open-source/contributing/monorepo.mdx
Start background services defined in `devenv.nix`, such as the local OpenTelemetry stack.
```bash
devenv up
```
--------------------------------
### Start Cloudflare Worker (yarn)
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/getting-started/expo.mdx
Start the Cloudflare Worker for the sync backend using yarn.
```sh
yarn wrangler:dev
```
--------------------------------
### Basic Expo App Setup with LiveStore
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/platform-adapters/expo-adapter.mdx
Demonstrates creating a LiveStore adapter, a custom hook, and setting up the StoreRegistryProvider for an Expo application.
```typescript
import { ExpoAdapter } from "@livestore/adapter-expo";
import { StoreRegistryProvider, createStoreRegistry } from "@livestore/react";
import { useAppStore } from "./useAppStore";
const adapter = new ExpoAdapter({
// Configuration options can go here
});
const registry = createStoreRegistry(adapter, useAppStore);
export function App() {
return (
{/* Your app content */}
);
}
```
--------------------------------
### Start Cloudflare Worker (npm)
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/getting-started/expo.mdx
Start the Cloudflare Worker for the sync backend using npm.
```sh
npm run wrangler:dev
```
--------------------------------
### Setting up Webmesh Nodes and Channels
Source: https://github.com/livestorejs/livestore/blob/main/packages/@livestore/webmesh/README.md
Demonstrates how to set up three nodes (A, B, C) and establish a direct channel between A and C through intermediate nodes B. This example uses MessageChannel for edge connections.
```typescript
import { makeMeshNode, Packet, WebChannel } from '@livestore/webmesh'
const ChannelSchema = Schema.Struct({ message: Schema.String })
// Creating shared message channels between nodes to simplify the example.
// In a real-world application, you would use e.g. a shared worker or similar to exchange the message channels between nodes.
const mcA_B = new MessageChannel()
const mcB_C = new MessageChannel()
// e.g. running in tab A of a browser
const codeOnNodeA = Effect.gen(function* () {
const nodeA = yield* makeMeshNode('A')
// create edge to node B using a MessageChannel
const edgeChannelB = yield* WebChannel.messagePortChannel({ port: mcA_B.port1, schema: Packet })
yield* nodeA.addEdge({ target: 'B', edgeChannel: edgeChannelB })
const channelToC = yield* nodeA.makeChannel({ target: 'C', schema: ChannelSchema })
yield* channelToC.send('Hello from A')
})
// e.g. running in tab B of a browser
const codeOnNodeB = Effect.gen(function* () {
const nodeB = yield* makeMeshNode('B')
const edgeChannelA = yield* WebChannel.messagePortChannel({ port: mcA_B.port2, schema: Packet })
yield* nodeB.addEdge({ target: 'A', edgeChannel: edgeChannelA })
const edgeChannelC = yield* WebChannel.messagePortChannel({ port: mcB_C.port2, schema: Packet })
yield* nodeB.addEdge({ target: 'C', edgeChannel: edgeChannelC })
})
// e.g. running in tab C of a browser
const codeOnNodeC = Effect.gen(function* () {
const nodeC = yield* makeMeshNode('C')
const edgeChannelB = yield* WebChannel.messagePortChannel({ port: mcB_C.port1, schema: Packet })
yield* nodeC.addEdge({ target: 'B', edgeChannel: edgeChannelB })
const channelToA = yield* nodeC.makeChannel({ target: 'A', schema: ChannelSchema })
const message = yield* channelToA.listen.pipe(Stream.take(1), Stream.runCollect)
console.log('message', message) // => 'Hello from A'
})
```
--------------------------------
### Start Cloudflare Worker (pnpm)
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/getting-started/expo.mdx
Start the Cloudflare Worker for the sync backend using pnpm.
```sh
pnpm wrangler:dev
```
--------------------------------
### Deploy Documentation
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/sustainable-open-source/contributing/monorepo.mdx
Deploy the project's documentation.
```bash
dt docs:deploy
```
--------------------------------
### Start Cloudflare Worker (bun)
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/getting-started/expo.mdx
Start the Cloudflare Worker for the sync backend using bun.
```sh
bun wrangler:dev
```
--------------------------------
### Install LiveStore Packages (Cloudflare)
Source: https://github.com/livestorejs/livestore/blob/main/release/release-notes.md
Install the core LiveStore package with Cloudflare adapters for Workers/Durable Objects.
```bash
# Or for Cloudflare
pnpm add @livestore/livestore @livestore/adapter-cloudflare @livestore/sync-cf
```
--------------------------------
### Install Expo Adapter Dependencies
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/platform-adapters/expo-adapter.mdx
Install the necessary Expo adapter and related packages using npm.
```bash
npm install @livestore/adapter-expo @livestore/livestore @livestore/react expo-sqlite expo-application
```
--------------------------------
### LiveStore Instance Connect Parameters
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/building-with-livestore/tools/mcp.mdx
Example parameters for connecting a LiveStore instance.
```json
{ "configPath": "livestore-cli.config.ts", "storeId": "" }
```
--------------------------------
### Install Dependencies with pnpm
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/getting-started/node.mdx
Install project dependencies using pnpm. This is a recommended package manager for reliability.
```sh
pnpm install
```
--------------------------------
### Run Dev Environment (npm)
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/getting-started/react-web.mdx
Start the development server using npm. This command will typically launch the application and enable hot-reloading.
```sh
npm run dev
```
--------------------------------
### Clone and Enter Development Shell
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/sustainable-open-source/contributing/monorepo.mdx
Clone the LiveStore repository and enter the development shell to set up the project environment.
```bash
git clone git@github.com:livestorejs/livestore.git
cd livestore
devenv shell
```
--------------------------------
### Worker: Authentication Example
Source: https://github.com/livestorejs/livestore/blob/main/docs/src/content/docs/sync-providers/cloudflare.mdx
Provides an example of how to implement authentication within a Cloudflare Worker for LiveStore synchronization.
```typescript
import { createWorker } from '@livestore/sync-cf'
import { LiveStore } from '@livestore/core'
const liveStore = new LiveStore({ sync: /* your sync client */ })
export default {
async fetch(request: Request): Promise {
const worker = createWorker(liveStore)
// Add custom authentication logic before handling the request
worker.use(async (req, next) => {
if (!req.headers.get('Authorization')) {
return new Response('Unauthorized', { status: 401 })
}
// Proceed to the next middleware or the request handler
return next()
})
return worker.handleRequest(request)
},
}
```