Skip to content

Embedded in Node

The memento server is a Fastify plugin before it is a process. Register it in the Fastify app you already run and it serves the whole API under a prefix: push, lists, queries, entity history, the /ws stream and the UDC collections, with its own API keys, its own error handler and its own hooks, none of which leak into your routes. The database is your PostgreSQL, where its tables sit next to yours, or a SQLite file next to the application.

  1. Install the packages from npm, next to Fastify:

    Terminal
    # your app: Fastify, the server plugin, the protocol client and the CLI
    mkdir my-app && cd my-app && npm init -y && npm pkg set type=module
    npm install fastify @jsmemento/core @jsmemento/lookups @jsmemento/server @jsmemento/cli

    @jsmemento/server brings Fastify’s WebSocket, cookie and static plugins, Drizzle and pg (SQLite is Node’s built-in node:sqlite, nothing to install); @jsmemento/cli is the memento command; @jsmemento/core is the protocol and its clients.

  2. The server, next to whatever your app already serves:

    server.ts
    import { connect, LocalBus, mementoPlugin, runMigrations } from "@jsmemento/server";
    import Fastify from "fastify";
    // DATABASE_URL picks the database: file:<path> is one SQLite file, postgresql://… your
    // PostgreSQL, where memento's tables live next to yours, all named memento_*.
    const database = connect(process.env.DATABASE_URL ?? "file:data/app.db");
    await runMigrations(database.db); // on SQLite this creates the file on the first start
    // One process: it publishes the events it stores and streams them to /ws itself.
    // More than one (PostgreSQL only): a RedisPublisher and a RedisFeed, so every process sees every event.
    const bus = new LocalBus();
    const app = Fastify({ logger: true });
    app.get("/", async () => ({ hello: "your own routes stay yours" }));
    await app.register(mementoPlugin, {
    prefix: "/memento",
    db: database.db,
    publisher: bus,
    stream: { feed: bus },
    });
    app.addHook("onClose", async () => {
    await bus.close();
    await database.close();
    });
    for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, () => void app.close());
    await app.listen({ port: Number(process.env.PORT ?? 8000) });
    • DATABASE_URL picks the database: file:<path> for one SQLite file, postgresql://… for PostgreSQL. connect() takes the driver from the URL; the rest of the code is the same for both.
    • runMigrations applies memento’s migrations for that database, which ship inside @jsmemento/server. Run it on every start: what is applied already is skipped, and on SQLite the first start creates the file. Every table is memento_*.
    • LocalBus is both the publisher (where stored events go) and the stream’s feed (where /ws takes them from), in memory. With several processes on PostgreSQL, give each a RedisPublisher and a RedisFeed on the same REDIS_URL: an event stored by one reaches the /ws clients of all of them.
    • The onClose hook closes the bus and the database, so Ctrl-C stops it cleanly.
    • More options: lookups (the vocabulary of lookups.yaml), defaultLocale, udc (your own UDC collections next to memento’s, or false), menu, demoApiKey and accounts (the self-service routes). Their meaning is in the MementoPluginOptions type.
  3. Something to follow the stream with. MementoStream from @jsmemento/core is the client @jsmemento/react and memento tail use: it sends the key as a WebSocket subprotocol, waits for the welcome, and reconnects with backoff:

    tail.ts
    import { MementoStream } from "@jsmemento/core";
    // What happens to user/42 from now on, rendered in Serbian. The key needs the read scope.
    const stream = new MementoStream({
    baseUrl: process.env.MEMENTO_URL ?? "http://localhost:8000/memento",
    apiKey: process.env.MEMENTO_API_KEY ?? "",
    filter: { instance_type: "user", instance_id: "42" },
    locale: "sr",
    onStatus: (status) => console.log(`[${status}]`),
    onEvent: (event) => console.log(event.occurred_at, event.rendered),
    });
    // It reconnects by itself (0.5 s doubling to 15 s) until you close it.
    process.on("SIGINT", () => stream.close());
  4. Run them, with a tenant and a key made by the CLI straight in the database:

    Terminal
    export DATABASE_URL=file:data/app.db # SQLite: one file, no database service
    # export DATABASE_URL=postgresql://jsmemento:change-me@localhost:5432/app # or PostgreSQL
    node server.ts # migrates, then listens on :8000
    # another terminal: a tenant and a key, straight into the same database
    export DATABASE_URL=file:data/app.db
    npx memento create-tenant acme --name "Acme Inc"
    npx memento create-key --tenant acme --scopes read,write --name app
    MEMENTO_API_KEY=mk_… node tail.ts # [live], then one line per event of user/42
    # a third: push one
    curl -X POST localhost:8000/memento/events -H "Authorization: Bearer mk_…" \
    -H 'content-type: application/json' \
    -d '{"event_type":"USER_LOGIN","instance_type":"user","instance_id":42,"actor_id":"igor"}'
    What tail.ts prints
    [live]
    2026-11-16T01:22:55.893Z Korisnik igor se prijavio.

    Node 24 runs the .ts files as they are, stripping the types. npx memento reads the same DATABASE_URL; create-key prints the mk_… secret once, like the Docker page’s.

  5. Your routes and memento’s, side by side, and the database file. This run used SQLite:

    Terminal
    curl -s localhost:8000/; echo
    curl -s localhost:8000/memento/api/health; echo
    ls data
    What it printed
    {"hello":"your own routes stay yours"}
    {"ok":true,"data":{"status":"ok"}}
    app.db
    app.db-shm
    app.db-wal

    app.db-wal and app.db-shm belong to the database while it is open; after Ctrl-C, only app.db remains.

Your application is the one server process the file allows: do not also run dist/server.js on it. memento CLI commands next to it are fine. No Redis is needed: the LocalBus streams what this process stores. A process speaks one database: connect() refuses a PostgreSQL URL while a SQLite handle is open in it, and the other way round. The rest, with a complete application that creates its own tenant and key on the first start, is in the SQLite guide.

Your own route keeps answering at /; memento’s are under the prefix, each with the scope its key needs. The list is the API section of the home page; every parameter is in docs/API.md, the stream’s messages and close codes in docs/STREAMING.md.

  • Draw the events in React: MementoProvider and MementoDataView from @jsmemento/react, the React tab of Start where you are.
  • The standalone server is this plugin too: packages/server/src/server.ts adds the optional Redis, the lookups, the menu and the accounts from environment variables (docs/ARCHITECTURE.md).

v1.1.0released built 663143e