Functions (your own server code)
Everything you could do with your own server and your own database, you can do on KUMODeck. Functions runs server code you write, with a private SQL database, key-value store, file storage, queues, Durable Objects (live state in one place: match rooms, chats, live feeds) and scheduled jobs for each environment. You never create a cloud account, paste resource IDs or manage servers.
The ready-made building blocks (sign-in, saves, …) are tools your code can call. They don't limit what you can build: write your own API, business or match logic, webhooks from other services, calls to any third-party API.
Your database or saves? ("save it in a DB" can mean either.) Pick by who may change the data:
Protect in D1, not in saves. Anything a user must not be able to change themselves — scores and rankings, coins, credits, items, purchases, badges, anything shared between users — goes in the project's own Functions + D1. saves holds only what the user may freely write (settings, drafts, a solo game's progress).
| Put it in | What | Who writes it |
|---|---|---|
| Your database (D1, here) | what must be protected: scores and rankings, coins, credits, items, purchases, a verified badge, anything shared between users | only your server code |
| Saves | what the user may change freely: settings, progress notes, drafts, favorites, a game's save | the user's browser (a changed value hurts nobody) |
When unsure: if a user changing it by hand would be a problem, keep it here. Your code cannot read or write a user's saves, so keep the protected copy in your database from the start.
Off by default. Nothing runs and nothing is billed until you turn Functions on for an environment. You pay only what it uses, at cost, from your prepaid balance (see Pricing).
Start from the template#
cp -r templates/functions-starter/functions ./functions && cd functions
npm install
# put your development secret key (sk_dev_…) in it
cp .dev.vars.example .dev.vars
npx wrangler d1 migrations apply DB --local
# = npx wrangler dev → http://localhost:8787/health
kumodeck functions devkumodeck functions dev runs everything locally (database, KV, files and Durable Objects included) and does not touch
KUMODeck. When it works, ship it from the folder that has kumo.json:
# needs prepaid credit
kumodeck functions enable
# bundles with your local wrangler, uploads, creates the empty database DB
kumodeck functions deploy
# create the tables: apply migrations/ to this environment's own database
kumodeck functions db migrate DB
curl https://<slug>--dev.functions.example.net/health
# URL, version, databases, secrets, crons, limits
kumodeck functions statusThe first deploy creates the database, so migrate after it: the deploy says which databases are new and prints the
db migrate line to run (in --json: newDatabases and next; in a terminal it offers to run it for you). Until you
migrate, the tables do not exist and the first call fails with no such table. db migrate reads the folder from
migrations_dir of that database in wrangler.jsonc (default migrations), and skips migrations already applied (the same
d1_migrations table as wrangler). kumodeck db migrate DB and kumodeck db query DB "SELECT …" are short for the same commands.
Every command takes --env development|production (default: development). Your code is served at:
| Environment | URL |
|---|---|
| production | https://<slug>.functions.example.net/ |
| development | https://<slug>--dev.functions.example.net/ |
These URLs and every response carry your app's name only — your users (called players in the API) never see KUMODeck.
What you can use#
Write a normal wrangler.jsonc. KUMODeck reads only the binding names and gives each environment its own
resources, so the same file works locally and on KUMODeck.
In wrangler.jsonc | What you get | Notes |
|---|---|---|
d1_databases | a private SQLite database per environment | 10 GB per database; add more bindings to shard. Tables and SQL are up to you |
kv_namespaces | a private key-value store | |
r2_buckets | private file storage | |
queues.producers | a private queue you can send to | consuming messages in your own code is not available yet |
durable_objects + migrations | live state in one place: match rooms that check moves, chats, live feeds (SQLite storage, WebSockets) | new_sqlite_classes only; a deploy that removes a class (and its data) is refused (durable_object_removed 409); up to 100 bindings |
triggers.crons | scheduled runs (UTC, 5-field cron) | on KUMODeck they arrive as a request with props.kumo.event = "scheduled" (the template handles both) |
vars | plain settings | |
the dashboard or kumodeck functions secret put NAME | API keys and passwords (secrets) | the value goes straight to the runtime; KUMODeck stores only the name (how to enter them) |
Not available: service bindings to other workers, Hyperdrive, Workers AI / Vectorize / Browser Rendering (no per-project
cost metering for them yet). Reach any outside service with fetch(); raw TCP sockets are blocked.
Durable Objects#
One Durable Object is one small server with its own storage that everyone reaches by the same name: one per match, chat
channel or feed. Verify the user in your Worker (players.verify) before you pass the request on, and use the
hibernation API (ctx.acceptWebSocket) so a quiet room costs nothing while it waits. The functions-d1 Skill has a
match room you can copy.
- Cost, at cost from your prepaid balance: requests $0.165 per million (20 messages sent to it = 1 request; messages it sends are free), running time $13.75 per million GB-seconds (one object = 0.128 GB; asleep = free), rows read / written $0.0011 / $1.10 per million, data kept $0.22 per GB a month (see Pricing). A 10-minute match of 4 players sending 1 move a second, saved once per move: about $0.0055.
- Limits from Cloudflare: about 1,000 requests a second and 10 GB of storage per object, 2 MB per stored value, 32,768 WebSockets per object (Limits). Your Functions' CPU limit (
kumodeck functions limits --cpu-ms) applies to Durable Objects too, and so does the limit that follows your prepaid balance. - Calls to other services go from your Worker, not from a Durable Object. Make the
fetch()in your Worker's handler and pass the result in. A deploy whose code opens raw TCP connections (cloudflare:sockets,node:net,node:tls) is refused (400 invalid_request). Calls from Durable Objects to other services are counted every hour, and a flood of them pauses your Functions (functions_suspended).
API keys and passwords#
Enter keys for other services, such as Stripe or OpenAI, in the dashboard: Functions → API keys and passwords (add,
replace, delete). The value goes into a password field, leaves the screen once sent and is never shown again. In
production you confirm on the spot before it is saved or deleted. Your code reads it as env.NAME.
Do not paste keys into your conversation with your AI. Conversations are kept as records. When you ask your AI assistant, the MCP tool
functions_secret_set returns a direct link to that screen: enter it there (your AI only gets the name). In your own
terminal, kumodeck functions secret put NAME works too (the value is read from a hidden prompt). If you pasted one
anyway, make a new key at that service and enter the new one on that screen.
Call KUMODeck from your code#
When you enable Functions, KUMODeck issues a secret key for that environment and passes it to your code as
KUMO_SECRET_KEY (with KUMO_API_URL). The template's src/kumo.ts is a tiny client for it:
const player = await new Kumo(this.env).players.verify(request.headers.get('authorization'));
if (!player || player.banned) return new Response('sign in first', { status: 401 });Your app sends the user's token with its request:
await fetch(`${FUNCTIONS_URL}/scores`, {
method: 'POST',
headers: { 'content-type': 'application/json', authorization: `Bearer ${await kumo.auth.getAccessToken()}` },
body: JSON.stringify({ score })
});players.verify calls POST /v1/admin/players/verify-token and only accepts users of the same environment. Any other
secret-key API (config, share stats, …) works the same way as from your own server.
Caught a cheat or an abuser? Ban the user right there: players.ban(player.id, { reason, durationHours }) (leave out
durationHours to ban until you lift it) and players.unban(playerId). It is the same ban as the dashboard's
(Banning players).
Calling from a browser (CORS)#
Your pages call the Functions from the browser with a signed-in user's token, so the template does not answer every site
("*"). It allows:
- your own site — KUMODeck passes your code
KUMO_ALLOWED_ORIGINS: the environment's site address, your verified custom domains and theweb.allowedOriginsofkumo.config.json. When one of those changes, KUMODeck updates it without a redeploy. If it could not,kumodeck functions statussays browser access is out of date — runkumodeck functions deployagain. The shared/play/…address is never included (every project's pages run on it). The whole list fits in 5 KB (a limit of the hosting provider): ifweb.allowedOriginsis longer, the sites at the end are left out andkumodeck config pushnames them in a warning — remove ones you no longer use or cover them with a wildcard - sites you list in
ALLOWED_ORIGINSinwrangler.jsoncvars(comma-separated, then deploy).https://*.example.comallows the subdomains of example.com, not example.com itself;"*"allows any site (not recommended) - localhost outside production (your dev server)
kumodeck functions status and kumodeck functions deploy show the sites KUMODeck set. A version deployed by an older CLI may still
allow the shared /play/ address; status says so, and deploying again removes it.
Your own domain#
Serve your Functions on your own domain: kumodeck functions domains add api.<your domain> (add --env production for the
live one). Add both DNS records it prints (a CNAME and a TXT _kumo-verify.<host>) where you manage the domain; keep the
TXT after it is live. Check with kumodeck functions domains status <host>, remove with kumodeck functions domains remove <host>.
Functions must be enabled in that environment. Using your domain on KUMODeck costs $0.11 a month per domain (the
certificate and serving on it), taken from your prepaid balance by the day. You still pay for the domain itself where you bought it.
kumodeck functions domains add api.example.com --env production
kumodeck functions domains status api.example.com --env productionLogs#
When a deployed function or page misbehaves, read what your code printed with console.log / console.warn / console.error.
One command reads your Functions and your server-rendered app together, mixed by time
(kumodeck logs is the same as kumodeck functions logs):
# the last hour, oldest first, in your local time
kumodeck logs
# up to 7 days back; levels: debug, log, info, warn, error
kumodeck logs --since 2d --level error,warn
# only the server-rendered app (--source functions: only Functions)
kumodeck logs --source app
kumodeck logs --search "score" --env production
# every page as JSON (newest first), for scripts
kumodeck logs --all --jsonEach line shows the time, where it came from (fn = Functions, app = the server-rendered app; source in --json), the level, what ran (fetch for a request, scheduled for a cron, queue) and the message. A
message longer than 64 KB is cut and marked (8 KB once a page has returned 4 MB). --since / --until take 15m, 1h, 2d or a date-time; --limit and
--cursor page through (across both). Your AI agent can read the same with the MCP tool functions_logs (argument source) — it needs the separate
Read server function logs permission (read:logs) on the consent screen (Use from an AI agent).
Locally, kumodeck functions dev prints the same output in your terminal.
What goes into logs is up to you. Logs show only what your own code prints, kept for 7 days and then deleted automatically. Do not log personal data or secrets: emails, passwords, access tokens, API keys, payment details, or anything a user would not want others to see. Anyone who can read this project's logs (you, your CLI keys, and AI agents you allowed to read logs) can see those lines. Log the ID of a user, not their email; log that a call failed and its status, not the token you sent.
Log lines are part of KUMODeck's usage fee, at cost: $0.66 per million lines. If your code prints nothing, they cost
nothing. To keep no logs for a version (for example a very chatty function whose output you never read), deploy it with
kumodeck functions deploy --no-logs (for the app: kumodeck deploy --no-logs); the next deploy without the flag turns them back on.
| Error | Meaning | Next step |
|---|---|---|
functions_disabled | Functions are off in this environment (and no server-rendered app is live) | kumodeck functions enable, or deploy your app with kumodeck deploy |
functions_not_deployed | nothing is deployed yet | kumodeck functions deploy |
logs_disabled | the live version was deployed with --no-logs (or before logs existed) | kumodeck functions deploy; logs start from that deploy |
app_logs_unavailable | the live version of the app was deployed with --no-logs (or before apps had logs) | kumodeck deploy; logs start from that deploy |
app_not_deployed | --source app, but no server-rendered app is live in this environment | kumodeck deploy, or read Functions with --source functions |
rate_limited (429) | too many log reads right now; the limit is shared by everyone on KUMODeck, not just this project | wait details.retryAfter seconds (it can be 300; the CLI says how long), then read once. Do not retry in a loop; narrow with --since / --level / --search |
rate_limit_unavailable (503) | log reads are paused for a moment on the server | wait a few seconds, then read once |
When something fails#
Errors come with a hint (the next step) and, in --json, a machine-readable code:
| Error | Meaning | Next step |
|---|---|---|
d1_query_error (400) | the database rejected your SQL (syntax, missing table or column, constraint); details.error is the database's message | fix the SQL; retrying the same SQL fails the same way |
migration_failed | a migration file failed; details lists what was applied, the failed file and how many later files did not run | fix that file and run kumodeck functions db migrate DB again (applied files are skipped) |
functions_script_error (400) | your code threw while starting (for example at import time); details.error is the exception | reproduce with kumodeck functions dev (npx wrangler dev), fix, deploy again |
d1_binding_not_found | no database with that binding name in this environment (the message lists the ones that exist) | check the name, or deploy first: the first deploy creates the database |
functions_suspended | stopped for this environment; details.reason says why | balance: add credit and it resumes within a minute; otherwise answer the email you got |
Limits, costs and stopping#
# per request (defaults 30 s / 10,000; max 5 min / 10 million)
kumodeck functions limits --cpu-ms 60000 --subrequests 50000# stop serving; code and data are kept
kumodeck functions disable
# remove the code and delete databases, files and queues
kumodeck functions delete --purgeThe limits are the same as Cloudflare's own (Workers Paid): 30 seconds of CPU and 10,000 subrequests per request by default, up to
5 minutes and 10 million. The same command sets the server-rendered app's limits (PUT …/functions/limits with app; see the
REST API).
How much CPU a request can actually use grows with your prepaid balance, because KUMODeck is prepaid and stops only after usage is
counted (a few minutes): about 5 ms per cent of balance, shared by your environments that run code, never less than 5 seconds (for
example $60 → 30 seconds, $600 → 5 minutes for one environment). If you run on the monthly free usage alone, with a prepaid balance of
$0, the ceiling is 50 ms of CPU a request: five times Cloudflare's own free plan (10 ms), and plenty for a normal API (saving a score or
returning JSON takes a few milliseconds). Add any amount of funds and you are back to 5 seconds and up within about a minute; until then
limits.requiredBalance shows 1 (cent). The value you chose is kept and takes effect within a minute of adding
funds. kumodeck functions status --json shows limits.cpuMs (in effect now), limits.requested, limits.cpuMsCap and
limits.requiredBalance. Subrequests do not depend on the balance. A request that goes over its limit is stopped with an exception.
A Worker holds at most 128 variables in total: your vars + secrets + up to 4 that KUMODeck sets (too_many_variables,
details.limit). Crons have no count limit. An environment can have up to 100 databases, 100 buckets, 100 queues and 5 KV namespaces
(KV namespaces are shared by everyone on KUMODeck's Cloudflare account).
Requests, CPU time, database rows and storage are billed as KUMODeck's usage fee, at cost, with no markup, after the $2 of free usage each month. As a rough guide, a small app (1 million requests, 5 ms CPU each, a 100 MB database) costs about $0.66 a month in usage. Prices are at cost, including the tax our providers add. The fixed monthly base fee for running Functions is shared between everyone who uses Functions, in proportion to use, and settled against the actual cost at the end of the month: usage is taken from your balance as it happens, part of it may come back at the end of the month, and nothing is ever taken afterwards. You get an email (and an MCP notice) when your prepaid balance runs low, and you can turn on automatic top-up. If the balance is used up and nothing else covers it (the month's free usage, or an automatic top-up that has not failed), Functions stop answering (503) until funds are added or the free usage comes back on the 1st; your data is kept.
From your AI agent#
Everything above is available as MCP tools (functions_status, functions_enable, functions_deploy,
functions_db_query, …) — see Use from an AI agent. Ask "add a table for daily scores and migrate
development", and the assistant writes the migration, runs it locally, and applies it with your confirmation.
Your data#
What you store in your own database, files or KV is yours to manage — including deleting a user's data when they ask.