Functions
A function is a TypeScript file in functions/ that runs on Deno and answers HTTP at /functions/v1/<name>. It receives a standard Request and returns a standard Response.
Where functions live
Functions sit in functions/ at the project root. Each one is either a folder with an index.ts or a single .ts file. The name becomes the route.
| File | Route |
|---|---|
functions/send-invite/index.ts | /functions/v1/send-invite |
functions/ping.ts | /functions/v1/ping |
functions/_shared/email.ts | none: shared code |
- Names starting with
_or.are skipped, sofunctions/_shared/holds code every function can import with a relative path. .d.tsfiles are skipped._logsis reserved by the worker, and the gateway refuses/functions/v1/hooksfrom outside, so do not use either name.
To use another directory, set functions.path in supatype.config.ts. It resolves against the project root.
import { defineConfig } from "@supatype/cli"
export default defineConfig({ project: { name: "my-app" }, database: { provider: "docker" }, server: { mode: "dev" }, app: { mode: "none" }, functions: { path: "functions", },})Runtime
Functions run on Deno. Locally the CLI downloads Deno on first use. On a self-hosted stack they run in the functions-worker container, and supatype-server proxies /functions/v1 to it.
The worker loads every function once at startup and serves them from one process. Invocations run concurrently: nothing per call is written to the process environment, so one slow function does not block another.
The CLI writes three files to help your editor: functions/deno.d.ts, functions/tsconfig.json and functions/_shared/context.ts. It also adds functions to the root tsconfig.json exclude list, so your app’s type check skips Deno code. context.ts is rewritten by init, functions new, push and dev, so do not edit it.
Write a function
Scaffold one with the CLI:
$ npx supatype functions new greetA function default-exports a handler. It gets the request and a context object, and returns a Response. There is no Supatype package to import at runtime and no client injected for you.
import type { FunctionContext } from "../_shared/context.ts"
export default async function handler(req: Request, ctx: FunctionContext): Promise<Response> { if (req.method !== "POST") { return Response.json({ message: "Use POST" }, { status: 405 }) } const { name } = (await req.json()) as { name?: string } return Response.json({ greeting: `Hello, ${name ?? "there"}`, region: ctx.region })}A thrown error becomes a 500 with { "error": "function_error", "message": "..." }. An unknown name returns 404 with the list of available functions.
The context object
The second argument carries what the function needs about its call and its project.
| Field | What it holds |
|---|---|
executionId | A UUID unique to this call. Every log line the call writes carries it. |
functionName | The route being served. |
url | The project’s API base URL, reachable from inside the function. |
anonKey | The project’s anon key. |
serviceRoleKey | Only present when the project grants this function the service role. See Service role. |
dbUrl | A direct database URL, only when the deployment provides one. |
region | local unless the deployment sets a region. |
env | Your variables from the function env files. See Environment and secrets. |
Who is calling
The client sends the signed-in user’s access token in the Authorization header. The function receives that header as it was sent. Nothing checks it for you, so a function that cares who is calling must ask auth.
import type { FunctionContext } from "../_shared/context.ts"
export default async function handler(req: Request, ctx: FunctionContext): Promise<Response> { const authorization = req.headers.get("Authorization") if (!authorization) return Response.json({ message: "Sign in first" }, { status: 401 })
const headers = { Authorization: authorization, apikey: ctx.anonKey } const res = await fetch(`${ctx.url}/auth/v1/user`, { headers }) if (!res.ok) return Response.json({ message: "Not signed in" }, { status: 401 })
const user = (await res.json()) as { id: string; email?: string } // Forward the same headers to REST and the user's access rules apply. const posts = await fetch(`${ctx.url}/rest/v1/post?select=title`, { headers }) return Response.json({ id: user.id, posts: await posts.json() })}Forwarding the caller’s token is the safe default: the database sees the user, not the function, and every access rule still applies.
Do not decode the token yourself to read a role. Until its signature is checked, anyone can send a payload that says "role": "admin". Ask /auth/v1/user, as above, which checks it. supatype.auth.getUser() on a client you create inside a function does not help here: it reads that client’s own stored session, not the request’s token, so it returns no user.
Service role
A function is a public endpoint. By default it does not receive the service-role key, which reads and writes past every access rule. The worker removes the key from the environment before any function is imported, so Deno.env cannot reach it either.
To give a function the key, name it in functions.serviceRole. It then appears as ctx.serviceRoleKey.
export default defineConfig({ // ... functions: { serviceRole: ["send-invite"], },})supatype push refuses a name that matches no function, so a typo cannot silently grant nothing. supatype doctor lists the current grants.
Local dev applies the same list, so a function that relies on the key without being named fails there first. Under supatype functions serve no function receives the key unless SUPATYPE_SERVICE_ROLE_KEY is set in your shell, and then only the functions the list names.
Environment and secrets
Variables for functions live in env files inside the functions directory:
functions/.env.localis shared by every function.functions/.env.<name>.localapplies to one function and overrides the shared file.
Read them from ctx.env. The files are read on each call, so a changed value takes effect without a restart. Keep them out of git.
Every value set with supatype functions env set, in .env.local or in .env.<name>.local arrives in ctx.env on each call, never in Deno.env: Deno.env is the worker’s one process environment, shared by every call running at the same time, so a value put there for one function would reach every other. Deno.env.get("RESEND_API_KEY") finds nothing.
Deno.env holds only the worker’s own settings (such as SUPATYPE_URL, SUPATYPE_PUBLIC_URL and SUPATYPE_ANON_KEY, which also arrive as ctx fields), Deno’s DENO_* variables and what the operating system needs, such as PATH and the temporary directory. Before any function is imported the worker deletes everything else, so the stack’s secrets and the variables in your shell never reach function code, under supatype dev and supatype functions serve as on a deployed stack. A self-hosted worker also keeps STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET and SITE_URL when Compose passes them.
$ npx supatype functions env set RESEND_API_KEY=re_123$ npx supatype functions env list$ npx supatype functions env unset RESEND_API_KEYOn a project that is not linked, these commands edit functions/.env.local. list masks the values.
Add --function <name> to list, set or unset to work on one function’s own values: on a linked project they go to that function, and on a project that is not linked they edit functions/.env.<name>.local. A function’s own value overrides a shared one with the same name.
$ npx supatype functions env set RESEND_API_KEY=re_456 --function send-invite$ npx supatype functions env list --function send-invite$ npx supatype functions env unset RESEND_API_KEY --function send-inviteOn Supatype Cloud the per-function routes need a control plane that serves /projects/<ref>/functions/<name>/env.
const apiKey = ctx.env["RESEND_API_KEY"]if (!apiKey) return Response.json({ message: "RESEND_API_KEY is not set" }, { status: 500 })Call a function
From your app, use functions.invoke on the client. It posts JSON to /functions/v1/<name> with the user’s token and returns { data, error }. A non-2xx response becomes error, using the message field from the body when there is one.
const { data, error } = await supatype.functions.invoke("greet", { body: { name: "Alex" } })invoke also takes method (default POST) and headers. A JSON response is parsed and anything else comes back as text. On a 401 the client refreshes the session once and retries. More in Client: Functions.
Local development
supatype dev serves functions through the same gateway as the rest of the API when a functions directory exists. You do not run anything else.
With the Native provider, Deno runs in the project folder, so a project with a package.json resolves npm: imports from its node_modules. Install what a function imports, such as npm install postgres for npm:postgres. Without it the call fails with Could not find a matching package for 'npm:postgres' in the node_modules directory. Do not turn on nodeModulesDir: "auto" in a deno.json there: Deno then rewrites node_modules, and supatype.config.ts stops loading.
To run functions on their own, with Deno watching for changes:
$ npx supatype functions serve$ npx supatype functions invoke greet --local --data '{"name":"Alex"}'serve listens on port 18472 by default; change it with --port. It loads functions/.env.local unless you pass --env-file. invoke sends a POST, prints the status and the response, and gives up after 30 seconds. It exits 1 when the function answers with a status of 400 or above, so a script can tell a failed call (a 404 for a function that does not exist, say) from one that worked. --auth adds a test token to the request, on this machine only: on a Cloud link it is refused, because it would send your Supatype Cloud session, which can manage your projects, to the function, and on a self-hosted link it is refused because there is no user token to send. Call a deployed function with a signed-in user’s access token instead. With --local, or when no Cloud project is linked, invoke calls a running serve on --port (18472 by default) when one answers, and the project’s dev API otherwise.
Self-host
The self-host Compose file always includes a functions-worker service, built from the supatype/functions-worker image. It mounts the project read-only and serves functions/ from it. There is no bundle or upload step: the files on disk are what runs.
The worker reads code once at startup, so restart it after changing a function:
$ docker compose -p supatype-<project> -f .supatype/self-host/docker-compose.yml restart functions-worker<project> is your project name from supatype.config.ts in lower case, with spaces and other symbols replaced by -. supatype self-host compose restart functions-worker does the same and finds the project name for you. Env file changes do not need a restart.
On an unlinked project with a self-host Compose file, supatype functions deploy uploads nothing. It lists the functions it found on disk and prints that restart command.
The worker gets the anon and service-role keys from the stack. To give functions a database connection, set SUPATYPE_FUNCTIONS_DB_URL; it appears as ctx.dbUrl. It is off by default because a direct connection is not a request through the API: model hooks do not run, and row rules and field masking apply only for the role the URL names. A superuser or BYPASSRLS role (the admin role, service_role) skips both, so point it at a login role that is neither, granted only what your functions need. The database name at the end of the URL is the value of POSTGRES_DB in your .env.
The worker runs Deno 2.9.8. Postgres drivers verified against a live database on it: npm:postgres (latest), npm:postgres@3.4.5 and npm:pg. npm:postgres 4.0 and later does not run on Deno before 2.8, where it fails with Not implemented: LibuvStreamWrap.prototype.useUserBuffer or socket._handle.useUserBuffer is not a function. Every 3.4 release runs there; a stack on an older worker image should pin npm:postgres@3.4.5.
Function logs are JSON lines on the container’s output, each with the call’s request_id, status and duration:
$ npx supatype self-host compose logs --service functions-workerUnder supatype dev without Docker (native dev), functions run inside the server process, so there is no worker container to read. supatype dev sets SUPATYPE_FUNCTIONS_LOG_TO_STDOUT, and the server then prints each line a function writes to the terminal that runs dev, prefixed with the function name, for example [hello] got a request. Lines that name no function, such as Deno’s own errors, are prefixed [deno]. The same lines stay in Studio’s function logs. A server that does not have the variable set, such as Cloud or a Compose stack, prints nothing extra.
Tools for agents
A function can be a tool for your app’s MCP server. Declare the tool in your schema with function set to the function’s directory. The CLI then writes functions/_supatype/mcp-tools.ts on every push and supatype dev, with an input type for each tool and the mcpTool() helper. Do not edit that file. It is removed when no tool is backed by a function.
// docs:no-check (imports the file the CLI generates into your project)import { mcpTool, type SummariseWeekInput } from "../_supatype/mcp-tools.ts"
export default mcpTool<SummariseWeekInput>(async (input, caller) => { const since = input.since ?? new Date(Date.now() - 7 * 86_400_000).toISOString() return { user: caller.id, canWrite: caller.scopes.includes("mcp:write"), since }})mcpTool() returns the handler the worker expects. It reads the JSON body as the input, finds out who is calling, calls your handler, and answers 200 with what it returns as JSON. A thrown error becomes 500 with { "error": "..." }, and a body that is not JSON is 400.
It finds the caller the way Who is calling says to: it asks the auth server. It sends the request’s bearer, the short-lived token the server made for this call, to /auth/v1/user. If the auth server refuses it, the answer is 401 and your handler does not run. Only after the auth server accepts the token does the helper read the client and the scopes from it. A function tool only answers calls that come through the app MCP: the token the server makes for a call names the tool, and a call made straight to the function with a person’s session token, or with a token made for another tool, is refused with 403 and your handler does not run. The handler’s second argument is the result: id, email, clientId, scopes and tool, the name of the tool being called, which arrives in the X-Supatype-Mcp-Tool header. Nothing is signed for the function to check, because the functions worker never holds the project’s signing secret. To read or write data as the person, forward the request’s Authorization header to the API, as in Who is calling, and the person’s access rules apply to what the tool reads and writes.
Model hooks
A model hook is a handler the API server calls around a write to one model: to check it, change it, refuse it, or react once it has happened. Hooks run on the same Deno worker as functions, but they are not public endpoints. They live in their own hooks/ directory at the project root, the worker serves them under a hooks/ route, and the gateway refuses that route from outside.
Triggers
| Key | Runs | Can |
|---|---|---|
beforeChange | Before an insert or update reaches Postgres | Let it through, replace the rows or the patch, or refuse it |
afterChange | After an insert or update commits, from any writer | React only. It cannot change or undo the write |
beforeDelete | Before a delete reaches Postgres | Let it through or refuse it |
afterDelete | After a delete commits, from any writer | React only |
before* hooks fire on writes to /rest/v1/<table>: POST and PUT are inserts, PATCH is an update, DELETE is a delete. That covers the client’s insert, upsert, update and delete, including calls made with the service-role key. RPC calls, direct SQL, seeds and migrations do not fire them.
after* hooks read committed changes from the database’s change log instead, so they fire for every writer: the API, Studio, SQL and functions. Seeds are the exception. On a database without logical replication they fall back to writes through the API only; supatype db check and supatype doctor say which you have.
Declare a hook
Name the handler in the model’s second argument. A string is the handler’s directory name; an object adds options.
export type Post = Model<{ id: UUID title: string // ...}, { // access, versions, ... hooks: { beforeChange: "check-post" afterChange: { function: "notify-post"; timeout: 5000 } }}>| Option | Meaning |
|---|---|
function | The directory under hooks/. |
timeout | Milliseconds to wait for an answer. Default 2000. |
onUnavailable | What to do when the hook does not answer: a timeout, a connection failure, a 5xx, a thrown error or an unreadable body. "reject" refuses the write, "log" lets it through and logs. Defaults to "reject" for before* hooks and "log" for after* hooks. |
columns | after* hooks only. "safe", the default, leaves every column with a field read rule out of the hook’s rows; "all" keeps them. |
supatype push refuses a schema whose hook names a directory with no index.ts, so a typo cannot leave a hook that never fires.
Write the handler
$ npx supatype hooks new check-post$ npx supatype hooks listhooks new creates hooks/<name>/index.ts. When a model already names it, the file is set up for that event; otherwise the command prints the line to add to the model. hooks list prints each Model.event with its handler and marks any whose handler is missing. supatype doctor reports the same.
Handlers import their types from hooks/_supatype/hooks.ts, which push, dev and generate write from your schema. Until the first push it does not exist, so a new handler will not compile yet. Do not edit it.
import { hook, type BeforeChange } from "../_supatype/hooks.ts"
const checkPost: BeforeChange<"post"> = async (ctx) => { if (ctx.operation === "insert") { if (ctx.rows.some((row) => row.title.trim() === "")) return { reject: "A post needs a title" } return { rows: ctx.rows.map((row) => ({ ...row, title: row.title.trim() })) } } if (ctx.patch.title !== undefined && ctx.patch.title.trim() === "") { return { reject: { message: "A post needs a title", status: 422, code: "empty_title" } } } return {}}
export default hook(checkPost)The type argument is the table name. BeforeChange, AfterChange, BeforeDelete and AfterDelete type the context from the model, and only tables that declare a hook are accepted.
| Context field | What it holds |
|---|---|
table, operation | The table and insert, update or delete. |
user | sub, role and email from the caller’s verified token, or null for an anonymous caller and for an after* hook on a write made outside the API. |
requestId | Matches the request in the server logs. |
rows | An insert’s rows, always an array. On afterChange, every row one transaction wrote to the table with that operation, always present and in the JSON shape PostgREST returns, so a bulk insert is one call. |
old | On an afterChange update and on afterDelete: the rows as they were before. On an update, old[i] is rows[i] as it was. |
deliveryId | On after* hooks: commitLSN:schema.table:operation, the same on every delivery of one call. Delivery is at least once, so keep the ids you have handled if a repeat would do harm. |
patch | An update’s changes. |
filter | The request’s filter on an update or delete, such as id=eq.42. A hook cannot change it. |
previous() | Before an update or delete: fetches the rows about to change, up to 100, with truncated: true when there were more. They come back as stored, without field masking, so do not copy them into a refusal message. |
A before* handler returns {} to let the write through. beforeChange can return { rows } for an insert or { patch } for an update to replace what is written. { reject } refuses the write: the caller gets your message with status 422, or the 4xx status you set. A thrown error is not a refusal: it counts as the hook not answering, and onUnavailable decides.
To keep a model’s whole lifecycle in one directory, point several events at the same name and export hooks({ beforeChange: checkPost, afterChange: notify }) instead of hook(...). An event with no handler in that map lets the write through.
How hooks run
- The server reads the whole request body before any hook runs. A body over 1 MiB on a write to a hooked table is refused, rather than written without the hook.
- An
after*hook runs once the write has committed. A delivery it does not answer is retried with backoff, then logged, and never reaches the caller. Its rows leave out restricted columns unless it declarescolumns: "all". - A hook may write through the API, and those writes fire hooks too. A chain more than four hooks deep is refused with status
508, so a hook that writes to its own table cannot loop forever. - On a Docker stack the
functions-workercontainer mountshooks/next tofunctions/. Whensupatype devruns on Docker, the worker restarts when a hook file changes. On a self-hosted stack, restart it after changing a hook, as for functions.
Limits
- The gateway waits up to two minutes for a function to start responding.
- The self-host worker sets no memory or CPU cap per function. Set container limits in Compose if you need them.
- Function names and bodies are not typed on the client.