Understand

Try It

Scaffold an app, see the files, add GET and POST /users, save a row — then email and the rest of the model if you want.

Scaffold a backend. See which file is GET /health. Add a users routes file. Save a row.

Console on 6533 is derived from that code. API is 6530. Stop after the first working POST if you want — keep reading for email, then the rest of the model.

The one rule

Every URL is a Flow: on(trigger, flow({ do })). Talk to the database, mail, and clock only through fx (the second argument to do). In a many-routes file you write the path. In a one-route file you can omit it.

Create

Your app runs on the host. Postgres, Redis, and mail run in Docker so local is the same shape as production — protocol drivers, not a laptop-only stack.

Why Bun and Docker

OKE is Bun ≥ 1.4.2 (native SQL, Redis, S3, streams) — install. Docker runs Postgres / Redis / mail so local matches production; your app stays on the host.

bun --version   # 1.4.2 or newer
docker info     # engine running

Scaffold and run

bunx create-oke@latest my-app
cd my-app
bun run dev

Default is -t blank. -t shorter is a finished URL shortener to read later — not this walkthrough.

Call health

curl -X GET http://localhost:6530/health -H "accept: application/json"
{ "data": { "ok": true }, "error": null } 

Every call returns { data, error } — see What comes back. The typed client uses the same envelope.

Open Console at 6533 and claim it with the code in the terminal. Health is listed because the file exists, not because you registered a dashboard.

The files

OKE does not ship one folder layout. Roles matter: Flow is behavior, Store is data at rest, root is how the process boots. Names below are common — not a law.

RoleMeaningOften lives at
Root configDrivers and Docker images for dev / test / prodoke.config.ts
Bootoke({ name }) — the processsrc/app.ts
FlowBehavior: a URL, a job, a worker. A folder is a router; a file is a route (or several)src/flows/<router>/
StoreTables and other data at rest. db.declare in config points heresrc/db/schema.ts or src/db/schema/
VaultSecret and config names — not valuessrc/vault.ts or src/core/vault.ts
WiringImported before oke() so store, mail, gates existsrc/core.ts or src/core/
GeneratedCatalog of Flows; SQL emit from your tables. Do not hand-editsrc/flows/index.ts, src/db/drizzle/
TestscreateTestApp — deterministic driverstests/

The blank starter is one arrangement of those roles (main/health.ts is GET /health). Shorter splits core/ and uses one file per verb. Both are OKE.

Write the path in a many-routes file

One file, one URL can omit the path. Next you put GET and POST in one file, so you write "/users" yourself. Pathless HTTP there fails OKE1040.

First HTTP

You add a users router. This walkthrough uses src/flows/users/ — a folder name you choose, not a required path.

src/flows/users/
  index.ts      # GET + POST /users
  shapes.ts     # optional — shared Zod

Do not add users/route.ts next to this index.ts. Do not omit "/users". oke dev rewrites src/flows/index.ts when the folder appears.

Contracts

in is the JSON you send. out is what do returns — that value is data in the envelope. List is UserOut[]; create is one UserOut.

src/flows/users/index.ts
import { z } from "zod";

export const CreateIn = z.object({
  email: z.string().email(),
  name: z.string().min(1),
});

export const UserOut = z.object({
  email: z.string().email(),
  name: z.string(),
});

Routes

Each export is one Flow. CreateIn / UserOut come from the Contracts step.

.public()

Every HTTP trigger needs .public() or .gate(...). Omit both and boot fails (GateBootError). .public() means anyone may call — no session. GET /health already uses it. .gate(member) comes later when a route needs a signed-in user (Gate).

src/flows/users/index.ts
import { on, flow, http } from "okengine/http";
import { z } from "zod";

export const list = on(
  http.get("/users", { out: z.array(UserOut) }).public(),
  flow("users.list", {
    do: () => [],
  }),
);

export const create = on(
  http.post("/users", { in: CreateIn, out: UserOut }).public(),
  flow("users.create", {
    do: async (input) => input,
  }),
);

What comes back

Every HTTP Flow returns { data, error } (optional meta). You return a value from do; the kernel wraps it. Failures are values — not thrown.

FieldSuccessFailure
dataout — what do returnednull
errornull{ code, message?, data? }
Status200 (fx.json.create → 201)422 if in fails; fx.fail.notFound → 404; domain fx.fail codes → 400

Bad in never runs do:

{
  "data": null,
  "error": {
    "code": "ValidationError", 
    "message": "The request failed validation."
  }
}

On the client, branch on error first:

import { createClient } from "okengine/client";
import { app } from "@/app";

const api = createClient(app, "http://localhost:6530"); 
const { data, error } = await api.users.create({
  email: "you@localhost",
  name: "You",
});
if (error) {
  // error.code — ValidationError, or a code you declared with fx.fail
  return;
}
data.email; 

Full table: HTTP · Response Envelopes.

Call both

curl -X GET http://localhost:6530/users -H "accept: application/json"

do returned [], so data is an empty array:

{ "data": [], "error": null } 
curl -X POST http://localhost:6530/users \
  -H "content-type: application/json" \
  -d '{"email":"you@localhost","name":"You"}'

do returned the body, so data is one UserOut:

{
  "data": { "email": "you@localhost", "name": "You" }, 
  "error": null
}

First Store

src/db/schema.ts was empty. src/core.ts already has store.sql("app", { schema }) — do not move it.

src/db/schema.ts     # you fill this
src/core.ts          # db is already here
src/flows/users/index.ts

Declare the table

src/db/schema.ts
import { store, field } from "okengine";

export const users = store.schema.table("users", {
  id: field.id().primaryKey(),
  email: field.text().notNull(),
  name: field.text().notNull(),
  createdAt: field.timestamp().notNull().now(),
});

oke dev pushes schema. Identity and time go through fx — fx.id(), not a hand-rolled uuid.

Read and write in the routes file

Widen UserOut with id and createdAt — same file as the other contracts (index.ts or shapes.ts):

export const UserOut = z.object({
  id: z.string(), 
  email: z.string().email(),
  name: z.string(),
  createdAt: z.iso.datetime(), 
});
src/flows/users/index.ts
import { db } from "@/core"; 
import { users } from "@/db/schema"; 

export const list = on(
  http.get("/users", { out: z.array(UserOut) }).public(),
  flow("users.list", {
    do: async (_input, fx) => {
      return await fx.store(db).page(users, {
        orderBy: [users.createdAt],
        limit: 20,
      });
    },
  }),
);

export const create = on(
  http.post("/users", { in: CreateIn, out: UserOut }).public(),
  flow("users.create", {
    do: async (input, fx) => {
      const [row] = await fx
        .store(db)
        .insert(users)
        .values({ id: fx.id(), email: input.email, name: input.name })
        .returning();
      return fx.json.create(row);
    },
  }),
);

fx.json.create is 201. Declared out projects the row — extra columns strip; timestamps become ISO-8601.

Call it and test

curl -X POST http://localhost:6530/users \
  -H "content-type: application/json" \
  -d '{"email":"you@localhost","name":"You"}'

201 — data is the projected row (id + ISO createdAt):

{
  "data": {
    "id": "…", 
    "email": "you@localhost",
    "name": "You",
    "createdAt": "2026-09-15T14:44:00.000Z"
  },
  "error": null
}
tests/users.test.ts
import { afterAll, beforeAll, expect, test } from "bun:test";
import { createTestApp, type TestApp } from "okengine/test";
import { app, type App } from "@/app";

let t: TestApp<App>;

beforeAll(async () => {
  t = await createTestApp(app);
});

afterAll(async () => {
  await t.close();
});

test("creates a user", async () => {
  const { data, error } = await t.api.users.create({
    email: "you@localhost",
    name: "You",
  });
  expect(error).toBeNull();
  expect(data?.email).toBe("you@localhost");
});
bun test

createTestApp swaps every driver behind fx for a deterministic one. It stamps Manifest tokens. Inline flows that are not an app pass capability: "open".

You can stop here

This is a working OKE app: files under src/flows/ are the API, fx is the door, Console lists what you wrote. What follows is email off the request path, then optional model.

First Signal

The POST should return the user before welcome-mail work runs. signal.once is a competing queue: one worker claims each message.

src/signals/users.ts              # declare — not a URL
src/flows/users/index.ts          # emit after insert
src/flows/workers/welcome.ts      # bind worker

Keep the worker in its own unit. A Flow file next to users/index.ts is a generate error (mixes a barrel index.ts with tree route files).

Declare

Physics live on the Signal. The worker inherits this payload type — not flow.in.

src/signals/users.ts
import { signal } from "okengine";
import { z } from "zod";

export const userRegistered = signal.once("users.registered", {
  schema: z.object({
    id: z.string(),
    email: z.string().email(),
    name: z.string(),
  }),
  retries: 3,
  deadLetter: true,
});

Bind the worker

The worker is a Flow that is not a route. Name it — nameless flow({ do }) here is OKE1072. once binds one worker; next section edits this do, it does not add a second on.

src/flows/workers/welcome.ts
import { on, flow } from "okengine";
import { userRegistered } from "@/signals/users";

export const welcome = on(
  userRegistered,
  flow("workers.welcome", {
    do: async () => {},
  }),
);

Emit after insert

In create, after the insert. { key: row.id } is one job per user — retries stay ordered; different ids run in parallel.

src/flows/users/index.ts
import { userRegistered } from "@/signals/users"; 

export const create = on(
  http.post("/users", { in: CreateIn, out: UserOut }).public(),
  flow("users.create", {
    do: async (input, fx) => {
      const [row] = await fx
        .store(db)
        .insert(users)
        .values({ id: fx.id(), email: input.email, name: input.name })
        .returning();
      if (!row) return; 
      await fx.emit(
        userRegistered,
        { id: row.id, email: row.email, name: row.name },
        { key: row.id },
      );
      return fx.json.create(row);
    },
  }),
);

POST /users again — 201 is the same envelope. The worker runs after that response.

First Channel

Mailpit is already in the blank images. Add a template, import it from core.ts (that file is already loaded before oke()).

src/email.ts                     # you add this
src/core.ts                      # re-export
src/flows/workers/welcome.ts     # worker calls fx.send

Template

src/email.ts
import { channel } from "okengine";
import { z } from "zod";

const mail = channel.email({ from: "App <app@localhost>" }); 

export const welcomeMail = mail.template("welcome", {
  description: "Welcome after signup",
  locales: ["en"],
  schema: z.object({ name: z.string() }),
  catalog: {
    en: {
      subject: "Welcome, {{name}}",
      text: "Hi {{name}} — your account is ready.",
    },
  },
});
src/core.ts
export * from "@/email"; 

Send from the worker

src/flows/workers/welcome.ts
import { on, flow } from "okengine";
import { userRegistered } from "@/signals/users";
import { welcomeMail } from "@/core"; 

export const welcome = on(
  userRegistered,
  flow("workers.welcome", {
    do: async (payload, fx) => {
      await fx.send(welcomeMail, {
        to: payload.email,
        data: { name: payload.name },
      });
    },
  }),
);

Open Mailpit at http://127.0.0.1:8025 (MAILPIT_UI_URL in src/vault.ts). POST /users again — the message lands after the HTTP response.

Split files or one mount

Optional. You already have a working routes file. These two shapes omit hand-written paths — never mix them with users/index.ts, and never put list.ts next to route.ts.

Delete users/index.ts. One verb per file. list / create / get do not add /list to the URL.

src/flows/users/
  list.ts        # GET /users
  create.ts      # POST /users
  [id]/get.ts    # GET /users/:id
  shapes.ts
src/flows/users/list.ts
import { on, flow, http } from "okengine/http";

export const list = on(
  http.get().public(), 
  flow({
    do: async (_input, fx) => fx.store(db).page(users, { orderBy: [users.createdAt], limit: 20 }),
  }),
);

Pathless http.get() is correct here. Shorter (-t shorter) is this tree in a real app.

The rest of the model

Same app. One snippet each — not four more labs.

Gate

You already used .public(). Every HTTP trigger needs .public() or .gate(...) — boot lists the gaps:

gate boot failed — 2 trigger(s) missing auth posture (attach a gate or .public()):
  - users.list GET /users
  - users.create POST /users

A signed-in check is a policy on the trigger. Identity is oke({ gate: { auth } }) plus a plugin — Gate · Auth, not this sitting.

src/core.ts
import { gate } from "okengine";

export const member = gate.policy("member", {
  description: "Signed-in user",
  check: ({ auth }) => !!auth.verified,
});
http.get("/users/me").gate(member); 

Clock

Time is an element. Date.now() inside do is a defect. While users/index.ts is still the routes file, put the schedule in that file — do not add expire.ts beside index.ts.

import { clock } from "okengine/http";

export const expire = on(
  clock.every("users.expire", "1h"), 
  flow("users.expire", {
    do: async (_input, fx) => ({ at: fx.clock.now() }), 
  }),
);

fx.clock.now() is epoch-ms. Clock.

Vault

src/vault.ts already lists contracts. Values resolve at boot — not in the file. Read through fx:

import { publicApiUrl } from "@/core";

const origin = await fx.vault.get(publicApiUrl); 

Never log a revealed secret. Vault.

AI

Optional. fx.ask is the same door as fx.store. Needs a key — skip it to finish Try It.

return await fx.ask(triage, { message }); 

oke ai setup and AI.

Troubleshooting

Learn more

  • Routing — when to omit the path, list / create / get filenames
  • Flow — one species; fx is the door
  • Signal — once / broadcast / live
  • Store — SQL, KV, files, search
  • Channel — templates and fx.send
  • Client · Calling — createClient(app, url), { data, error }

Next

On this page