Your app has a backend
The complete guide to backend.js: webhook endpoints, GitHub repository webhooks, change reactions, scheduled jobs, retries and the dead-letter log, per-vibe secrets, outbound fetch, and server-side AI — no server to provision, no key to hold.
Every vibe can ship a third file. App.jsx is what people see, access.js is
who can do what — and backend.js is the part that runs when nobody's
browser is open. It runs on the platform's servers, next to your data, with
four lanes and no infrastructure to provision:
fetch(request, ctx)— your app gets its own HTTP endpoint at/_api/.... Webhooks from the outside world, orfetch("/_api/…")calls from your own UI.onChange(event, ctx)— runs after any document write commits. Derive, aggregate, moderate, fan out.scheduled(event, ctx)— runs on a timer, from every 5 seconds to every hour. Cleanup, digests, token rotation.email(message, ctx)— your app has its own email address. Mail sent to it arrives here, one message at a time.later(event, ctx)— runs once, when a timer you set withctx.latercomes due. Follow-ups, "check back in two days".
Export only what you need. Most apps need no backend.js at all — normal
reads and writes flow through Fireproof directly. Reach for it when something
must happen server-side: accepting a webhook, maintaining a tally users
shouldn't be able to forge, or doing periodic work.
This guide is the narrative tour. The full contract — every field, every cap — is the backend.js reference, the same document the code generator reads. You can also just describe what you want ("a backend that summarizes new entries every night") and the generator wires it for you.
Ship one in five minutes
Pull your app, add a file, push:
shnpx vibes-diy pull you/your-app --dir ./your-app
cd your-app
# create backend.js (below), then:
npx vibes-diy push --vibe you/your-app
js// backend.js — an RSVP endpoint anyone can POST to
export async function fetch(request, ctx) {
const url = new URL(request.url);
if (url.pathname === "/rsvp" && request.method === "POST") {
const body = await request.json();
const id = await ctx.db.put(
{ kind: "rsvp", name: body.name, at: Date.now() },
{ db: "rsvps" }
);
return new Response(JSON.stringify({ ok: true, id }), {
headers: { "content-type": "application/json" },
});
}
return new Response("not found", { status: 404 });
}
The path is rooted after /_api: a request to
https://your-app--you.host/_api/rsvp arrives with pathname /rsvp. From
your own App.jsx, call it relative — fetch("/_api/rsvp", { method: "POST", … }).
From a terminal, npx vibes-diy app call you/your-app /rsvp --body '{"name":"Ada"}'
calls it as you, signed in.
When something goes wrong, the status tells you which kind of wrong it is:
| Response | What it means |
|---|---|
404 backend.js _api: not found |
the app has no fetch handler to run, or it isn't published yet |
500 backend.js threw: TypeError. … |
your handler threw; the full message is in your app's backend log |
502 backend.js failed to run. … |
the module never started — usually an error at the top of backend.js |
The public response names only the kind of error, so nothing in your error
message reaches whoever called the URL. Read the whole message with
npx vibes-diy app logs you/your-app. For failures you expect — an upstream
that can be down, input that can be malformed — catch them in the handler and
answer with your own status and a reason your app can show.
You can also prompt for it in the editor: backend.js is a normal part of the vibe's source, editable in the Code tab like everything else.
Your /_api opens to the world when you publish. Before the first
publish, and after you unpublish, the routes answer your app's own people —
you, your developers, and anyone you shared it with — and everyone else gets
the 404 above without your handler running. Your page reaches its own routes
in every state through apiFetch from use-vibes, which calls as the
signed-in visitor; a script calls as you with your token in
Authorization: Bearer …. onChange and scheduled keep running either way,
and a connected GitHub webhook runs until you unpublish. Apps built in the editor publish as they're
built, and npx vibes-diy push publishes by default, so most apps are
already open.
GitHub webhooks — a connected repository calls your fetch
Besides webhooks you arrange yourself, a vibe can receive a GitHub
repository's events without holding a GitHub secret. The repository is bound
to the vibe when the vibes.diy GitHub App is installed on it with your vibe
named in the install link's state (you/your-app); the install flow lands
back on vibes.diy, where you confirm as the signed-in owner of that vibe. From
then on, every delivery for that repository arrives at your ordinary fetch
handler as a POST to /_api/github-webhook:
jsexport async function fetch(request, ctx) {
const url = new URL(request.url);
if (url.pathname === "/github-webhook" && request.method === "POST") {
const event = request.headers.get("x-vibes-github-event"); // "issues", "push", …
const delivery = request.headers.get("x-vibes-github-delivery"); // GitHub's delivery id
const payload = await request.json(); // GitHub's parsed payload
if (event === "issues" && payload.action === "opened") {
await ctx.db.put(
{ _id: "gh-" + delivery, kind: "issue", title: payload.issue.title },
{ db: "inbox" }
);
}
return new Response(null, { status: 204 });
}
return new Response("not found", { status: 404 });
}
What the platform has already done for you, and what is still yours:
- The signature is verified before you see the request. GitHub's own
x-hub-signature-256is checked against the App's secret and then stripped; you never hold that secret and cannot check it yourself. Everyx-vibes-*header on the request was put there by the platform — inbound headers in that namespace are deleted before the forward — sox-vibes-github-event,x-vibes-github-delivery,x-vibes-github-installation,x-vibes-github-binder(the handle of the person who connected that repo, left off when they have none) andx-vibes-timestampare the platform's word, not the caller's. (x-vibes-signature-256carries a per-vibe provenance signature over those fields; the key to verify it is not yet handed to vibes, so treat it as reserved.) - The body is untrusted text. Issue titles, pull-request descriptions
and commit messages are written by strangers; the request carries
x-vibes-content: untrusted-externalto say so. Store them as data and never feed them toctx.callAIas instructions. - A delivery can arrive more than once. Key what you write by the delivery id, as above, so a redelivery lands on the same document.
- Your status decides the retry. A
2xxacknowledges. A4xxis final: the platform answers GitHub with success and the delivery is not retried, which is also what happens when your backend has no/github-webhookroute at all. A throw, or a5xx, marks the delivery as failed on GitHub's side. GitHub does not retry failed deliveries on its own: the repository owner can redeliver one from the webhook's Recent Deliveries page, so work that must not be lost should also be reachable by ascheduledsweep. - It runs as nobody. GitHub's deliveries carry no sign-in, so
ctx.userInfoisnulland anyctx.db.putmust passaccess.jsfor an anonymous caller — or write a request document and letscheduleddo the privileged part. - It keeps running until you unpublish. A never-published draft receives deliveries; a vibe you have taken down does not, until you publish again.
Bring records in from Zapier
A Zap can hand your app a new record from any tool Zapier reaches — a Google Forms response, a new row in a sheet, an email in your inbox, a Slack message — and the record lands in your app's own database, ready for your screens. Ask the builder in your own words ("every new Google Forms response arrives from Zapier") and it writes the route. Then set up two things once:
- A shared secret. Pick a long random value and save it:
npx vibes-diy secrets set ZAPIER_INBOUND_SECRET --vibe you/your-app, or the vibe's Settings page. - The Zap. The trigger is your tool. The action is Webhooks by Zapier →
POST to
https://vibes.diy/vibe/you/your-app/_api/zapier/lead, payload type JSON, with your fields mapped and the tool's own id for the record (the response id, the row id, the message id) mapped toid. Add a header namedx-zapier-secretcarrying the same secret.
What the route does with each delivery:
- It checks the sender. The header is compared with your secret in
constant time; a delivery without it gets
401and writes nothing. The secret rides a header of your own naming, becauseAuthorizationandCookieare removed before your handler sees a request. - It keeps one record per thing. Zapier can deliver the same record twice, so the record's own id keys the document, and a second delivery lands on the same record.
- It seals each arrival, and within a minute it's a record. The route
writes a sealed arrival that only your backend reads; your
scheduledtick checks the seal against your secret and turns each match into the record your app shows. That is what lets your app welcome anonymous deliveries from Zapier while every record on your screens is one your Zap sent: an arrival without the seal is cleared without ever appearing.
Until the secret is set, the route answers 503 ("this app is still being
set up") and the rest of your app works as usual. The builder's own recipe is
in the backend.js reference, under Records in from
Zapier.
The identity model — one permission system, not two
There is no service key. Every ctx.db.put and ctx.db.delete a handler
makes goes through your app's own access.js, acting as whoever triggered
the handler:
| Handler | Writes act as… |
|---|---|
onChange |
the user whose write triggered the event |
fetch |
the signed-in caller when verifiable — treat as possibly anonymous |
scheduled |
the app owner, in admin mode |
email |
the person who sent the mail when Vibes knows them, else nobody |
Two consequences worth internalizing:
onChange is for derivation, never privilege escalation. Its writes act
as the triggering user, so anything it may write, that user's own client
could write too. Its reads see the same boundary: an access-function-bound
database comes back filtered to the triggering user's channels, so a reaction
can read its neighbours but never anything privileged. If a document should
be something only the server controls, don't write it from onChange.
scheduled is the owner, with the owner's override. It runs in admin
mode: requireAccess/requireRole no-op, and its reads are unfiltered — a
scheduled sweep can read and rewrite every user's documents in the app.
Access functions protect users from each other, not from the app's owner.
That makes scheduled the right lane for genuinely server-controlled
documents (gate them to the owner in access.js and no user can forge them),
and also the lane to keep small and well-guarded: because admin mode skips
the access checks, a buggy scheduled write fails silently-wrong instead of
forbidden.
If your fetch handler writes, the access function must allow that write for
an anonymous caller — or move the write to onChange/scheduled, which
carry stronger identities.
onChange without loops
jsexport async function onChange(event, ctx) {
// event: { dbName, docId, doc, oldDoc, seq, deleted } — the id is docId; doc is the body plus _rev
if (event.dbName !== "votes" || event.deleted) return;
await ctx.db.put(
{ _id: "tally-" + event.doc.pollId, kind: "tally", bump: event.seq },
{ db: "tallies" }
);
}
Two rules keep reactions sane, both visible above:
- Guard on
event.dbNamefirst — the handler fires for every database in the app, so an unguarded write-back loops on itself. - Write derived docs to a different database than the one that
triggered the event. Backend writes trigger
onChangeagain (the platform caps runaway chains, but a same-database ping-pong is still wasted work). Different db + dbName guard makes loops structurally impossible.
A few details of the event worth knowing before you lean on them:
- The chain cap is four generations deep. A person's write is generation one; a write your handler makes in response is generation two, and so on. Nothing fires past generation four, and the suppressed event leaves no trace in your app's logs — a reaction that quietly never runs is the sign to look for.
doc._revis the write's sequence number, the same value asevent.seq, and_revis filled in on read, never stored.- A deleted document arrives as
{}withdeleted: trueand no_rev.oldDocis the stored body of the previous revision without a_rev, and it isnullwhen there was no previous revision or that revision was itself a delete.
When a handler throws — retries, and the end of the line
Each lane fails differently: fetch does not retry, while onChange and
scheduled both retry on their own:
fetchanswers the caller with the500above and does not retry; a caller that wants a retry has to send the request again.onChangeis retried with backoff. A throw puts the same event back on the queue after 10 seconds, then 30, 90, 270 and 300 seconds — six deliveries over about twelve minutes. A handler that keeps throwing gets the event five more times with the samedocand_revas the first delivery, which is why the state-machine pattern claims a job withifRevbefore doing the work. Throw on purpose when the work is safe to repeat (an upstream503); return on purpose when it is not (a paid call, a message to a person).scheduledretries a throw with a short backoff. A throw is recorded as the timer's last error (npx vibes-diy app status you/your-appshows it) and the handler runs again after 5 seconds, then 10, 20 and 40 (never longer than the timer's own interval). After the fifth failure in a row the timer goes back to its normal cadence. Those extra runs repeat whatever the handler did before it threw, so make the work safe to repeat, and carry longer-lived retry state on a document — anattemptscounter and a cap — as scheduled self-maintenance shows.
After the sixth onChange delivery fails, the platform stops and writes one
error-level line into your app's log, prefixed platform: so you can tell
the platform giving up from your own code throwing:
platform: onChange delivery gave up after 6 attempts — <reason>. db=<db> doc=<id> seq=<n>
shnpx vibes-diy app logs you/your-app --since 24h # look for level error, body "platform:"
That line is the only trace a lost event leaves. The same shape covers a
schedule that could not be re-armed after a push
(platform: schedule re-arm delivery gave up …); npx vibes-diy app status you/your-app shows the timer's health and re-arms a dead one. When it says
STALLED, your live release has a scheduled handler with no timer armed
for it. Start it again with npx vibes-diy app rearm you/your-app. When it
says stopped, you stopped the timer yourself (with app schedule off, or by
asking the builder to stop it), and it names when; the same
npx vibes-diy app rearm you/your-app starts it again, and so does your next
deploy. When it says paused, you switched "Scheduled runs" off in the app's
settings; turn the switch back on there to start it again.
scheduled — periodic work
The interval is a static string literal between "5s" and "1h", validated
at push time:
jsexport const config = { scheduled: { interval: "15m" } };
export async function scheduled(event, ctx) {
// event: { scheduledTime } — ISO timestamp of this tick
const docs = await ctx.db.query({ db: "notes" }); // unfiltered, admin mode
// read, decide, then put/delete
}
ctx.db.query({ db }) returns the database's latest docs (capped at 2000) —
filter and sort in the handler. A plain ACL database can be queried from a
user-triggered fetch or onChange when the acting identity may read it;
those reads are ACL-gated and anonymous callers are denied. A database bound
to an access function still rejects fetch-lane reads, but onChange reads
it filtered to the triggering user's channels — the same per-reader
filter the frontend applies, so the handler sees exactly what the user who
triggered it could see. Page with limit/after and walk next to
exhaustion: a page whose docs all filter out still advances the cursor.
The owner's scheduled/admin override may query an access-function-bound database, but that read is deliberately unfiltered. For viewer-filtered access-function reads, query from the frontend instead; if the backend needs to query the data itself, use a plain ACL database.
Revisions — write only if nothing changed since you read
Every document a handler reads carries its current revision as _rev: the doc
ctx.db.get returns, each ctx.db.query row, and the onChange event's
doc. The first two carry _id beside it; the event's id is event.docId. Pass it back when you write, and the write commits
only if nobody has written that document since your read:
jsconst job = await ctx.db.get("job-42", { db: "jobs" });
try {
await ctx.db.put({ ...job, status: "running" }, { db: "jobs", ifRev: job._rev });
} catch (err) {
if (err.code === "conflict") return; // someone else moved it first
throw err;
}
- One of several racers wins. When two runs write from the same read, one
commits and the other throws with
err.code === "conflict"anderr.currentRev, the revision there now. That holds even when both wrote identical content. ifRev: nullmeans "create it". The write commits only if the document does not exist. A deleted document counts as not existing, the same answergetgives (null), soifRev: nullbrings it back._revis filled in on read and never stored. Spreading a read into a put is safe, and youraccess.jsnever sees it.- Leave
ifRevout and a write is last-writer-wins, exactly as before. Existing apps change nothing.
Revisions are a backend.js feature. Writes from the browser through
useFireproof save to the local copy first and sync afterwards, so they stay
last-writer-wins. The doc-status state machines
pattern uses revisions to hand each job to exactly one worker.
Secrets — set by the owner, seen only by handlers
shnpx vibes-diy secrets set STRIPE_KEY --vibe you/your-app # prompts for the value, hidden; or the vibe's Settings page
npx vibes-diy secrets ls --vibe you/your-app # names + last4 only
npx vibes-diy secrets rm STRIPE_KEY --vibe you/your-app
In the app, the same place is Code mode's App settings tab, under
Secrets: type the name under KEY, paste the value beside it, and press
Set. The feature that reads it works the moment it is set. Key names use
letters, numbers and _, like MY_API_KEY, and start with a letter or _
(up to 64 characters). The KEY field shapes what you type as you go: it
upper-cases it and turns spaces and hyphens into _, so my api-key becomes
MY_API_KEY. Typing the name of a key you already saved picks that key just
as it is saved, lower case included, so Set gives it a new value. A multi-line value, such as a PEM key, keeps its line breaks
when you paste it. Each vibe holds up to 32 secrets of up to 8192 bytes each.
Handlers see them as ctx.secrets.STRIPE_KEY — frozen, {} when none. The
value never appears in a document, a release, or any browser (not even
yours); it exists only inside a handler invocation. Use secrets to verify
inbound webhooks (compare a shared secret) or authenticate outbound calls
(Authorization: Bearer ${ctx.secrets.KEY}). Keeping your own code from
leaking one is on you: never write a secret anywhere users can read —
a doc, a response body, an error message. Write back a status code, not the
response.
An app that needs a secret before a feature works gets one Setup surface, and it looks the same whichever integration asked for it. The backend answers what the app needs and whether each item is done (a key present, a page saved, an account connected); you, the owner, get a Setup entry in the app's own navigation, highlighted until every item is done, listing the steps as links to the exact pages with your vibe's handle and slug filled in (an app with no navigation shows a banner at the top that opens it). Visitors never see the steps: the feature that depends on them reads "not open yet" until you are done, and the rest of the app works as usual. Set the secret in another tab, come back, and the feature unlocks in place with no reload. Once done, the entry stays, quietly, for rotating a key or switching from test to live. Payments are the worked example: Take payments with Stripe § What you set up once.
Outbound fetch — what your backend may call
Handlers can fetch() external HTTPS APIs through a policy gate with three
lanes:
- Public reads: a plain
GETwith no key and no custom headers reaches any ordinary site, so an RSS or Atom feed, a public JSON API, an.icscalendar or a web page just works — nothing to arrange. The platform makes the request itself and serves the answer from a cache for about five minutes, so polling one feed faster than that re-reads the same bytes. - CORS-parity: if a browser on your app's own page could call
it, your backend can too. Same preflight rules, same
Access-Control-Allow-Origincheck, browser-forbidden headers stripped. Most public JSON APIs just work — Bluesky's entire XRPC API, for example, is CORS-open, which is why a vibe can run a Bluesky bot with no special arrangement. - Curated platform list: server-to-server APIs that send no CORS headers
(
api.github.comis seeded,api.linkedin.comcame via meta-hub). A shop can read its own Squarespace orders and profiles (api.squarespace.com) and its Shippo orders, labels and parcel templates (api.goshippo.com), with the owner's key saved as a secret; both are reads only. Adding a host is a reviewed change to the platform's curated list — ask in Discord or open an issue at VibesDIY/use-vibes.
Sending a record to another tool goes through Zapier. hooks.zapier.com
is on the curated list for a POST to a Webhooks by Zapier → Catch Hook, so
an app can hand a new record to any tool Zapier reaches (Clio, Slack, Google
Sheets, an inbox) without holding that tool's credentials. Make the Zap, save
the hook URL as a secret (npx vibes-diy secrets set ZAPIER_HOOK_URL --vibe you/your-app, or the Settings page), and ask the builder to post each new
record to ctx.secrets.ZAPIER_HOOK_URL. The URL is the credential: never
write it into a document or a response. Treat any 2xx as accepted and mark the
record sent; on anything else throw, so the event is re-delivered with backoff
and a run that never succeeds lands in the app's logs. Walkthrough:
Send your vibe's data anywhere you want.
Records travelling the other way are
Bring records in from Zapier.
Taking money goes through Stripe Checkout, into your own Stripe account.
Ask the builder to charge for something — a deposit, dues, tickets, a one-time
purchase — and it writes the backend that mints a Checkout Session for each
order through ctx.stripe and opens Stripe's own payment page in a new tab;
the card never touches your app. Press Connect Stripe under Payments
on your app's Settings tab once, and the Pay buttons go live in test mode as
soon as Stripe says your account is ready (live payments follow on a Go
live with Stripe button on the same tab). The platform holds the Stripe
credential, and each order remembers whether it was made in test or live. An
order is marked paid only after the backend reads the session back from
Stripe and matches it to the order, and a sweep every few minutes settles
anyone who paid and closed the tab. One-time charges here; recurring money
is the membership recipe below. The builder never adds payments unasked: an app that only
records orders stays that way, and offers Take card payments with Stripe
as a chip you can tap when you want it. Guide:
Take payments with Stripe; the builder's own recipe:
Stripe payments.
A paid membership is a subscription, and it follows Stripe's state. Ask for a monthly or yearly membership and the builder uses Checkout in subscription mode, keeps each member's access a mirror of their subscription (active and trialing are in; a failed card gets a grace period, five days by default, then locks; cancelled locks at once), sends cancellations and card changes to Stripe's Customer Portal, and re-reads every live subscription on a half-hourly sweep. Members-only content is a channel the membership record grants, so a lapsed member loses it on the next sync (the posts and the memberships share one database, because a grant reaches only the database it was made in). One Stripe step beyond Connect Stripe: save the Customer Portal under Settings → Billing in your Stripe Dashboard with "cancel at end of billing period" on. Guide: Take payments with Stripe; the builder's own recipe: Stripe subscriptions.
Reading YouTube needs no key. ctx.youtube.fetch("/channels?part=statistics&forHandle=@you")
reads the public YouTube Data API on a key vibes.diy holds, and answers
YouTube's own JSON. It reads channels, videos, playlists and playlist items;
each read costs one unit from your app's own allowance of 2,000 a day, which
resets at midnight UTC, and ctx.youtube.status() tells you how many are left
without spending one. Guide: Works with YouTube;
the builder's own recipe: YouTube.
A link you paste into the builder rides the same gate. When the builder tells you that reading a source takes more power than this app has today, that source sits outside the three lanes above — ask the vibes.diy team in Discord or open an issue at VibesDIY/use-vibes, and they can open it for you.
A denied call returns
403 {"vibesEgressDenied": true, "gate": "floor" | "owner-blocked" | "cors" | "read-rate" | "rate-limit", "host": …} —
check for that shape and surface a useful error instead of a mystery failure.
gate says which lane refused: cors is a write or a keyed call to a host
that never opted you in, and read-rate means the public-read budget is spent
for the moment and the next tick clears it.
Limits: HTTPS on port 443 only, 15s per request, 10MB responses, per-vibe
rate caps (30 per 10s, 300 per minute). Public reads from a host that has
not opted your app in are budgeted more tightly — 10 per 10s and 60 per
minute — and a body over 512KB is served but not cached. Make outbound calls before
returning your Response — a fetch fired after the handler returns is
denied. The design story behind the gate is
"Trust the target, bless the person".
ctx.callAI — server-side AI with no key anywhere
jsconst text = await ctx.callAI(
"Summarize these entries as one paragraph: " + JSON.stringify(entries),
{ model: "openrouter/auto", max_tokens: 500 }
);
Resolves to the completion text. No API key exists in your code, your
secrets, or anywhere in your tenant world — the platform makes the call and
meters the cost to the account of whoever triggered the handler (the writer
in onChange, the signed-in caller in fetch, the owner for scheduled
ticks and anonymous webhooks — same ai_credits ledger as the chat).
Options: model (default "openrouter/auto"), max_tokens, temperature.
No streaming, no schema mode — ask for JSON in the prompt and JSON.parse
defensively. Budget: a handful of calls per invocation (currently 5) and
~64k prompt chars. A failed or denied call throws: catch it and write an
error field back onto the doc rather than losing the event. Keep
interactive, streaming AI in App.jsx via callAI; use ctx.callAI when
the result must be server-authoritative — moderation, digests, summaries
users shouldn't be able to forge. The canonical shape is
button → request doc → onChange → ctx.callAI → write-back: the
database is the request/response channel, so results survive reloads and
sync to every viewer.
ctx.webSearch — look things up on the web
jsconst { results, summary } = await ctx.webSearch("lego 10305 in stock", { maxResults: 5 });
// results: [{ title, url, snippet }] — every url an https link
Your backend can search the web with no key and no setup: shop listings,
news, opening hours, whatever is new on a topic. It pairs naturally with
scheduled, so an app can keep watch for something every morning and save
what it finds beside the record it belongs to. Each search runs on the same
account ctx.callAI bills (the owner on a scheduled tick), a couple of
credits a search, with up to 10 searches a handler run and queries up to 300
characters. When a run spends its searches or its credits, the call
throws an Error whose reason is "budget" or "credits": catch it,
keep what the run found, and the next tick carries on. A search that finds
nothing throws with reason "empty", so a record keeps the links it already
has. To watch a long list, save a cursor between ticks: follow each page's
next, save where you stopped when a search throws, and start over at the top
when next runs out. Results are web data,
so store or show them, or quote them to ctx.callAI for judging, with your
own instructions in charge.
ctx.notify — tell one participant
jsawait ctx.notify({
toHandle: game.opponent,
body: "Your turn",
dedupeKey: `game-${game._id}-turn-${game.turn}`,
});
One object, all three fields required; an optional path (a hash path
inside your app, like #/game/42) makes the notification open there. The
message lands in that person's bell, inbox, and push notifications. toHandle must already be a participant
of this app — the owner (always), an accepted invite, an approved request,
a handle in the access function's grant state, or somebody whose authenticated
write reached the app (revocations deny anyone but the owner); the platform
checks, not your handler. Membership resolves the person through their bound
handle, except the grant-state clause, which matches the named handle itself.
A passing check plus valid fields writes to the inbox history of a recipient
the platform can resolve (an unresolvable handle fails after the participation
check); their switches silence the live bell, push, and email — not the
history. Note
the grant-state clause is yours to write with care: naming a handle there
makes it notifiable, so for opt-in turn messages seat handles their owners
seated themselves — the full rule and the guest-list convention live in
Telling one person vs. telling everyone.
body is the whole message, plain text and 500 characters max (the
platform supplies the title and the link back to your app). dedupeKey names
the happening, keyed per (app, recipient), so a retried handler delivers once.
It throws on failure and resolves with nothing on success — there's no
result to inspect, so await it inside a try/catch and let the
surrounding work survive an undeliverable message.
A picture with the words
Add picture and the notification carries a photo: someone reached by text
gets it under the words, the way a friend drops a picture into a chat.
jsconst sent = await ctx.notify({
toHandle: follower.handle,
body: "Tonight's poster is up",
dedupeKey: `poster-${poster._id}`,
picture: { dbName: "posters", docId: poster._id }, // or poster._files.art.url
});
// sent.picture is "attached", or "text-only" with a reason
Name a record of your own app ({ dbName, docId }, plus fileKey to pick one
of several files; a record an image button painted works as is), or one of its
own file URLs. Each person gets the picture only when they could open that
record in your app, and it goes as a png, jpeg, gif or webp of up to 5 MB.
Anything else goes as the words alone, so the call still succeeds and the
result says why (denied, not-found, no-picture, too-large,
not-a-photo). On the web the notification shows its words. A follower who
texts Vibes' phone number (rather than iMessage) gets the picture when anyone
may open it, as on a public app; a private one reaches them as the words.
Use it when one person needs to know one thing. When everyone should
see something, there is no broadcast call: write the change into a database
the audience already reads, and their useLiveQuery shows it to exactly the
entitled readers. Both halves, with worked examples:
Telling one person vs. telling everyone.
tools — the verbs a person can ask for
Some of what people do in your app fits in one sentence: vote for a place,
claim a slot, add a book to the list. Declare those verbs as tools. Each
declaration is the contract an assistant host reads: a host that lists and
calls an app's tools lets an assistant acting for a person do them on that
person's behalf, through your app's own rules. Vibes in your texts is the first
host: in a chat, one to one or in a group that added your app, it reaches for
your app's tools first, as the person who asked (or as the group, for a group
setting), and sees each tool by name and description, as meetup_keeper.vote
for the vote tool of meetup-keeper:
jsasync function recordVote(input, ctx) {
const me = ctx.userInfo.userHandle;
await ctx.db.put({ type: "vote", place: input.place, voterHandle: me }, { db: "meetup", id: `vote:${me}` });
return { ok: true, place: input.place };
}
export async function fetch(request, ctx) {
return Response.json(await recordVote(await request.json(), ctx)); // the page's button
}
export const tools = {
vote: {
description: "Vote for one place for the next meetup.",
input: { place: { type: "string", description: "The place, as the poll lists it" } },
handler: recordVote, // the same function the button reaches
},
add_pick: {
description: "Add a book to this month's picks.",
for: "members",
input: { title: "string" },
write: { db: "picks", set: { type: "pick" }, key: "caller" }, // one record, no code
},
};
Each tool has a one-line description, typed input fields (string,
number or boolean, optionally with an enum), who it is for
("anyone", "members" or "owner"), and either a handler or a declared
write. A declared write saves the input with set laid over it;
key: "caller" keeps it to one record per person. A vibe declares up to 8
tools, and a backend.js that exports only tools is complete.
A tool can say more about itself, and every host reads it: the Vibes connector passes these to an assistant in the names it already knows, and Vibes in your texts reads them too.
jsexport const tools = {
standings: {
title: "Standings", // a short display name, up to 60 characters
description: "See which place is ahead for the next meetup.",
annotations: { readOnly: true }, // only looks things up
output: { leader: "string", votes: "number" }, // what the answer holds
handler: readStandings,
},
cancel_meetup: {
description: "Cancel the next meetup and tell everyone who voted.",
for: "owner",
annotations: { consequential: true }, // runs once the person says yes
handler: cancelMeetup,
},
};
annotations holds one static flag: readOnly for a tool that writes
nothing, or consequential for one a person would want a say in before it
runs. Vibes holds a consequential tool for that yes: when an assistant calls
it, the person is asked first, in Vibes' own words, with the tool's name and
exactly what it will be given, such as Ready to run "cancel" in meetup-keeper with reason: "rain"? Reply yes and it goes ahead., and the tool runs once their
next message says yes. A plain name reads best in that question. In a group
chat everyone reads it, so it names a text field's value when that field lists
its choices with enum (day: { type: "string", enum: ["Tue", "Wed"] }) and
gives any other text by its length, keeping what the group sees to your own
words. Mark a
tool that messages other people this way. When a tool's handler sends a
message to someone other than the person using it (ctx.notify) or works
through a connection, vibes-diy push names it, so you can mark it
consequential: true, or consequential: false when it needs no yes. output is written like input and describes the answer. When a
handler returns { error: "…" }, the host reports it as the tool's error in
your words, so the assistant tells the person what your app said. Return it
before the handler saves anything: a record already saved stays saved, so an
error after a save says what was done.
A tool always acts as the person it is used for. ctx.userInfo is them, every
write passes your access.js as them with user.backend === "tool", reads
see what they can see, and ctx.callAI spends their credits. A tool never gets
admin mode or any other bypass: it writes what your access.js admits for that
person, and ctx.requireBackend("tool") marks a record that only tools write. Name the verbs a person would actually
say, one action per tool, and let the caller come from ctx.userInfo rather
than an input field.
Your tools also run from the terminal and from the chat on your app's own
page, as whoever is signed in there. npx vibes-diy app tools you/meetup lists
what the app offers you, and
npx vibes-diy app call you/meetup vote --input '{"place":"Tap Room"}' runs one
(CLI). A consequential tool asks at the
terminal first and runs when you answer y. In your app's own chat, the agent
calls each tool by its own name (vote), and on your own app a
consequential one waits for you: the agent's reply ends with that same
question, and the tool runs once your next message says yes. A collaborator
with code access runs consequential tools from the app or the terminal.
Email in — your app's own address
Every app can receive mail at <slug>--<handle>@in.vibes.diy, the same
slug--handle order as its own web address. Forward your order confirmations
or receipts to it, hand it to a venue or a supplier so their messages land in
your app, or make it your club's shared inbox. Ask for it in plain words
("forward my receipts to the app", "when the venue emails us, add it to the
calendar") and the app shows you its address with a copy button.
Give each kind of mail its own tag with plus-addressing:
[email protected] reaches the same app with message.tag set
to "urgent", so one address sorts rush orders from the rest.
jsexport async function email(message, ctx) {
// message: { id, from, fromAddress, authenticated, sender, to, cc, subject, text, html, date, tag, headers, attachments, untrusted: true }
const record = {
type: "mail",
from: message.fromAddress, // "[email protected]", lowercased
verified: message.authenticated === true, // the mail server checked the sender's domain
subject: message.subject,
receivedAt: message.date,
tag: message.tag || "inbox",
};
await ctx.db
.put(record, { db: "orders", id: "mail:" + message.id, ifRev: null })
.catch((err) => {
if (err?.code !== "conflict") throw err; // this message is already filed
});
}
- Everyone's mail lands. Anyone can write to the address, and every
message is filed with who it came from:
message.fromAddressis the bare address andmessage.authenticatedsays the mail server verified the sender's domain, so your page can mark those. Vibes slows down one address that sends a flood, so your app keeps no sender list. - Mail acts as whoever sent it. When you forward your own mail, the app
knows it is you (
message.sender); any other mail acts as nobody, and youraccess.jslets the mail handler file it withctx.requireBackend("email"). - The mail is data. Store it, show it as text, have
ctx.callAIanswer your own question about it; the message itself never steers your app. - Your app answers on its own page and to you. A reply to the person who
wrote is a draft you approve first (
ctx.ask, below). - People sign in to be known. Mail files a message. Who someone is in your app comes from their vibes.diy sign-in, so an app keeps its accounts and membership there and mail stays mail.
ctx.email.addressholds the app's address on every handler, so afetchroute can show it on the page with a copy button.textandhtmlarrive cut at 256 KB each, withtextTruncatedandhtmlTruncatedsaying so. Attachments come as names, types and sizes.ctx.callAIinside the handler bills to you, whoever sent the mail. To work a filed message as yourself (parse it, hand it to an agent), queue it withctx.later, which runs as you. A message can arrive more than once, so the first write is keyed onmessage.idwithifRev: null.
The next three sections follow one order email through a pie shop's app: an agent files it, the app asks you before it replies to the customer, and it checks back two days later.
ctx.agent.run — let an agent work with your tools
Some jobs are easier to describe than to write out: read this order email and
file the order, triage this request, sort this pasted form. ctx.agent.run
hands the job to an agent that works with your app's own tools, from any
handler. Here it reads each email the email export filed, from a later
run that acts as you:
jsexport async function email(message, ctx) {
const id = `mail:${message.id}`;
await ctx.db.put({ type: "mail", from: message.fromAddress, subject: message.subject, text: message.text }, { db: "orders", id, ifRev: null });
await ctx.later({ in: "1m", name: "read-mail", data: { id }, key: `read-${message.id}` });
}
export async function later(event, ctx) {
const mail = await ctx.db.get(event.data.id, { db: "orders" });
const run = await ctx.agent.run({
goal: "If this email is an order, add it with add_order, then notify_owner.",
input: { from: mail.from, subject: mail.subject, body: mail.text }, // the email, as data
tools: ["add_order", "notify_owner"], // optional: defaults to all your tools
});
// run: { summary, data, steps: [{ tool, input, ok }], stoppedBecause }
await ctx.db.put({ _id: `status:${event.data.id}`, summary: run.summary, stoppedBecause: run.stoppedBecause }, { db: "status" });
}
Besides your tools, the agent can read your app's records (db_query,
db_get) and ends the run with finish, whose summary and data come back to
your handler.
- Each tool acts as your handler acts: the writer in
onChange, the signed-in caller infetch, you, the owner, on ascheduledtick or alaterrun, and the person who sent anemailwhen Vibes knows them. The agent gets no extra reach, andaccess.jsdecides every write. A write your rules refuse comes back as a step withok: false, and the agent adjusts or stops. - It is billed like
ctx.callAI, to the same person, from the sameai_credits. Out of credits, the run stops withstoppedBecause: "credits". - The platform keeps runs short: a run stops after a fixed number of
steps and tool calls (
stoppedBecause: "steps"or"tool_calls"), and its model calls count on their own budget, apart from the handler'sctx.callAIcalls. inputis data. Pass the email or webhook body asinputrather than pasting it intogoal; the platform shows it to the model as data, so words inside it cannot steer the agent. A tool that sends something outside your app because of what an email said should ask you first withctx.ask, which comes next.- Every step writes one line to
ctx.log, sonpx vibes-diy app logs <handle>/<app-slug>shows what the agent did.
ctx.ask — your app asks you before it acts
Some work should wait for a yes. The agent just filed a customer's order from an email; your app drafts the reply, and you decide whether it goes out:
jsexport async function onChange(event, ctx) {
if (event.dbName === "orders" && event.oldDoc === null) {
await ctx.ask({
question: `Reply to ${event.doc.customer} that their pies ship Friday?`,
options: ["Send", "Skip"],
data: { orderId: event.docId },
key: `reply-${event.docId}`,
});
}
if (event.dbName === "_asks" && event.doc.status === "answered" && event.doc.choice === "Send") {
// send the reply, mark the order, then check back in two days:
await ctx.later({ in: "2d", name: "follow-up", data: event.doc.data, key: `follow-${event.doc.data.orderId}` });
}
}
ctx.ask records the question in your app's own _asks database and tells
you about it, in your bell, on your phone, and in your texting chat for an app
your agent made. Your answer is a write to that ask (status: "answered",
choice), and it arrives in onChange like any other write, so the workflow
picks up right where it left off. Only you, the app's owner, can read or
answer _asks; your app can show you a panel of pending asks with
useFireproof("_asks"), and the notification opens #ask=<id>.
The same key while an ask is pending returns the same ask, so a retried
handler asks once. An ask nobody answers turns expired after a week, which
also reaches onChange, so the app can say it did not send.
ctx.later — wait, then continue
jsexport async function later(event, ctx) {
// event = { name: "follow-up", data: { orderId }, scheduledTime }
const order = await ctx.db.get(event.data.orderId, { db: "orders" });
if (order === null || order.status === "shipped") return; // the world moved on
await ctx.ask({ question: `${order.customer}'s pies haven't shipped. Send an update?`, options: ["Send update", "Not yet"], data: { orderId: order._id }, key: `update-${order._id}` });
}
ctx.later sets one timer: in a duration ("30m", "3h", "2d") or at
an exact time. When it comes due, your later export runs once, as you, the
way scheduled does. A second ctx.later with the same key moves the timer
instead of adding one, and ctx.later.cancel(key) removes it. Timers wait
while your app is unpublished or its scheduled runs are paused, and run once
it is back. For "every morning at 9", keep using scheduled.
npx vibes-diy app schedule off you/your-app pauses your later timers along
with any scheduled task, and says how many it paused. Each timer keeps its
place. npx vibes-diy app status you/your-app counts the timers waiting and
whether they are paused, and npx vibes-diy app rearm you/your-app (or your
next deploy) lets them run again: a timer whose time passed during the pause
runs right away.
hooks — functions the platform calls
A hook is a function the platform calls at a set moment. Hooks live in their
own export, apart from tools, so they take none of the 8 tool slots and an
assistant sees only your app's verbs. The first hook is picturePrompt: a
picture app's own way of writing a picture's prompt. It takes the person's
words as addition ("make it 1920s", "add rain") and returns the prompt
string your app paints from:
jsconst STYLE = "A warm studio portrait, soft window light, film grain";
export const hooks = {
picturePrompt: {
input: { addition: { type: "string", optional: true } },
async run(input, ctx) {
const extra = (input.addition || "").trim();
return extra === "" ? STYLE : `${STYLE}. ${extra}`;
},
},
};
When someone in a chat sends a first photo or asks for a new look through your app, Vibes runs this hook as them and paints exactly what it returns (up to 1,200 characters), and the record keeps that prompt too. Answer within 5 seconds: the platform ends the hook at that mark, a slower first photo paints from your app's newest record's own prompt, and a slower new-look ask comes back for Vibes to try again.
A hook reads and computes. Inside run, ctx.db.query and ctx.db.get read
what the person can read and ctx.log writes to your logs. Saving a record,
ctx.callAI, ctx.notify and a fetch to another service belong in a tool
or a handler; in a hook each one throws a hook is read-only. An app that
marked a tool picturePrompt: true keeps working: that tool now runs as the
hook, the same read-only way, and moves to hooks whenever you next edit it.
ctx.log — the diagnostics your handler leaves behind
jsctx.log("info", "tick finished", { written: 3, skipped: 12 });
ctx.log("cache miss", { key }); // level optional, defaults to info
shnpx vibes-diy app logs you/your-app --since 1h # or --tail to follow
That's the lane. A handler's console.* output is collected nowhere — if
you want to see it later, route it through ctx.log. The level comes first
and is optional ("debug", "info", "warn", "error"); any other first
argument is treated as the message with the level defaulting to info.
Log the shape of a run, not its contents: document ids, counts, statuses,
timings, and an error's message and code. Identifiers keep the stream
diagnostic while users' document bodies and ctx.secrets values stay inside
the handler.
Honest edges
- Backends always run the live release. There is no version-pinned
backend serving: whatever you pushed last under
you/your-appis what/_api,onChange, andscheduledexecute. To test backend or access changes without touching production, push under a secondary slug (npx vibes-diy push --vibe you/your-app-staging) and promote by pushing to the real slug when it works. - Verified signed-in identity on the
fetchlane is still rolling out — design as iffetchcallers are anonymous, and requireallowAnonymous-permitted writes or route through the other lanes. - Two kinds of observability, and they're for different jobs. For
debugging,
ctx.logis the real log lane and you read it back withnpx vibes-diy app logs you/your-app --since 1h(--tailto follow) — a handler'sconsole.*output goes nowhere. For anything users or your dashboard should see, write status docs into anoplogdatabase, which doubles as the dashboard's data source (see the operator console pattern). The log stream is for you; the documents are the app's own memory.
Where to go next
- backend.js reference — the full contract, every field and cap, generated from platform source.
- Telling one person vs. telling everyone —
when to send a
ctx.notifyand when to just write the change down. - Connect your visitors' accounts — let a visitor link their own GitHub account so your backend can read from it, with no credential code of your own.
- Patterns cookbook — the write-only credential vault, doc-status state machines, CI lanes with device certs, and the other production patterns our own infrastructure runs on.
- Launch stories: Every vibe just got a backend, Your backend can call the model now.