Node
Minimal example
Section titled “Minimal example”import { const makeAdapter: ({ sync, ...options }: NodeAdapterOptions & { sync?: SyncOptions;}) => Adapter
Runs everything in the same thread. Use makeWorkerAdapter for multi-threaded implementation.
makeAdapter } from '@livestore/adapter-node'import { const createStorePromise: <TSchema extends LiveStoreSchema = LiveStoreSchema.Any, TContext = {}, TSyncPayloadSchema extends Schema<any> = Schema<JsonValue, JsonValue, never>>({ signal, otelOptions, ...options }: CreateStoreOptions<TSchema, TContext, TSyncPayloadSchema> & { signal?: AbortSignal; otelOptions?: Partial<OtelOptions>;}) => Promise<Store<TSchema, TContext>>
Create a new LiveStore Store
createStorePromise } from '@livestore/livestore'import { const schema: FromInputSchema.DeriveSchema<{ events: { readonly todoCreated: EventDef<"v1.TodoCreated", { readonly id: string; readonly text: string; }, { readonly id: string; readonly text: string; }, false>; }; state: InternalState;}>
schema, const tables: { readonly todos: TableDef<SqliteTableDefForInput<"todos", { readonly id: { columnType: "text"; schema: Schema<string, string, never>; default: None<never>; nullable: false; primaryKey: true; autoIncrement: false; }; readonly text: { columnType: "text"; schema: Schema<string, string, never>; default: None<never>; nullable: false; primaryKey: false; autoIncrement: false; }; readonly completed: { columnType: "integer"; schema: Schema<boolean, number, never>; default: Some<false>; nullable: false; primaryKey: false; autoIncrement: false; }; }>, WithDefaults<...>, Schema<...>>;}
tables } from './livestore/schema.ts'
const const adapter: Adapter
adapter = function makeAdapter({ sync, ...options }: NodeAdapterOptions & { sync?: SyncOptions;}): Adapter
Runs everything in the same thread. Use makeWorkerAdapter for multi-threaded implementation.
makeAdapter({ NodeAdapterOptions.storage: { readonly type: "in-memory"; readonly importSnapshot?: Uint8Array<ArrayBuffer> | undefined;} | { readonly type: "fs"; readonly baseDirectory?: string | undefined;}
storage: { type: "fs"
type: 'fs' }, // sync: { backend: makeWsSync({ url: 'ws://localhost:8787' }) },})
const const main: () => Promise<void>
main = async () => { const const store: Store<FromInputSchema.DeriveSchema<{ events: { readonly todoCreated: EventDef<"v1.TodoCreated", { readonly id: string; readonly text: string; }, { readonly id: string; readonly text: string; }, false>; }; state: InternalState;}>, {}>
store = await createStorePromise<FromInputSchema.DeriveSchema<{ events: { readonly todoCreated: EventDef<"v1.TodoCreated", { readonly id: string; readonly text: string; }, { readonly id: string; readonly text: string; }, false>; }; state: InternalState;}>, {}, Schema<JsonValue, JsonValue, never>>({ signal, otelOptions, ...options }: CreateStoreOptions<FromInputSchema.DeriveSchema<{ events: { readonly todoCreated: EventDef<"v1.TodoCreated", { readonly id: string; readonly text: string; }, { readonly id: string; readonly text: string; }, false>; }; state: InternalState;}>, {}, Schema<...>> & { ...;}): Promise<...>
Create a new LiveStore Store
createStorePromise({ CreateStoreOptions<TSchema extends LiveStoreSchema, TContext = {}, TSyncPayloadSchema extends Schema<any> = Schema<JsonValue, JsonValue, never>>.adapter: Adapter
adapter, CreateStoreOptions<FromInputSchema.DeriveSchema<{ events: { readonly todoCreated: EventDef<"v1.TodoCreated", { readonly id: string; readonly text: string; }, { readonly id: string; readonly text: string; }, false>; }; state: InternalState; }>, {}, Schema<...>>.schema: FromInputSchema.DeriveSchema<{ events: { readonly todoCreated: EventDef<"v1.TodoCreated", { readonly id: string; readonly text: string; }, { readonly id: string; readonly text: string; }, false>; }; state: InternalState;}>
schema, CreateStoreOptions<TSchema extends LiveStoreSchema, TContext = {}, TSyncPayloadSchema extends Schema<any> = Schema<JsonValue, JsonValue, never>>.storeId: string
storeId: 'demo-store' })
const const todos: readonly { readonly id: string; readonly text: string; readonly completed: boolean;}[]
todos = const store: Store<FromInputSchema.DeriveSchema<{ events: { readonly todoCreated: EventDef<"v1.TodoCreated", { readonly id: string; readonly text: string; }, { readonly id: string; readonly text: string; }, false>; }; state: InternalState;}>, {}>
store.Store<FromInputSchema.DeriveSchema<{ events: { readonly todoCreated: EventDef<"v1.TodoCreated", { readonly id: string; readonly text: string; }, { readonly id: string; readonly text: string; }, false>; }; state: InternalState; }>, {}>.query: <readonly { readonly id: string; readonly text: string; readonly completed: boolean;}[]>(query: Queryable<readonly { readonly id: string; readonly text: string; readonly completed: boolean;}[]> | { query: string; bindValues: Bindable; schema?: Schema<readonly { readonly id: string; readonly text: string; readonly completed: boolean; }[], readonly { readonly id: string; readonly text: string; readonly completed: boolean; }[], never>;}, options?: { otelContext?: Context; debugRefreshReason?: RefreshReason;}) => readonly { readonly id: string; readonly text: string; readonly completed: boolean;}[]
Synchronously queries the database without creating a LiveQuery.
This is useful for queries that don't need to be reactive.
Example: Query builder
const completedTodos = store.query(tables.todo.where({ complete: true }))
Example: Raw SQL query
const completedTodos = store.query({ query: 'SELECT * FROM todo WHERE complete = 1', bindValues: {} })
query(const tables: { readonly todos: TableDef<SqliteTableDefForInput<"todos", { readonly id: { columnType: "text"; schema: Schema<string, string, never>; default: None<never>; nullable: false; primaryKey: true; autoIncrement: false; }; readonly text: { columnType: "text"; schema: Schema<string, string, never>; default: None<never>; nullable: false; primaryKey: false; autoIncrement: false; }; readonly completed: { columnType: "integer"; schema: Schema<boolean, number, never>; default: Some<false>; nullable: false; primaryKey: false; autoIncrement: false; }; }>, WithDefaults<...>, Schema<...>>;}
tables.todos: TableDef<SqliteTableDefForInput<"todos", { readonly id: { columnType: "text"; schema: Schema<string, string, never>; default: None<never>; nullable: false; primaryKey: true; autoIncrement: false; }; readonly text: { columnType: "text"; schema: Schema<string, string, never>; default: None<never>; nullable: false; primaryKey: false; autoIncrement: false; }; readonly completed: { columnType: "integer"; schema: Schema<boolean, number, never>; default: Some<false>; nullable: false; primaryKey: false; autoIncrement: false; };}>, WithDefaults<...>, Schema<...>>
todos) var console: Console
The console module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
- A
Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
- A global
console instance configured to write to process.stdout and
process.stderr. The global console can be used without importing the node:console module.
Warning: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the note on process I/O for
more information.
Example using the global console:
console.log('hello world');// Prints: hello world, to stdoutconsole.log('hello %s', 'world');// Prints: hello world, to stdoutconsole.error(new Error('Whoops, something bad happened'));// Prints error message and stack trace to stderr:// Error: Whoops, something bad happened// at [eval]:5:15// at Script.runInThisContext (node:vm:132:18)// at Object.runInThisContext (node:vm:309:38)// at node:internal/process/execution:77:19// at [eval]-wrapper:6:22// at evalScript (node:internal/process/execution:76:60)// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';console.warn(`Danger ${name}! Danger!`);// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
const out = getStreamSomehow();const err = getStreamSomehow();const myConsole = new console.Console(out, err);
myConsole.log('hello world');// Prints: hello world, to outmyConsole.log('hello %s', 'world');// Prints: hello world, to outmyConsole.error(new Error('Whoops, something bad happened'));// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';myConsole.warn(`Danger ${name}! Danger!`);// Prints: Danger Will Robinson! Danger!, to err
console.Console.log(message?: any, ...optionalParams: any[]): void (+3 overloads)
Prints to stdout with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to printf(3)
(the arguments are all passed to util.format()).
const count = 5;console.log('count: %d', count);// Prints: count: 5, to stdoutconsole.log('count:', count);// Prints: count: 5, to stdout
See util.format() for more information.
log(const todos: readonly { readonly id: string; readonly text: string; readonly completed: boolean;}[]
todos)}
const main: () => Promise<void>
main().Promise<void>.catch<undefined>(onrejected?: ((reason: any) => PromiseLike<undefined> | undefined) | null | undefined): Promise<void | undefined>
Attaches a callback for only the rejection of the Promise.
catch(() => var undefined
undefined)
import { const makeAdapter: ({ sync, ...options }: NodeAdapterOptions & { sync?: SyncOptions;}) => Adapter
Runs everything in the same thread. Use makeWorkerAdapter for multi-threaded implementation.
makeAdapter } from '@livestore/adapter-node'import { const createStorePromise: <TSchema extends LiveStoreSchema = LiveStoreSchema.Any, TContext = {}, TSyncPayloadSchema extends Schema<any> = Schema<JsonValue, JsonValue, never>>({ signal, otelOptions, ...options }: CreateStoreOptions<TSchema, TContext, TSyncPayloadSchema> & { signal?: AbortSignal; otelOptions?: Partial<OtelOptions>;}) => Promise<Store<TSchema, TContext>>
Create a new LiveStore Store
createStorePromise } from '@livestore/livestore'
import { import schema
schema, import tables
tables } from './livestore/schema.ts'
const const adapter: Adapter
adapter = function makeAdapter({ sync, ...options }: NodeAdapterOptions & { sync?: SyncOptions;}): Adapter
Runs everything in the same thread. Use makeWorkerAdapter for multi-threaded implementation.
makeAdapter({ NodeAdapterOptions.storage: { readonly type: "in-memory"; readonly importSnapshot?: Uint8Array<ArrayBuffer> | undefined;} | { readonly type: "fs"; readonly baseDirectory?: string | undefined;}
storage: { type: "fs"
type: 'fs' }, // sync: { backend: makeWsSync({ url: 'ws://localhost:8787' }) },})
const const main: () => Promise<void>
main = async () => { const const store: Store<any, {}>
store = await createStorePromise<any, {}, Schema<JsonValue, JsonValue, never>>({ signal, otelOptions, ...options }: CreateStoreOptions<any, {}, Schema<JsonValue, JsonValue, never>> & { signal?: AbortSignal; otelOptions?: Partial<OtelOptions>;}): Promise<Store<any, {}>>
Create a new LiveStore Store
createStorePromise({ CreateStoreOptions<TSchema extends LiveStoreSchema, TContext = {}, TSyncPayloadSchema extends Schema<any> = Schema<JsonValue, JsonValue, never>>.adapter: Adapter
adapter, CreateStoreOptions<any, {}, Schema<JsonValue, JsonValue, never>>.schema: any
schema, CreateStoreOptions<TSchema extends LiveStoreSchema, TContext = {}, TSyncPayloadSchema extends Schema<any> = Schema<JsonValue, JsonValue, never>>.storeId: string
storeId: 'demo-store' })
const const todos: unknown
todos = const store: Store<any, {}>
store.Store<any, {}>.query: <unknown>(query: Queryable<unknown> | { query: string; bindValues: Bindable; schema?: Schema<unknown, unknown, never>;}, options?: { otelContext?: Context; debugRefreshReason?: RefreshReason;}) => unknown
Synchronously queries the database without creating a LiveQuery.
This is useful for queries that don't need to be reactive.
Example: Query builder
const completedTodos = store.query(tables.todo.where({ complete: true }))
Example: Raw SQL query
const completedTodos = store.query({ query: 'SELECT * FROM todo WHERE complete = 1', bindValues: {} })
query(import tables
tables.any
todos) var console: Console
The console module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
- A
Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
- A global
console instance configured to write to process.stdout and
process.stderr. The global console can be used without importing the node:console module.
Warning: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the note on process I/O for
more information.
Example using the global console:
console.log('hello world');// Prints: hello world, to stdoutconsole.log('hello %s', 'world');// Prints: hello world, to stdoutconsole.error(new Error('Whoops, something bad happened'));// Prints error message and stack trace to stderr:// Error: Whoops, something bad happened// at [eval]:5:15// at Script.runInThisContext (node:vm:132:18)// at Object.runInThisContext (node:vm:309:38)// at node:internal/process/execution:77:19// at [eval]-wrapper:6:22// at evalScript (node:internal/process/execution:76:60)// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';console.warn(`Danger ${name}! Danger!`);// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
const out = getStreamSomehow();const err = getStreamSomehow();const myConsole = new console.Console(out, err);
myConsole.log('hello world');// Prints: hello world, to outmyConsole.log('hello %s', 'world');// Prints: hello world, to outmyConsole.error(new Error('Whoops, something bad happened'));// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';myConsole.warn(`Danger ${name}! Danger!`);// Prints: Danger Will Robinson! Danger!, to err
console.Console.log(message?: any, ...optionalParams: any[]): void (+3 overloads)
Prints to stdout with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to printf(3)
(the arguments are all passed to util.format()).
const count = 5;console.log('count: %d', count);// Prints: count: 5, to stdoutconsole.log('count:', count);// Prints: count: 5, to stdout
See util.format() for more information.
log(const todos: unknown
todos)}
const main: () => Promise<void>
main().Promise<void>.catch<undefined>(onrejected?: ((reason: any) => PromiseLike<undefined> | undefined) | null | undefined): Promise<void | undefined>
Attaches a callback for only the rejection of the Promise.
catch(() => var undefined
undefined)
Option A: Quick start
Section titled “Option A: Quick start”For a quick start, we recommend using our template app following the steps below.
-
Set up project from template
Terminal window bunx @livestore/cli@dev create --example node-todomvc-sync-cf livestore-appTerminal window pnpm dlx @livestore/cli@dev create --example node-todomvc-sync-cf livestore-appTerminal window npx @livestore/cli@dev create --example node-todomvc-sync-cf livestore-appReplace
livestore-appwith your desired app name. -
Install dependencies
It’s strongly recommended to use
bunorpnpmfor the simplest and most reliable dependency setup (see note on package management for more details).Terminal window bun installTerminal window pnpm installTerminal window npm installPro tip: You can use direnv to manage environment variables.
-
Run dev environment
Terminal window bun startTerminal window pnpm startTerminal window npm run start