Skip to content

Quickstart ​

You will design the events of a todo app, run it on a local server and read it back from a script. About ten minutes.

You need Node 24 or newer.

bash
mkdir todo-app && cd todo-app
npm init -y
npm pkg set type=module
npm install @iwentsourcing/core @iwentsourcing/client @iwentsourcing/cli tsx

1 · Define a realm ​

A realm says who may sign in. Every stream belongs to one.

ts
// src/realm.ts
import { defineRealm } from '@iwentsourcing/core/realm/define-realm.js';
import { jwtStore } from '@iwentsourcing/core/authentication/jwt-store.js';

export const todoRealm = defineRealm('todo', {
  providers: {
    custom: jwtStore({
      issuer: 'todo-app',
      audience: 'todo-app',
      // at least 32 bytes, read it from your environment in production
      secret: 'change-me-this-secret-is-32-bytes-long',
    }),
  },
});

2 · Design the events ​

This is the part that matters. The events are the facts of your application, everything else is derived from them. The state is a read model that the handlers keep up to date, and the platform can rebuild it by replaying the events.

ts
// src/todo.ts
import { declareEvent } from '@iwentsourcing/core/storage/declare-event.js';
import { declareState } from '@iwentsourcing/core/storage/declare-state.js';
import { defineState } from '@iwentsourcing/core/storage/define-state.js';
import { defineEvents } from '@iwentsourcing/core/stream/define-events.js';
import { defineStream } from '@iwentsourcing/core/stream/define-stream.js';
import { boolean } from '@iwentsourcing/core/typing/boolean.js';
import { date } from '@iwentsourcing/core/typing/date.js';
import { string } from '@iwentsourcing/core/typing/string.js';
import { todoRealm } from './realm.js';

// Events are the facts, the only thing that is ever stored.
export const CreateTodo = declareEvent('create-todo', { title: string() });
export const CompleteTodo = declareEvent('complete-todo', { id: string() });

// State is derived from the events and can be rebuilt by replaying them.
export const Todo = declareState(
  'todos',
  {
    id: string(),
    title: string(),
    completed: boolean(),
    createdAt: date(),
  },
  ['id'] as const,
).index('date', ['createdAt']);

export const todoStream = defineStream(todoRealm, {
  pattern: 'personal-$(auth.sub)', // one stream per signed-in user
  events: defineEvents([CreateTodo, CompleteTodo]),
  state: defineState([Todo]),
  outputs: {},
  auth: { allowAnonymous: false },
  handle: {
    'create-todo': async (evt, ctx) => {
      await ctx.state('todos').insert({
        id: ctx.metadata.id,
        title: evt.title,
        completed: false,
        createdAt: new Date(),
      });
    },
    'complete-todo': async (evt, ctx) => {
      await ctx.state('todos').patch({ id: evt.id, completed: true });
    },
  },
});

The pattern decides which events belong together. $(auth.sub) resolves to the signed-in user, so every user gets a stream of their own with their own events and state. See Concepts.

The CLI reads one entry file that exports everything to deploy:

ts
// src/export.ts
export { todoRealm } from './realm.js';
export { todoStream } from './todo.js';

3 · Run it locally ​

bash
npx aion serve src/export.ts

This starts the platform on http://localhost:3333 with everything in memory, and watches your sources. Leave it running.

The server has no accounts yet. In a second terminal, point the CLI at it, sign up as a developer, create a tenant and deploy your definitions:

bash
export IWENTSOURCING_HOST=http://localhost:3333
export IWENTSOURCING_TENANT=dev

npx aion register iwentsourcing --username dev --password dev
npx aion tenant create dev
npx aion upload src/export.ts

A tenant is the space your realms live in. The developer login belongs to the platform's directory, not to a tenant, so it works for every tenant you create.

serve keeps everything in memory, so after a restart you run these three commands again. To keep data between restarts, start it with --storage pointing at a Postgres database.

4 · Use it from a script ​

The users of your realm are separate from the developer. A client signs one in, pushes events and reads the state back:

ts
// src/client.ts
import { createRemoteManagement } from '@iwentsourcing/client/management/create-remote-management.js';
import { createRemoteStream } from '@iwentsourcing/client/management/remote-stream.js';
import { createOAuthStorage } from '@iwentsourcing/client/oauth/oauth-storage.js';
import { createMemorySessionStorage } from '@iwentsourcing/client/auth/create-memory-session-storage.js';
import { resolvedLazy } from '@iwentsourcing/core/lazy/resolved-lazy.js';
import { createMemoryLock } from '@iwentsourcing/core/lock/create-memory-lock.js';
import { createNodeEnv } from '@iwentsourcing/core/node/create-node-env.js';
import { createConsoleTelemetry } from '@iwentsourcing/core/tracer/create-console-telemetry.js';
import { todoRealm } from './realm.js';
import { todoStream } from './todo.js';

const signal = new AbortController().signal;

const remote = createRemoteManagement({
  url: process.env.IWENTSOURCING_HOST ?? 'http://localhost:3333',
  tenant: process.env.IWENTSOURCING_TENANT ?? 'dev',
  env: createNodeEnv(),
  signal,
  telemetry: createConsoleTelemetry(),
  // Only the provider names and types go to the client, never the secret.
  session: createOAuthStorage<typeof todoRealm.providers>(
    todoRealm.name,
    resolvedLazy({ custom: { type: 'jwt' } }),
    {
      sessionStorageFactory: createMemorySessionStorage,
      transferStorageFactory: createMemorySessionStorage,
      lock: createMemoryLock(),
    },
  ),
});

await remote.session.register('custom', 'ada', 'lovelace-secret', signal);

// The stream of the signed-in user, resolved from its pattern.
const todos = remote.getStream(createRemoteStream(todoStream));

await todos.push(
  'create-todo',
  { title: 'Learn iwentsourcing' },
  { signal, await: true },
);

// range streams the rows of the state
for await (const row of todos.snapshot('todos').range(null, { signal })) {
  console.log(row.data.title);
}
process.exit(0);
bash
npx tsx src/client.ts
# Learn iwentsourcing

In a browser, use createBrowserEnv and createLocalSession from @iwentsourcing/browser in place of the Node env and the memory storage, so the login survives a reload. The browser package can also run a stream locally in IndexedDB and sync it to the server, so an app keeps working offline.

Live updates ​

observeRange emits the current rows and again on every change, so a UI never polls:

ts
for await (const { items } of todos
  .observe('todos')
  .index('date')
  .observeRange(null, { take: 10, dir: 'prev', signal })) {
  console.log(items.map((row) => row.data.title));
  // emits again after every insert, patch or delete
}

5 · Look at what happened ​

Everything the client did is in the event log, and the CLI reads it. Sign in as the user and look around:

bash
npx aion login custom --realm todo --username ada --password lovelace-secret

npx aion stream list --realm todo
npx aion stream events todo 'personal-$(auth.sub)' personal-ada
npx aion stream state todo 'personal-$(auth.sub)' personal-ada todos

The CLI guide goes through each command, and Use it with AI agents gives an agent the same view.

Next steps ​