# Kanon — guide for coding agents and developers Kanon hosts a whole app per **project**: a Postgres database, a REST API over its tables, sign-in for the app's users, file storage, server-side functions, realtime channels and the frontend itself, all on one HTTPS address (`https://.`). This file is everything needed to build and ship on it. ## The loop ```bash kanon up # create the project if needed, apply migrations, build, deploy → prints the live URL kanon logs --errors # what failed, straight from the gateway and the database ``` Work in this order: change files → `kanon up` → open the URL → `kanon logs --errors` if something is wrong. ## Project layout ``` kanon.json { "project": "my-app" } written by `kanon up` / `kanon link` kanon/migrations/*.sql database changes, applied once each, in filename order functions/*.js|ts server-side functions, one per file, deployed by `kanon up` server/ optional: your own HTTP server (Express, Hono, …), run at /api/* src/, index.html the frontend (any static build: Vite, Astro, plain HTML) .env.development.local written by `kanon env` for local dev only; never commit it ``` ## Database rules (read these before writing SQL) 1. Change the database only by adding a new file in `kanon/migrations/` (`0002_add_notes.sql`, …). Never edit a migration that was already applied. 2. A new table is **invisible to the app** until it is granted. Signed-in users act as the role `authenticated`; visitors without an account as `anon`. 3. Every table the app touches needs row-level security. The pattern for "each user sees only their own rows": ```sql create table public.notes ( id bigint generated always as identity primary key, owner uuid not null default auth.uid(), -- the signed-in user's id body text not null, created_at timestamptz not null default now() ); alter table public.notes enable row level security; create policy "own rows" on public.notes for all to authenticated using (owner = auth.uid()) with check (owner = auth.uid()); grant select, insert, update, delete on public.notes to authenticated; ``` 4. For data everyone may read (a public catalogue): `grant select … to anon, authenticated` plus a policy `for select using (true)`. Never grant insert/update/delete to `anon`. 5. `auth.uid()` is the current user's id; users live in `auth.users` (do not modify that schema). 6. Do not put secrets in the frontend. Anything that needs a private API key belongs in a function (see "Functions"). ## The client (`@kanon/client`) Zero dependencies. Every call resolves to `{ data, error }`; it does not throw. ```js import { createClient } from "@kanon/client"; const kanon = createClient({ url: import.meta.env.VITE_KANON_URL, // unset in production: the page's own address is used key: import.meta.env.VITE_KANON_KEY, // unset in production: discovered automatically }); // Sign-in await kanon.auth.signUp({ email, password }); await kanon.auth.signIn({ email, password }); await kanon.auth.signOut(); kanon.auth.user; // { id, email } | null kanon.auth.onChange((user) => { /* runs now and on every sign-in/out */ }); // Tables — requests run as the signed-in user; row-level security filters the rows const { data, error } = await kanon.from("notes").select("id, body").order("id", { ascending: false }).limit(20); await kanon.from("notes").insert({ body: "hello" }); const { data: row } = await kanon.from("notes").insert({ body: "hi" }).select().single(); await kanon.from("notes").update({ body: "edited" }).eq("id", 3); await kanon.from("notes").delete().eq("id", 3); // Postgres functions const { data: total } = await kanon.rpc("my_function", { arg: 1 }); ``` Filters: `eq neq gt gte lt lte like ilike in is`. Shape: `order limit range single maybeSingle`. Together with the three sections below that is the whole API; do not call methods that are not listed here. `update()` and `delete()` without a filter are refused. Always check `error` and show `error.message` to the user. Without a build step, a hosted page can use the client directly: ```html ``` ## Files (`kanon.storage`) Create a bucket once: `kanon storage create avatars` (public: anyone with the link can read) or `kanon storage create documents --private` (only the uploader can read). Signed-in users upload; only the uploader can replace or delete. ```js const { data, error } = await kanon.storage.from("avatars").upload(`${kanon.auth.user.id}/me.png`, file); img.src = kanon.storage.from("avatars").publicUrl(`${userId}/me.png`); // public bucket const { data: blob } = await kanon.storage.from("documents").download("contract.pdf"); const { data: link } = await kanon.storage.from("documents").createSignedUrl("contract.pdf", 3600); // link.url const { data: files } = await kanon.storage.from("documents").list("folder"); // [{ name, size, type } | { name, folder: true }] await kanon.storage.from("avatars").remove("me.png"); ``` Limits: 25 MB per file. Put the user's id in the path when each user has their own files. Uploaded HTML/SVG/JS is always served as a download, never rendered. ## Functions (`functions/*.js`) Server-side code: one file per function, `export default` an async function. It receives a standard `Request` and returns an object (sent as JSON), a string, or a `Response`. Deployed by `kanon up`; reachable by anyone at `/functions/v1/`, so check `ctx.user` when it is for signed-in users. ```js // functions/summarize.js export default async function (request, ctx) { if (!ctx.user) return new Response("Sign in first", { status: 401 }); const { text } = await request.json(); const r = await fetch("https://api.example.com/v1/summarize", { method: "POST", headers: { authorization: `Bearer ${ctx.env.EXAMPLE_API_KEY}`, "content-type": "application/json" }, body: JSON.stringify({ text }), }); return { summary: (await r.json()).summary, for: ctx.user.email }; } ``` ```js const { data, error } = await kanon.functions.invoke("summarize", { body: { text } }); ``` - `ctx.user` — `{ id, email }` of the signed-in caller, or `null`. - `ctx.env` — the project's secrets (`kanon secrets set EXAMPLE_API_KEY=…`), plus `KANON_URL`, `KANON_ANON_KEY` and `KANON_SERVICE_KEY`. With the service key a function can read and write any row, bypassing row-level security: `fetch(ctx.env.KANON_URL + "/rest/v1/orders", { headers: { apikey: ctx.env.KANON_SERVICE_KEY, authorization: "Bearer " + ctx.env.KANON_SERVICE_KEY } })`. - Functions run on **Deno** in a sandbox: TypeScript, `fetch`, Web APIs and Node built-ins (`node:crypto`, `node:buffer`, …) are all available. - Packages, two ways: `import Stripe from "npm:stripe"` (nothing to install; fetched on the server at first use), or `npm install stripe` in the app folder and `import Stripe from "stripe"` (the CLI bundles it at deploy). Relative imports work; put shared code in `functions/_shared/`. - Packages with compiled native code (sharp, bcrypt, canvas, better-sqlite3) do not work: use a pure-JavaScript package or the service's HTTP API. - A function is `functions/.js|ts` or `functions//index.js|ts`. Names starting with `_` are not deployed. Limit: 10 MB after bundling. - Secrets are in `ctx.env.NAME` and also in `Deno.env.get("NAME")` / `process.env.NAME`, so SDKs that read the environment just work. - A function can use the network, read its own code and write to `/tmp`. It cannot read other files, start programs, or load native libraries. - The module stays loaded between calls for a few minutes: create SDK clients at the top of the file, but never keep one user's data in a module variable. - A call may run 30 seconds. `console.log` goes to `kanon logs --service functions`. - The first deploy of a project's first function takes up to a minute: that is when its backend starts. - Webhooks: point the other service at `https:///functions/v1/` and verify its signature inside the function. ## Your own server (`server/`) For anything a function cannot be — a long-running process, WebSockets, background timers, an existing Express/Fastify/Hono app — put an HTTP server in `server/`. `kanon up` uploads the source and runs it; it is reachable at `https:///api/…` (your server receives the path unchanged, including `/api`). ```js // server/server.js (server/package.json lists express under "dependencies") const express = require("express"); const app = express(); app.use(express.json()); app.get("/api/health", (req, res) => res.json({ ok: true })); app.listen(process.env.PORT, "0.0.0.0"); // PORT is given; always listen on it ``` - The entry file is `main` in `package.json`, else `main.ts`, `index.js`, `server.js`, … Deploy alone with `kanon server deploy`; check with `kanon server status`. - It runs on Deno, which runs most Node servers unchanged (CommonJS or ES modules, TypeScript without a build step). Packages are installed from `package.json` on the server; do not upload `node_modules`. Packages with compiled native code may not work. - One server per project. Secrets are environment variables (`process.env.NAME`), as are `KANON_URL`, `KANON_ANON_KEY`, `KANON_SERVICE_KEY`. - Who is calling: pass the user's token on and ask the project, `fetch(process.env.KANON_URL + "/auth/v1/user", { headers: { apikey: process.env.KANON_ANON_KEY, authorization: req.headers.authorization } })`. - It can use the network, read its own folder and write to it and `/tmp`; files do not survive a restart: keep data in the database or in storage. - A crash restarts it automatically; output and errors are in `kanon logs --service functions`. ## Realtime (`kanon.channel`) ```js // Messages and who-is-here, between everyone subscribed to the same channel name const room = kanon.channel("room:42") .on("broadcast", ({ event, payload }) => { /* a message from someone else */ }) .on("presence", ({ members }) => { /* [{ id, user, state }] currently here */ }) .subscribe({ presence: { name: "Ada" } }); room.send("chat", { text: "hi" }); // to everyone else on the channel room.unsubscribe(); // Database changes: turn the table on once with `kanon realtime enable notes` const stop = kanon.onTableChange("notes", ({ type, id }) => loadNotes()); // type: INSERT | UPDATE | DELETE ``` A table change arrives as a signal (which row changed), not the row: reload the data with `kanon.from(...)`, so row-level security still decides what each user sees. Anyone holding the public key can join a channel by name, so never broadcast private data; use channels for cursors, typing indicators, "new message" pings. The table needs a column named `id` for the signal to carry it. ## Commands | Command | Does | |---|---| | `kanon login` | Save an access token (create one in the console → Access tokens) | | `kanon init [dir]` | Scaffold a starter app (Vite, sign-in, one protected table) | | `kanon up [name]` | Create/link the project, apply migrations, build, deploy | | `kanon db push` | Apply new files from `kanon/migrations/` | | `kanon sql ""` / `kanon sql -f file.sql` | Run SQL and print rows as JSON | | `kanon deploy [dir]` | Build (if there is a build script) and publish the site | | `kanon functions deploy [file]` | Bundle and deploy functions (default: everything in `functions/`); also `list`, `delete ` | | `kanon server deploy [dir]` | Upload and run your own server (default `server/`); also `status`, `delete` | | `kanon secrets set NAME=value` | Keys for functions and the server; also `list`, `unset NAME` | | `kanon storage create [--private]` | A bucket for uploads; also `list`, `delete ` | | `kanon realtime enable ` | Announce a table's changes; also `list`, `disable
` | | `kanon env` | Write `.env.development.local` for local development | | `kanon status` | Project address, tables with their access rules, traffic, site | | `kanon logs [--errors] [--service rest\|auth\|db\|site\|functions]` | Recent requests or service log lines | | `kanon projects` / `kanon link ` | List projects / point this folder at one | | `kanon mcp [--read-only]` | Run as an MCP server for coding agents | ## When something fails - `Not allowed on "
"` → missing `grant`, missing policy, or the user is signed out. - `There is no table "
" in the API` → migration not applied (`kanon db push`), or wrong name. - Sign-in returns 400 → wrong email or password. Sign-up needs a password of at least 6 characters. - A page shows the old version → `kanon deploy` again; each deploy replaces the site at once. - Upload fails with "Sign in before uploading" → the user is signed out; with "There is no bucket" → `kanon storage create `. - Deploy says `imports "x", which is not installed` → `npm install x` in the app folder. - A function answers 500 → its error message is in the response and in `kanon logs --service functions`; 504 → it ran over 30 seconds; 503 right after the first deploy → the backend is still starting. - `onTableChange` never fires → `kanon realtime enable
`. - Anything else → `kanon logs --errors`, then `kanon logs --service db`.