Your own API functions
The REST API covers reading and writing records. For anything else you write a function: a webhook from a payment provider, a button that makes three writes and then texts the customer, an endpoint for another app. Each function is one file in the project’s functions/ folder, served at /api/functions/<name>.
If you have used Supabase Edge Functions, this will feel familiar. A function is a Web-standard handler that takes a Request and returns a Response. Only signed-in callers get in unless the function says otherwise. It has a data client that acts as the caller, and the raw database for privileged work.
The examples below come from Pip’s bike shop (see From a table to an admin). The repository compiles and tests every one of them.
A first function
Section titled “A first function”import { defineFunction } from '@protobase/server'
// GET /api/functions/hello: who is calling. Only a signed-in user gets here; anyone else gets a 401 problem.export default defineFunction((_request, { session }) => Response.json({ message: `Hello, ${session.user.id}`, roles: session.user.roles }),)protobase dev serves it at /api/functions/hello of the address it prints, such as http://localhost:23456/api/functions/hello. A change reloads it on the next request, and a new file appears after the next change inside the project. protobase build bundles the functions into the deploy bundle, and protobase serve serves them the same way. Call it with a token:
curl -H "Authorization: Bearer $(protobase token [email protected])" http://localhost:23456/api/functions/hello# {"message":"Hello, 9f3c…","roles":["admin"]}curl -i http://localhost:23456/api/functions/hello# HTTP/1.1 401 Unauthorized, an application/problem+json body like every other refusalThe app’s own authenticate checks the token, the same one that guards the REST API, so a function needs no auth code of its own. A call without a valid token is the usual 401 problem, and the handler never runs.
Files and names
Section titled “Files and names”- One function per file:
functions/<name>.ts, orfunctions/<name>/index.tsfor a function of several files. The name is the URL segment, so it uses letters, digits,-and_. - Not functions: files and folders starting with
_(shared code, such asfunctions/_shared/), dotfiles,*.test.ts,*.spec.tsand*.d.ts. A folder without anindex.tsis an error that says so. - The default export is
defineFunction(...)from@protobase/server, a bare(request, context)handler, or a Hono app. The last two need a signed-in caller. - Any method reaches the function, and so does any path below its name. The request’s path is the part after
/api/functions/<name>:/for the function itself,/42/advancefor/api/functions/workshop/42/advance. The query string and the body are passed through unchanged. - Only the folder:
protobase.config.tsnames no functions; they are found infunctions/. The functions of an extension’sfunctions/folder are kept, and a name used by two folders is an error that names both.
The context
Section titled “The context”The second argument of a handler (c.env in a Hono app):
session |
The caller: { user: { id, roles }, tenant? }, from the app’s authenticate. |
records |
The app’s resources, acting as the caller: list, get, create, update, delete, softDeleteField. |
db |
The Kysely instance itself. It skips every access rule, row filter and the tenant scope of .tenant resources, but keeps the organization’s tables to the caller’s organization. |
caller() |
Resolves to { session, records }. Public functions use it to ask for a caller when they need one. |
decryptField(resource, key, field) |
An encrypted field’s value, skipping access rules like db; each read is audited, naming the function and the caller. |
acceptWebSocket(events) |
Answers a WebSocket upgrade with a socket; return its response. See WebSockets. |
calls.join(member) |
The events of a member’s socket in a call, for acceptWebSocket. See Calls. |
channels |
channels.broadcast({ resource, key, event, payload }) sends to whoever is on a record’s channel, as the server. |
live |
live.refresh({ user }) tells a person’s open pages to read again once their access changed. See Refreshing access. |
name |
The function’s name. |
A public function has only db, caller(), acceptWebSocket, calls, channels, live and name.
The organization’s tables
Section titled “The organization’s tables”With organizations on, the tables of the auth store whose rows each belong to one organization, member, invitation and personal_access_token under the names the app gives them, show db only the caller’s organization, the one their session works in. While organizations are off after being on, the tables they left show db only the default organization, for a session of it, whose tenant is its id; a session of another tenant, or of none, sees none of their rows. A read, update or delete of one gets organization_id = <the organization> in the select, update or delete that reads the table: in its where, or for a joined table in the join’s on, so a left join keeps its other rows. Subqueries, common table expressions and exists filter their own tables, and a name a common table expression takes is not the table. An insert writes the organization, and one naming another organization, or an update moving a row to one, is refused with a ScopeRefused error before it reaches the database; so is an upsert’s update of a row of another organization, which it leaves as it is. A table of the project’s own with the same name in another schema is never taken for the store’s. A right or full join, or a merge, of one of these tables throws, as the scope cannot keep it to the organization.
A job works in the organization of the db that enqueued it, such as a function’s. A public function, a function called at /api/sb/functions/v1, a webhook’s call of a function, a recurring job, and a job enqueued with db.unscoped(...), a plain database or from SQL work in no organization: their db reads no row of these tables and writes none. Work that means every organization’s rows says so, with a reason for whoever reviews it:
const everyone = await db.unscoped('the nightly report counts members of every organization').selectFrom('auth.member').select(({ fn }) => fn.countAll().as('members')).executeTakeFirstOrThrow()Raw SQL names these tables through scoped(table) for the organization’s rows, or unscoped(reason, table) for every organization’s, both from @protobase/query. Naming one with sql.table or sql.id is refused, and db.withoutPlugins() too, as it would drop the scope without a reason:
import { scoped } from '@protobase/query'import { sql } from 'kysely'
const { rows } = await sql`select count(*) as members from ${scoped('auth.member')} as m`.execute(db)scoped(table) runs only on a database that keeps the scope: elsewhere Postgres refuses it as an unknown function. SQL written as plain text, sql.raw, a database view, or Kysely’s CompiledQuery.raw is not seen, so name these tables through the helpers. The .tenant resources of the app’s own tables are not kept to the organization in db: their API and records are.
Transactions
Section titled “Transactions”db.transaction(queries) sends Kysely query builders as one transaction, in one round trip to the database: its begin, every query and the commit go out together, and it resolves to one result per query, { rows, numAffectedRows }, typed by its builder. Either every query applies or none does: the first that fails rolls the whole transaction back, and the call rejects with its error.
const [moved, total] = await db.transaction((q) => [ q.updateTable('stock').set((eb) => ({ count: eb('count', '-', 1) })).where('item_id', '=', itemId).where('count', '>', 0), q.selectFrom('stock').select(({ fn }) => fn.sum('count').as('total')),])if (moved.numAffectedRows === 0n) return new Response('Sold out', { status: 409 })The queries are built up front: the callback gets a database that only builds them, returns them without awaiting, and anything it executes or awaits is refused with an error naming the ways out. A transaction that reads, decides in code and then writes would hold its connection, and a lock, across round trips while the code runs. Write such work as one of these instead:
- One statement, such as an
update … wherethat checks the condition itself, as above, or aninsert … on conflict. - A batch, when the queries do not need each other’s results.
- A stored procedure or a trigger, when the decision needs data the queries read: Postgres makes it next to the data.
- A write that checks an ETag, such as
records.update(resource, key, data, { etag }), which fails with412when the record changed after it was read.
db.transaction().execute(...) cannot be refused yet because moving Protobase’s own interactive transactions to batches is not implemented.Reading and writing records as the caller
Section titled “Reading and writing records as the caller”import { z } from 'zod'import { defineFunction, HttpProblem, readJson } from '@protobase/server'
const Input = z.object({ repairId: z.number().int().positive() })
// POST /api/functions/ready-for-pickup { "repairId": 7 }: the workshop finishes a repair. It reads and writes as the// caller, so a mechanic touches only the repairs their access rules allow, and the repair's validation and write hooks// run as for any other update.export default defineFunction({ roles: ['mechanic', 'desk'] }, async (request, { records }) => { const { repairId } = await readJson(request, Input) const { record: repair, etag } = await records.get('repairs', repairId) if (repair.status !== 'working') { throw new HttpProblem(409, 'not-in-progress', 'Conflict', `Repair ${repair.number} is ${repair.status}, not in the workshop`) } // The ETag makes this fail with 412 when someone changed the repair since it was read. const ready = await records.update('repairs', repairId, { status: 'ready' }, { etag }) const waiting = await records.list('repairs', { filter: `customer_id = ${repair.customer_id} AND status = "ready"`, fields: ['number', 'bike'] }) return Response.json({ repair: ready.record, readyForCustomer: waiting.items.map(({ number, bike }) => ({ number, bike })) })})records takes the same path as the REST API. The caller’s access rules, row filters, field access and tenant scope apply. So do the resource’s validation and the write hooks, and a record the caller may not see is not there:
list(resource, params?) |
A page as GET /api/v1/{resource} gives it: { items, next_page_token, total_size_estimate }. params are filter, order_by, page_size, page_token, fields (an array), count: 'exact' and show_deleted. |
get(resource, key) |
{ record, etag }. A composite key is an array of its parts, or a,b as in a URL. |
create(resource, data) |
{ record, etag } of the new record. |
update(resource, key, data, { etag }?) |
With etag, it fails with 412 when the record changed after it was read. |
delete(resource, key, { etag }?) |
{ record, etag } of the record as it was. It is a soft delete when the resource has one. |
softDeleteField(resource) |
The field a delete sets when the resource has a soft delete, or undefined when a delete removes the record. |
A refusal or a missing record rejects with the problem the REST API would answer, such as 403, 404 or 412. Left uncaught, that problem becomes the function’s response. Each call is its own transaction. Use the batch endpoint when several writes must succeed or fail together.
Checking input
Section titled “Checking input”readJson(request, schema) reads the body and checks it against a schema. It takes any Standard Schema, such as zod 4, Valibot or ArkType. The result is typed. A body that is not JSON is a 400 malformed-json problem. A body the schema refuses is a 400 invalid-body problem with an errors list of { field, message }. Without a schema, readJson(request) only parses the JSON.
defineFunction({ roles: ['mechanic', 'desk'] }, handler) lets in callers with at least one of those roles. defineFunction({ capability: 'vms.update' }, handler) lets in callers whose roles hold all of that capability (roles.holds): *, vms.* or a plain vms.update, but not vms.update.own or a vms.update limited to fields or rows. A wildcard means all of it, so vms.* needs a role that holds vms.* or *. Anyone else gets a 403 function-forbidden problem before the handler runs. Finer rules belong in the resources’ access rules, which records already applies.
In an app with roles (config/roles.ts), a function with neither is closed like a resource without a rule: only callers whose roles hold *, such as admin: ['*'], may call it, unless defaultAccess is allow. A function for everyone signed in says so with its roles. In an app without roles, every signed-in caller may call it. A capability needs the app’s roles, and a function takes roles or capability, not both: the server refuses to start otherwise.
Public functions and webhooks
Section titled “Public functions and webhooks”import { defineFunction, requireEnv, verifySignature } from '@protobase/server'
type PaymentEvent = { type: string; data: { reference: string } }
// POST /api/functions/payment-webhook: the payment provider says a repair is paid. Nobody signs in to send it, so the// function is public and checks the provider's signature instead; with no caller, it writes through the database// directly, past every access rule.export default defineFunction({ public: true }, async (request, { db }) => { const body = await verifySignature(request, { secret: requireEnv('PAYMENTS_WEBHOOK_SECRET'), header: 'x-signature', prefix: 'sha256=' }) const event = JSON.parse(body) as PaymentEvent if (event.type === 'payment.succeeded') { await db.updateTable('shop.repairs').set({ paid: true }).where('number', '=', event.data.reference).execute() } return new Response(null, { status: 204 })}){ public: true } lets anyone call the function. A sender that signs its requests is checked with one of these helpers. Each returns the body as text once the signature matches, and otherwise throws a 401 invalid-signature problem:
verifySignature(request, { secret, header, prefix?, encoding?, hash? })checks an HMAC of the body (hexandSHA-256by default), as GitHub, Shopify and many payment providers sign. GitHub’s is{ header: 'x-hub-signature-256', prefix: 'sha256=' }, and Shopify’s is{ header: 'x-shopify-hmac-sha256', encoding: 'base64' }.verifyStandardWebhook(request, { secret })checks Standard Webhooks signatures, as Supabase Auth hooks, Svix and Resend send them, including the timestamp (5 minutes of tolerance by default).- Stripe ships its own check:
stripe.webhooks.constructEventAsync(await request.text(), request.headers.get('stripe-signature'), secret).
A public function has no caller, so it has no records. Its db skips the tenant scope too, so filter by tenant yourself where it matters, and it sees no row of the organization’s tables. When a function should serve anyone but treat a signed-in caller differently, await context.caller() resolves the caller from the request, or rejects with the 401 problem.
WebSockets
Section titled “WebSockets”A function can answer a WebSocket instead of a request, for a live console, a chat or an agent that keeps one connection open. It returns acceptWebSocket(events):
import { defineFunction, type FunctionSocket } from '@protobase/server'
// Everyone in the workshop chat, in this process.const everyone = new Set<FunctionSocket>()
// /api/functions/workshop-chat, opened as a WebSocket by a signed-in page: each text message goes to everyone in the// chat, with who sent it. Awaiting the sends holds the sender's next message back until everyone has this one.export default defineFunction((_request, { session, acceptWebSocket }) => { let own: FunctionSocket | undefined return acceptWebSocket({ onOpen: (socket) => { own = socket everyone.add(socket) }, onMessage: async (data) => { if (typeof data !== 'string') return await Promise.all([...everyone].map((socket) => socket.send(`${session.user.id}: ${data}`))) }, onClose: () => { if (own) everyone.delete(own) }, })})A page of the app opens it with the browser’s own WebSocket. The session cookie signs it in, so the function sees the signed-in user and their roles, as for a plain call:
const chat = new WebSocket(`${location.origin.replace(/^http/, 'ws')}/api/functions/workshop-chat`)chat.onmessage = (event) => console.log(event.data)chat.onopen = () => chat.send('Truing stand is free')A client that is no browser sends Authorization: Bearer <token> with its upgrade instead. The events:
onOpen(socket) |
The socket is open. |
onMessage(data, socket) |
Text arrives as a string, binary as an ArrayBuffer, byte for byte. Messages come one at a time and in order. |
onClose(code, reason) |
Either side closed it, after the last message. |
recheck() |
Runs every minute while the socket is open, after the framework’s own check. A 401, 403 or 404 problem it throws closes the socket with 1008; any other error is reported and closes it with 1011, as does a check that has not finished a minute later. What it returns is ignored, so refuse by throwing. |
maxMessageBytes |
Not an event: the largest message the socket takes, in bytes, a whole number of at least 1. A larger one closes the socket with 1009 before the server reads it, and onMessage never sees it. |
socket.send(data) takes a string, an ArrayBuffer or a Uint8Array, and socket.close(code?, reason?) closes it. A handler that throws closes the socket with 1011, and the error is reported like any other.
Sockets need @hono/node-server’s upgradeWebSocket, the only upgrade supported, which protobase dev and protobase serve use. A server of your own that passes another host’s upgrade to createAdmin gets sockets that misbehave, since they rely on its send callback and bufferedAmount.
Who may open one
Section titled “Who may open one”- Refusals come before the socket. A caller without a valid session or token gets the usual
401, and one without the function’s roles a403; the handler never runs. The browser only sees a socket that failed to open, since an upgrade’s refusal has a status but no body. - Only the app’s own pages may open a socket with the cookie. An upgrade from a page on any other origin is a
403, so another site cannot borrow a visitor’s session. - While it is open, the framework checks the caller again every minute: their session or token, the function’s roles, and that the user, tenant, organization and roles are unchanged. It does so for a protected function, and for a public one once
caller()resolved. Signing out, a ban, a role taken away, or another active role or organization closes the socket with1008, and a socket opened with a bearer token closes once the token expires. The client opens it again, as who they are now. - The function’s own checks are not repeated, such as whether the caller may still see one record. Pass them as
recheck, which runs right after the framework’s check:
import { defineFunction, notFound } from '@protobase/server'
// /api/functions/repair-watch/7, opened as a WebSocket by a signed-in page: repair 7's status, for as long as the caller// may see the repair. A repair their access rules hide is a 404 and no socket; once it moves out of their sight, such// as to another mechanic, `recheck` rejects with that 404 and the socket closes with 1008 within a minute.export default defineFunction({ roles: ['mechanic', 'desk'] }, async (request, { records, acceptWebSocket }) => { const id = Number(new URL(request.url).pathname.slice(1)) if (!Number.isInteger(id) || id <= 0) throw notFound('Watch a repair at /api/functions/repair-watch/<id>') const { record: repair } = await records.get('repairs', id) return acceptWebSocket({ onOpen: (socket) => socket.send(JSON.stringify({ status: repair.status })), recheck: () => records.get('repairs', id), })})- A plain request to a function that accepts a socket is a
426problem.
Agents and other clients without a cookie
Section titled “Agents and other clients without a cookie”A public function can accept a socket too. One that admits its caller with await caller() is checked again like a protected one. One that checks a credential of its own, for example a host agent’s key in a header, passes recheck to check it again, since the framework cannot.
A page with no session cookie of the app, such as the workshop’s display board on its own origin, gets a short-lived ticket from a plain call with its token and puts it in the socket’s address:
import { createHmac, timingSafeEqual } from 'node:crypto'import { requireEnv } from '@protobase/server'
const lifetimeSeconds = 30
const signature = (payload: string) => createHmac('sha256', requireEnv('TICKET_SECRET')).update(payload).digest('base64url')
// A ticket names a user and when it expires, signed with the app's own secret.export const mintTicket = (userId: string | number) => { const payload = `${userId}.${Math.floor(Date.now() / 1000) + lifetimeSeconds}` return `${payload}.${signature(payload)}`}
// The user a ticket names, or undefined when it is forged or expired.export const ticketUser = (ticket: string) => { const payload = ticket.slice(0, ticket.lastIndexOf('.')) const given = Buffer.from(ticket.slice(payload.length + 1)) const expected = Buffer.from(signature(payload)) if (given.length !== expected.length || !timingSafeEqual(given, expected)) return undefined const userId = payload.slice(0, payload.lastIndexOf('.')) const expires = Number(payload.slice(userId.length + 1)) return expires * 1000 > Date.now() ? userId : undefined}import { defineFunction } from '@protobase/server'import { mintTicket } from './_shared/tickets'
// POST /api/functions/display-ticket, from the display board's page: a ticket that opens its socket for 30 seconds.export default defineFunction({ roles: ['mechanic'], cors: { origin: 'https://workshop.pips-bikes.example' } }, (_request, { session }) => Response.json({ ticket: mintTicket(session.user.id) }),)import { defineFunction, unauthorized } from '@protobase/server'import { ticketUser } from './_shared/tickets'
// /api/functions/display?ticket=…, the workshop's display board, opened as a WebSocket from a page with no session// cookie of this app. Public, so it checks the ticket itself: a missing, forged or expired one gets a 401 and no socket.// Nothing checks the ticket's user again while the socket is open, so `recheck` ends it after 15 minutes, as a signed-in// token would end, and the board opens it again with a new ticket.export default defineFunction({ public: true }, (request, { acceptWebSocket }) => { const user = ticketUser(new URL(request.url).searchParams.get('ticket') ?? '') if (!user) throw unauthorized('Get a ticket from /api/functions/display-ticket first') const until = Date.now() + 15 * 60_000 return acceptWebSocket({ onOpen: (socket) => socket.send(JSON.stringify({ shownFor: user })), recheck: () => { if (Date.now() >= until) throw unauthorized('Get a new ticket') }, })})// On https://workshop.pips-bikes.example, with a client made by createClientconst { ticket } = await client.invoke('display-ticket', { method: 'POST' })const board = new WebSocket(`wss://pips-bikes.example/api/functions/display?ticket=${encodeURIComponent(ticket)}`)The ticket only lets the socket open, and anyone who holds it may open one with it during its 30 seconds. It is in the address, so it appears in the request log when REQUEST_LOG is true. Nothing checks the ticket’s user again, so display.ts’s recheck ends the socket after 15 minutes, and the board opens it again with a new ticket, which display-ticket mints only after checking the role again.
Slow readers and large messages
Section titled “Slow readers and large messages”- Await
sendwhen the other side may read slowly: it resolves once the data is written, so a relay that awaits each send never piles up data in the server. It never rejects; after a close it resolves at once. - Return a promise from
onMessageto hold the next message back until it settles. Above 1 MiB of waiting messages the server stops reading from the client, which slows it down, and reads again once they are handled. Bun’s built-inws, whichprotobase devuses on Bun, cannot stop reading: there the socket closes with1013once 16 MiB are waiting. - A message may be up to 100 MiB, or the socket’s
maxMessageBytes, which only lowers it. A larger message closes the socket with1009before the server reads it, so a function that only takes small messages sets it, such asacceptWebSocket({ maxMessageBytes: 64 * 1024, onMessage }).protobase devandprotobase serveapply it; a server of your own that hostscreateAdminrefuses a socket withmaxMessageByteswith a500, since itswsserver would not apply it.
Restarts
Section titled “Restarts”protobase dev closes every open socket with 1012 when you edit the project, so it reconnects to the rebuilt API. protobase serve closes them with 1001 when it stops, and drops any still open after 5 seconds. Clients that reconnect on these codes keep working across both.
Work after the response
Section titled “Work after the response”waitUntil(promise) from @protobase/server lets a function answer at once and finish its work afterwards, such as a slow call to another API:
import { defineFunction, waitUntil } from '@protobase/server'
export default defineFunction((_request, { session }) => { waitUntil(fetch('https://hooks.example.com/notify', { method: 'POST', body: JSON.stringify({ user: session.user.id }) })) return new Response(null, { status: 202 })})protobase serve waits for that work when it stops gracefully; work still running when the host kills the process is lost, and an error it throws is printed, since no response waits for it. On Protobase Cloud’s Starter plan an app stops 30 seconds after its last request, with 10 seconds to finish, so move longer work into a job.
Secrets and other APIs
Section titled “Secrets and other APIs”import { z } from 'zod'import { defineFunction, readJson, requireEnv } from '@protobase/server'
const Input = z.object({ repairId: z.number().int().positive() })
// POST /api/functions/notify-customer { "repairId": 7 }: texts the customer that their bike is ready, through an SMS// provider's API. The key comes from the environment: .env in development, the host's settings in production.export default defineFunction({ roles: ['desk'] }, async (request, { records }) => { const { repairId } = await readJson(request, Input) const { record: repair } = await records.get('repairs', repairId) const { record: customer } = await records.get('customers', repair.customer_id as number) if (!customer.phone) return Response.json({ sent: false, reason: 'The customer has no phone number' })
const sent = await fetch('https://api.sms.example/v1/messages', { method: 'POST', headers: { authorization: `Bearer ${requireEnv('SMS_API_KEY')}`, 'content-type': 'application/json' }, body: JSON.stringify({ to: customer.phone, text: `Hi ${customer.name}, your ${repair.bike} is ready for pickup.` }), }) if (!sent.ok) throw new Error(`The SMS provider answered ${sent.status}`) return Response.json({ sent: true })})requireEnv(name) returns an environment variable, or throws when it is not set. The call then fails as a 500 that the app reports, and the request goes nowhere. protobase dev and protobase serve read the nearest .env file. In production the serve runtime takes the host’s environment as it is, so set the secret where the host keeps its settings. Keep secrets in functions, never in protobase.ui.tsx, which runs in the browser.
Calling a function
Section titled “Calling a function”From the admin UI, an action handler gets a client that carries the user’s token. client.invoke calls a function the way supabase.functions.invoke does:
import { defineUi } from '@protobase/ui'
export default defineUi({ actions: { readyForPickup: async ({ client, record }) => { await client.invoke('ready-for-pickup', { body: { repairId: record?.id } }) }, },})invoke(name, { method?, body?, path?, query?, headers?, cache? }) sends a GET, or a POST with a JSON body; cache is the browser’s fetch cache mode other than only-if-cached, such as no-store for an answer only its caller may see. It resolves to the parsed JSON, to text for a text/* answer or one without a content type, to a Blob of any other type, or to undefined for a 204. A function sends a file, such as a PDF, as a plain Response with its type and name: new Response(bytes, { headers: { 'content-type': 'application/pdf', 'content-disposition': 'attachment; filename="invoice.pdf"' } }), and invoke gives the caller that Blob, with its type. A problem rejects with an ApiError, as any call of the client does. Outside the admin, createClient from @protobase/client gives the same invoke, or you can call the URL with fetch and an Authorization: Bearer header.
Hono apps
Section titled “Hono apps”A function of several routes can be a Hono app. The context is its c.env:
import { defineFunction, functionApp } from '@protobase/server'import { nextStatus } from './status'
// /api/functions/workshop/*: the workshop's tablet app, a Hono app on its own origin. `c.env` is the function's// context, so every route acts as the signed-in mechanic.const app = functionApp()
// GET /api/functions/workshop/queueapp.get('/queue', async (c) => { const page = await c.env.records.list('repairs', { filter: 'status = "waiting" OR status = "working"', order_by: 'booked_on', fields: ['id', 'number', 'bike', 'status'] }) return c.json(page.items)})
// POST /api/functions/workshop/7/advanceapp.post('/:id/advance', async (c) => { const id = Number(c.req.param('id')) const { record, etag } = await c.env.records.get('repairs', id) const updated = await c.env.records.update('repairs', id, { status: nextStatus(record.status as string) }, { etag }) return c.json(updated.record)})
export default defineFunction({ roles: ['mechanic'], cors: { origin: 'https://workshop.pips-bikes.example' } }, app)functionApp() is new Hono() with one difference: errors and unknown paths reach the app’s own error handling, so problems are rendered as problem+json and anything else is reported. Your own Hono instance works too, typed with FunctionEnv (or PublicFunctionEnv):
import { Hono } from 'hono'import type { FunctionEnv } from '@protobase/server'
const app = new Hono<FunctionEnv>()// Without this, Hono answers errors itself: a plain-text 500 that the app never reports.app.onError((error) => { throw error})export default appA Hono app’s routes start at /, because the request path no longer includes /api/functions/<name>. The deploy bundle supplies hono, hono/cors, hono/http-exception and hono/validator (see the config module). Other Hono middleware is bundled with the function, as are its other packages.
A function called from a page on another origin needs CORS. Use the cors option, which takes the options of hono/cors:
defineFunction({ cors: { origin: 'https://workshop.pips-bikes.example' } }, app)Preflight requests are answered before authentication, because a browser sends them without a token. Every response, including a 401 problem, carries the CORS headers. In a protected function, the hono/cors middleware inside a Hono app would never see the preflight, because authentication runs first.
Long queries
Section titled “Long queries”A function’s queries through db have the database’s own statement timeout: on Protobase Cloud, 1 second, so a slow query fails where it runs instead of holding a connection that pages wait for. A function that does bulk work, such as an import, a report or a large delete, asks for longer:
export default defineFunction({ longQueries: true }, async (request, { db }) => { await sql`delete from audit_log where at < now() - interval '1 year'`.execute(db) return new Response(null, { status: 204 })})- Up to 30 seconds per query, the most any query of an app may run. Work longer than that belongs in steps, such as a job per batch, which takes
longQueriestoo. - One connection kept for it. Under
protobase devandserve, those queries run on a connection of their own, which asks for the longer timeout when it logs in, so long work never takes the connections pages need; a second long call waits for it. A PgBouncer of your own in front of the database must liststatement_timeoutintrack_extra_parametersto pass that on; Protobase Cloud’s does. - Room for pages. Under
protobase devandserve, function calls and jobs together hold at most one connection less thanPROTOBASE_DB_CONNECTIONS, so a long import always leaves one to page and API requests; a call past that waits for a connection of its own. recordskeep the API’s limit,statementTimeoutMs.- A query past its limit is stopped, and the call answers
504 statement-timeoutnaming the call, its limit and the way out, such asPOST /api/functions/import ran a query longer than the database's statement timeout, so the database stopped it. It may also have waited on a lock another transaction held, such as a migration while a deploy runs. Make the query faster, such as with an index or a narrower filter, or give it longQueries: true, whose queries may run up to 30 s.It goes to the app’s error hook,hooks/error.ts, and the error tracker.
Errors
Section titled “Errors”- Problems: throw an
HttpProblem(orbadRequest,unauthorized,forbidden,notFoundfrom@protobase/server) to answer with an RFC 9457 problem. Hono’sHTTPExceptionworks too. - A query the database stopped is a
504 statement-timeoutthat names the call; see Long queries. - Everything else: any other error, or a handler that returns something other than a
Response, becomes a500 internal-errorproblem without its message. The error goes to the app’s error hook,hooks/error.ts; without one,protobase devandserveprint it.
Functions moved from Supabase
Section titled “Functions moved from Supabase”protobase import supabase converts supabase/functions into functions/. A converted function keeps Supabase’s shape, defineFunction({ supabase: true }, { fetch }), and keeps working with @supabase/server and supabase-js:
- At
/api/sb/functions/v1/<name>too, sosupabase.functions.invokecallers do not change. Only a function withsupabase: trueanswers there, and any other function answers404. There a protected function lets in a request with the app’s publishable or secret key in theapikeyheader, and a user token of/api/sb/auth/v1as the bearer, if any, as Supabase’sverify_jwtdoes. A public function lets in anyone. The keys are the app’s API keys: without them, only public functions answer there. As on Supabase, the request’s path starts at the function’s name (/<name>/more/parts), and a CORS preflight reaches the function, which answers it. - Its context there is
{ name, db, caller() }, wherecaller()resolves to who the key and token make the request:{ role: 'anon' }for the publishable key alone,{ role: 'app' }for the secret key, or{ role: 'authenticated', claims }. There is nosessionand norecords. The publishable key alone lets callers in, so givesupabase: trueonly to functions written for Supabase’sverify_jwt. Together withrolesorcapability, which the address cannot check, it stops startup. - Supabase’s variables:
protobase devsetsSUPABASE_URLto the app’s address with/api/sb, where supabase-js finds it,SUPABASE_ANON_KEYandSUPABASE_PUBLISHABLE_KEYto the publishable key andSUPABASE_PUBLISHABLE_KEYSto{"default":<publishable key>},SUPABASE_SERVICE_ROLE_KEYandSUPABASE_SECRET_KEYto the secret key andSUPABASE_SECRET_KEYSto{"default":<secret key>}, each only when the app has that key,SUPABASE_JWKS_URLto the key set of/api/sb/auth/v1when the app has sign-in, andSUPABASE_DB_URLto the database. A variable set in.envwins. Underprotobase serve, set them where the host keeps its settings. waitUntil(promise)from@protobase/servertakes the place ofEdgeRuntime.waitUntil.
What functions are not
Section titled “What functions are not”- Not under
/api/v1, which stays resources only. Functions live beside the system endpoints, like/api/meta. - Not in the OpenAPI document or the
/api/docsreference. - Not scheduled: a function runs when it is called. A cron job on the host, or an external scheduler, can call one with a token, or call a public one that checks a signature.