Hooks: run your code when things happen
Register your own typed functions for sign-ups, payments, form answers and 20 more events in one file. They run after the change is saved, are retried for about a day, and every run is in Admin → Developers' delivery log beside your webhooks. Guards can turn away a sign-up or a new organisation, jobs run your code on a schedule, routes add your own API, tools give your AI agents your own tools beside ours, your own React blocks appear in the page editor, and any event can be replayed to your hooks and integrations.
Updated · 17 min read
Hooks are for the code only your business needs: a welcome email on sign-up, a row in your CRM when a customer first pays, a lead tagged when a form comes in. You write a function, register it for an event in one file, and the app runs it every time that thing happens. It runs after the change is saved, is retried for about a day if it fails, and every run is in Admin → Developers.
Write your first hook
Your code lives in apps/server/src/app/. Starter updates never change that folder beyond its example file, so you can pull new releases without conflicts in your code. Open apps/server/src/app/index.ts:
import { defineApp, type Hook } from "../modules/hooks/index.js";
export const welcomeEmail: Hook<"user.signed_up"> = async ({ user }, ctx) => {
await ctx.email.send("notice", user.email, {
name: user.name,
subject: "Welcome aboard",
body: "Thanks for signing up. Your account is ready whenever you are.",
});
};
export default defineApp({
hooks: {
"user.signed_up": [welcomeEmail],
},
});
The event's name autocompletes, and the payload is typed from it, so user.email is checked as you write. Restart the server, sign up, and the run shows in Admin → Developers.
The example file ships with seven real examples, each switched off: a welcome email on sign-up, a Slack message on the first payment, posting whoever sends a form to your CRM as a lead, a guard that lets only listed email domains sign up, a Monday job that posts last week's sign-ups to Slack, a small API route for plans with API access, and an agent tool that tells an admin's agent who signed up this week. Uncomment one at the bottom of the file and set the environment variable it names.
Give each hook a name: a named function as above, or { name: "crm", timeoutMs: 10_000, run }. The name is how Admin → Developers lists it and how a retry finds it again.
What a hook gets
The payload is the event's, and the second argument has what most hooks need:
ctx.db | The app's database (Drizzle), to read or write your own tables |
ctx.logger | A logger tagged with the hook and the event |
ctx.email.send(template, to, data) | One of the app's emails, by its template's name ("notice", "order" and the rest, checked as you type), with the fields it shows: subject, body, url, name and so on. Sent once even if the hook is retried. Throws while email isn't set up, so the run is retried |
ctx.track(event, properties, userId) | An event in the app's own analytics |
ctx.entitlements(organizationId) | An organisation's plan's features and limits |
ctx.event | id, name, occurredAt, attempt, test for a test event, and replay for a replayed one |
ctx.signal | Aborted when the hook's time is up; pass it to fetch and stop when it fires |
The events
| Event | Sent when |
|---|---|
user.signed_up | An account is created, by any sign-in method |
user.email_verified | Someone opens the verification link in their email |
organization.created | Someone creates an organisation |
member.joined | Someone accepts an invitation to an organisation |
subscription.started | Stripe confirms a subscription that puts an organisation on a paid plan |
subscription.changed | Stripe confirms a change of paid plan or of seats |
subscription.cancelled | Stripe ends a subscription, or it lapses, and the organisation is on Free again |
payment.first | An organisation's first paid invoice above zero, once per organisation |
invoice.paid | Stripe reports an invoice paid |
payment.failed | Stripe reports a failed payment for an invoice |
order.paid | Stripe confirms a store checkout's payment, once per order, including one that settles days later |
order.refunded | Stripe reports a refund or a lost chargeback on a paid store order, each time the amount changes |
order.fulfilled | An admin marks a paid store order fulfilled (with its tracking), or an order of downloads only is paid; once per order |
order.cancelled | An admin cancels a paid store order before it's sent, with why and whether the rest is being refunded; once per order |
form.submitted | Someone sends one of your forms and it isn't spam, or you restore an answer the spam filter caught |
enquiry.received | The contact form sends an enquiry |
affiliate.approved | An admin approves an affiliate application |
experiment.finished | A test is completed, with or without a winner |
page.published | A page is published, by an admin, a schedule or an agent |
site.status_changed | The whole site goes live, or into coming soon or maintenance, by hand or at its launch time |
course.enrolled | Someone first opens a lesson of a course they may take |
lesson.completed | Someone finishes a lesson for the first time |
course.completed | Someone finishes the last lesson of a course for the first time |
Payment, subscription and order events come only from Stripe's webhook, never from the browser. Six of these events can also go to a webhook; see Webhooks and alerts. Admin → Developers lists every event with a sample payload, and so does pnpm hooks:fire --list.
When a hook fails
A hook never slows down or breaks what the person is doing. The event is saved with the change (a sign-up, a payment) and the hook runs moments later in the background. If the change fails or rolls back, the event is never saved and no hook runs.
A hook that throws, or runs past its time limit (30 seconds unless you set timeoutMs, up to 5 minutes), is tried 8 times in all, waiting 1 minute, 5 minutes, 30 minutes, 2 hours, 5 hours, 8 hours and 10 hours: about a day, the same as webhooks. Then it's marked Failed.
Because of retries, a hook can run more than once for the same event. Use ctx.event.id to skip work you've already done, for example as the idempotency key you send to another service. A time limit stops the waiting, not your code: a hook that ignores ctx.signal keeps going, and its retry can start while it's still running, so pass the signal to fetch and anything else that takes one. With more than one server running, each hook runs for each event once at a time.
Watch the runs
Admin → Developers lists every hook by event, with its time limit, its last run and how many failed in the last 7 days. Runs lists the latest, newest first, as Running, Succeeded, Waiting, Retrying or Failed; filter them by event or status.
Open a run to see the payload and every attempt, newest first, with how long it took, its error and the top of the stack. Retry now runs a failed run again straight away. Send a test event sends an event's sample payload to its hooks, marked Test, and tries it once.
Only admins see payloads and errors, retry runs and send tests. Viewers see the hooks and runs. Runs and events are kept for 30 days.
Replay an event
The Delivery log in Admin → Developers lists the latest events your app raised, whether anything heard them or not. Each one shows what read it: your hooks' runs, the deliveries to your webhooks in Admin → Integrations and the automations that reacted to it, such as the publish notification. Open an event to see each of them with every attempt, and a link to the run, the webhook's own deliveries or the automation.
Replay sends an event again to the hooks registered for it now and the webhooks that got it the first time and still get it, for example after you've fixed a bug, added a hook or fixed a receiver. A webhook you added since doesn't get it. You can replay from the log, from an open event, or from an open run with Replay event.
Each hook gets a new run and each webhook a new delivery, marked Replay, and they're tried like any other (retried if they fail). The first runs and deliveries stay as they were. A webhook gets the same event, with the same id and payload, so a receiver that drops events it has already handled drops it too. Inside a hook, ctx.event.replay is true, and ctx.email.send sends again rather than skipping the email the first run sent. Automations don't run again, and a test event only reaches your hooks. Only admins can replay, and each replay is in the audit log.
Whatever the hooks do happens again, so Replay asks first. It names the hooks that will run and the webhooks that will get the event again, and says that emails go out again and other services are called again. It sends to exactly what it named: if that's changed by the time you confirm, it asks you to look again. Some events happen only once for the same thing: payment.first once per organisation, order.paid once per order. Their hooks may count on running once, and the question says plainly that a replay runs them again anyway. When nothing would get the event again, or it's a form answer you've since deleted, it says so instead.
An event's replays go one at a time: a second is refused while the last one's runs or deliveries are still running or retrying. Each hook and each webhook can get an event 20 times by replay.
Guards: say no before it happens
A guard runs before something is saved and can turn it away. There are two:
beforeSignUp({ email, name, ip, country }), before any new account, by any sign-in method;beforeOrganizationCreate({ name, userId }), before a new organisation.
Return { allow: true }, or { allow: false, message } to refuse. The person sees your message as it is. Someone signing up with Google, GitHub or single sign-on is sent back to the sign-in page, which says that account can't sign up here.
import { defineApp, type Guard } from "../modules/hooks/index.js";
const workEmailsOnly: Guard<"beforeSignUp"> = ({ email }) =>
email.endsWith("@acme.com")
? { allow: true }
: { allow: false, message: "Sign-up is open to Acme staff only." };
export default defineApp({ guards: { beforeSignUp: workEmailsOnly } });
A guard has 5 seconds. If it throws or takes longer, the answer is no, with "Sign-up is paused, try again shortly": a broken gate stays shut. The real error is in Admin → Developers → Guards, with each guard's refusals and failures for the last 7 days. An admin creating a user from the admin panel skips the guard.
Jobs: run your code on a schedule
A job runs on a cron schedule: a nightly clean-up, a weekly report, a sync every few minutes. Add it under jobs:
import { defineApp, type Job } from "../modules/hooks/index.js";
export const nightlyCleanup: Job = {
cron: "0 3 * * *", // every day at 03:00
async run(ctx) {
ctx.logger.info({ due: ctx.job.dueAt }, "Cleaning up");
},
};
export default defineApp({ jobs: { nightlyCleanup } });
The schedule has five fields (minute, hour, day of month, month, day of week) and runs in UTC unless you set timeZone: "Europe/London" or another time zone. A job gets the same ctx.db, ctx.logger, ctx.email.send, ctx.track, ctx.entitlements and ctx.signal as a hook, and ctx.job with its name, runId, dueAt (the time it was due) and manual.
- Once, however many servers. With more than one server running, each due time runs on one of them only.
- Failures wait for the next time. A job that throws or runs past its time limit (30 seconds unless you set
timeoutMs, up to 5 minutes) is logged with its error and runs again at its next due time, not sooner. - A time limit stops the waiting, not your code. A job past its time limit is marked Timed out, but code that ignores
ctx.signalkeeps going. Until it ends, the job stays held and its run shows Still going, so neither its schedule nor Run now starts a second copy. The hold lasts at most a minute past the time limit. Code still going after that can overlap the job's next run, so pass the signal tofetchand stop when it fires. - Still going at its next due time. A job still running when it falls due again runs once more, late, as soon as it finishes. If several due times passed meanwhile, that's still one run.
- Missed while everything was down. If every server was down when a job fell due, it runs once when the first one starts, however many times it was missed, then carries on with its schedule.
- Cut off by a deploy. When a server shuts down, a job still running gets 7 seconds to finish. Then
ctx.signalfires and the run is marked Failed. That due time isn't run again: the job runs at its next one. - A new job waits for its first time. Adding a job doesn't run it straight away; Run now does. A job you remove and later add back with the same schedule is different. The database still has the due time it was waiting for, so if that time has passed, it runs at once.
- Daylight saving. In a time zone with daylight saving, a daily time the clocks skip (01:30 in London when they go forward) runs when the gap ends, at 02:00. A time that happens twice when they go back runs once, the first time. Hourly and every-few-minutes schedules keep real time, so an hourly job still runs every 60 minutes. With UTC, the default, none of this happens.
- Changing a schedule during a deploy. Each server runs the schedule in its own code. While old and new servers run side by side, a server whose schedule isn't the one in the database leaves the job alone, and Admin → Developers shows a warning instead of the next run. A server that starts with a new schedule writes it to the database straight away, starting from its next due time. A server already running writes its own schedule back once the other has been there for 5 minutes, so a server restarted mid-deploy can't stop a job for good.
pnpm jobs:runnever changes a schedule.
Admin → Developers → Jobs shows each job's schedule in plain words ("At 03:00 (UTC)"), when it runs next (or a warning while the database has another server's schedule), its last run and how many failed in the last 7 days. Job runs lists the latest runs with how long each took and, for admins, the error and stack of a failed one. Run now runs a job once straight away, marked Manual, without changing its schedule. A job that's already running, or still going past its time limit, isn't started twice. Only admins can run a job now; viewers see the jobs and runs.
Routes: your own API
Add your own API endpoints under /api/app. They're listed in the API reference under App, and their input is checked before your code runs:
import { z } from "zod";
import { type AppRoutes, appRoute, json, requireEntitlement } from "../modules/hooks/index.js";
export const notes: AppRoutes = (routes) =>
routes.openapi(
appRoute({
method: "post",
path: "/notes",
middleware: [requireEntitlement("apiAccess")] as const,
request: { body: { required: true, content: json(z.object({ title: z.string().max(80) })) } },
responses: {
200: { description: "The note", content: json(z.object({ title: z.string() })) },
},
}),
(c) => c.json({ title: c.req.valid("json").title }, 200),
);
export default defineApp({ routes: [notes] });
Routes take the signed-in person's session cookie, so call them from your own web app. Personal access tokens are for MCP only: a request with one counts as signed out. That includes requireEntitlement("apiAccess") above, which checks the plan of whoever is signed in.
Three helpers decide who may call a route, all checked on the server:
requireUser | Signed in. c.var.user is who |
requireAdmin | Someone who opens the admin panel, by their role; viewers only for reads. Changes follow the admin panel's rules: they need a passkey sign-in in the last 15 minutes (unless ADMIN_PASSKEY_STEP_UP=off), and each one is in the audit log |
requireEntitlement(feature) | A member of their active organisation, whose plan includes the feature (apiAccess, prioritySupport, auditLog). c.var.organizationId and c.var.entitlements say which and what |
Someone signed out gets 401; someone without the role, the organisation or the plan gets 403 (UPGRADE_REQUIRED for the plan, PASSKEY_REQUIRED or PASSKEY_SETUP_REQUIRED for an admin's change without a recent passkey). Every route can use c.var.db and c.var.logger.
For a route anyone can call, rateLimit({ limit: 20, windowMs: 60_000 }) in middleware caps how often one address may call it, and answers 429 past that. Each server keeps its own count.
Tools: your own tools for AI agents
Give the agents you connect (Claude, Cursor, or the browser's own agent) tools of your own, beside the app's. An agent connected over MCP with a personal access token, or using WebMCP in the browser, sees them in its list and calls them like any other:
import { z } from "zod";
import { defineApp, defineTool, ToolError } from "../modules/hooks/index.js";
export const openTickets = defineTool({
name: "app_open_tickets",
title: "List open tickets",
description: "The support tickets still open for a customer, newest first.",
audience: "admin",
input: z.object({ email: z.email() }).strict(),
annotations: { readOnlyHint: true, destructiveHint: false },
async run({ email }, ctx) {
const tickets = await findOpenTickets(ctx.db, email);
if (!tickets) throw new ToolError("NOT_FOUND", "No customer has that email");
return { tickets };
},
});
export default defineApp({ tools: [openTickets] });
- Name it
app_and then snake_case, likeapp_open_tickets. Your tools can never take the name of one of ours, so an update never changes what yours do. The server won't start if two clash, and says which. - The audience decides who sees and calls it:
publicfor anyone,userfor anyone signed in,adminfor admins (and viewers, for a tool that only reads). An agent with a personal access token acts as the person who made it, with their role. Someone signed out getsUNAUTHORIZED, someone without the role getsFORBIDDEN, and the tool never runs. A tool that writes can't bepublic: each write is audited as the person who made it, so the server won't start with one, and says which. - The input is checked first. An agent that sends something your zod schema refuses gets
INVALID_INPUTwith what was wrong, and yourrunnever sees it. Describe each field with.describe()so the agent knows what to send. - Say whether it only reads. A tool with
readOnlyHint: trueis on straight away. One that writes stays off until an admin turns it on in Admin → Agents, where they can also have each call wait for their approval. An approved call runs as the person who asked, in the organisation they asked from, checked again when it's approved: if they've been banned, lost the role or left that organisation since, it fails and doesn't run. Every call is in the agents' call log, and each write that goes through is in the audit log (with who approved it, if anyone did). - Errors stay yours. Throw
ToolErrorwithINVALID_INPUT,FORBIDDEN,NOT_FOUNDorCONFLICTand a message for the agent. Anything else, anHTTPExceptiontoo, reaches the agent as "The tool could not complete", with the real error and stack in your server's log, once. So does a result JSON can't hold, like a BigInt: return plain data. - Mind the time limit. A tool gets 30 seconds unless you set
timeoutMs(up to 5 minutes); passctx.signaltofetch. Your code can't be stopped, so past the limit a tool that only reads tells the agent to try again, but one that writes answersOUTCOME_UNKNOWN: it may still finish, and the agent is told to check before calling again. Your log says how it ended, and a write that lands late is still audited.
run gets the checked input and:
ctx.user | Who's calling, with their role (null only for a public tool called signed out) |
ctx.organizationId | The organisation they act in: their active one while they're still a member of it, otherwise the first they joined (a personal access token has no active one), or null |
ctx.requireEntitlement(feature) | Refuses unless that organisation's plan includes the feature; returns { organizationId, entitlements } |
ctx.db, ctx.logger, ctx.entitlements(organizationId), ctx.signal | As a hook's |
Admin → Developers → Agent tools lists your tools with who may call each, whether it reads or writes, and whether it's on.
Blocks: your own blocks for the page editor
Add a block of your own to the page editor: a React component and a zod schema of its props. It shows up in the editor's Insert tab under Your blocks, gets a Style panel made from the schema, and renders on the server like ours, so search engines see it. Define it in packages/contracts/src/app/blocks.ts:
export const banner = defineAppBlock({
name: "app_banner",
title: "Banner",
description: "A one-line announcement with a link.",
props: z.object({
text: z.string().max(120),
href: z.string().default("/").meta({ field: "href" }),
tone: z.enum(["light", "dark"]).default("light"),
}),
example: { text: "We're live on Product Hunt" },
});
export const appBlocks = [quote, banner] as const;
And draw it in apps/web/src/app/blocks.tsx, under the same name:
export const appBlockViews: AppBlockViews = {
app_quote: Quote,
app_banner: ({ text, href, tone }) => <Banner href={href} dark={tone === "dark"} text={text} />,
};
TypeScript makes you add a view for every block, and gives each view its block's props.
- Name it
app_and then snake_case, likeapp_banner. Our blocks never start withapp_, so an update never clashes with yours. - The props make the Style panel. Text is a one-line field;
.meta({ field: "multiline" }),"markdown","href","image"or"icon"give it a box with line breaks, Markdown, a link, an image (with upload and the media library) or one of the site's icons. Numbers keep to the schema's.min()and.max()and round for.int().z.boolean()is a switch,z.enuma choice, andz.array(z.object({ ... }))a list of items with its own fields (.max()limits it). A field's label is the prop's name in sentence case, or.meta({ title: "Stars" }). - The example is what Insert adds. Without one, every prop needs a default or
.optional(). - Every save is checked against the schema. A page that holds props the schema refuses won't save until they're fixed, and the editor says which prop and why; link and image addresses must start with https://, /, mailto: or #. So give a prop you add later a default, or pages already using the block need someone to fill it in. A page saved before a change keeps showing, without that block, until it's fixed.
- Taking a block out of code doesn't break a page. Its layers stay, the editor says it's gone, visitors see nothing in its place, and it's back, props and all, when the block is.
- A mistake in a block stops the build, with the block's name: a bad name, two alike, a missing title, a prop type the panel can't edit, or an example that doesn't fit.
Each block is a section of its own: editors can move it, space it and hide it on a screen size. Agents find your blocks with list_blocks (the props as JSON Schema, and the example) and can use them in import_page. Admin → Developers → Page-editor blocks lists each with its props and the pages using it.
What goes to PostHog
With PostHog set up and sending turned on, MCP analytics sends each agent's tool call to PostHog too. analytics.beforeSend sees each event before it leaves, so you can take out a property or keep an event back:
export default defineApp({
analytics: {
beforeSend(event) {
if (event.properties.$mcp_tool_name === "app_open_tickets") return null;
delete event.properties.$mcp_parameters;
return event;
},
},
});
- Return the event, changed or not, or
nullto drop it. It may beasync. - It has 50 ms. One that throws, takes longer or returns something else drops the event, and says so once in your server's log. The event is never sent as it was, so a check that fails can't let through what it was meant to remove.
- It never touches the call. The call is in your own log before
beforeSendruns, and sending happens in the background, so the agent never waits for it. - Keep it quick. Work that doesn't
awaitruns on the server's one thread: while it runs, nothing else does. A slow loop or regex holds up every request (the event is still dropped), so keep it to a property or two andawaitanything slow.
The event has event (like $mcp_tool_call), distinctId (the person's id, or a hashed key for someone signed out, never an email) and PostHog's $mcp_* properties.
Try it on your machine
Run an event's hooks against your local database, in the foreground:
pnpm hooks:fire user.signed_up
It sends the event's sample payload, or your own with --payload answer.json, prints how each hook went, and marks the run as a test in Admin → Developers.
Run a job now, in the foreground, the same way:
pnpm jobs:run nightlyCleanup
It prints how the job went, with its error and stack if it failed, and the run shows in Admin → Developers marked Manual. pnpm jobs:run --list lists your jobs and their schedules.
In your own tests, fireAppEvent runs a hook without a server and records the emails it would send:
import { fireAppEvent } from "../modules/hooks/index.js";
import app from "./index.js";
const fired = await fireAppEvent(app, "user.signed_up", {
user: { id: "u_1", email: "ada@example.com", name: "Ada", emailVerified: false, createdAt: new Date().toISOString() },
});
// fired.emails, fired.tracked and fired.results say what happened.
Pass { db } for a hook that reads the database.
callAppTool calls one of your tools the same way, as a pretend user, with the same checks an agent's call gets:
import { callAppTool } from "../modules/hooks/index.js";
import app from "./index.js";
const asAdmin = await callAppTool(app, "app_open_tickets", { email: "ada@example.com" }, {
user: { role: "admin" },
db,
});
// { ok: true, result } or { ok: false, code, message, status }
const asMember = await callAppTool(app, "app_open_tickets", { email: "ada@example.com" });
// { ok: false, code: "FORBIDDEN", ... }: a member isn't an admin
The pretend user is a member unless you say otherwise; user: null calls it signed out, and organizationId sets their active organisation (with db, it counts only if they're a member of it there, as in the app). An error your tool throws, other than a ToolError, fails the test with the real error.
Coding agents can read the events, the hooks, the jobs and their runs through five read-only tools: list_app_events, list_hooks, hook_runs, list_jobs and job_runs; see Agents and the API.
Something unclear or missing? Ask us and we'll answer, then fix the page.



