Backend
Custom Functions
Overview
Section titled “Overview”Custom functions let you add arbitrary Hono API routes alongside Rebase’s auto-generated CRUD endpoints. They follow the same file-based discovery pattern as cron jobs: drop a TypeScript file in your functions/ directory, and Rebase mounts it automatically.
Use custom functions for:
- Business logic endpoints — approvals, promotions, custom workflows
- Third-party integrations — Stripe webhooks, Slack commands, external API proxies
- Public endpoints — contact forms, lead capture, health checks
- Aggregate queries — dashboard stats, reports, analytics
Defining a Custom Function
Section titled “Defining a Custom Function”Create a file in your backend/functions/ directory that default-exports a Hono app:
// backend/functions/hello.tsimport { defineFunction } from "@rebasepro/server/functions";
export default defineFunction((app) => { app.post("/", async (c) => { const { name } = await c.req.json<{ name?: string }>().catch(() => ({ name: undefined })); return c.json({ message: `Hello, ${name ?? "world"}!` }); });});This mounts at /api/functions/hello. The filename (without extension) becomes the route prefix.
POST, because that is what the SDK sends by default — see Invoke from the client. A GET route is just as valid; the caller then has to say { method: "GET" }.
rebase dev watches the functions directory, so a file added while it is
running is mounted on the next reload — no restart. (It has to be told: the
directory is scanned rather than imported, so the watcher cannot infer it.)
Invoke from the client
Section titled “Invoke from the client”import { createRebaseClient } from "@rebasepro/client";
const client = createRebaseClient({ baseUrl: "http://localhost:3000" });
const { message } = await client.functions.invoke<{ message: string }>( "hello", // the filename, without extension — one path segment { name: "Ada" } // JSON body; omitted for a GET);invoke builds the URL, attaches the caller’s token, and throws a
RebaseApiError on a non-2xx — so the function’s own error shape reaches the
caller instead of a bare fetch rejection.
Four things it takes beyond the name:
// A different method. The payload is dropped for GET, since GET has no body.await client.functions.invoke("hello", undefined, { method: "GET" });
// A sub-path — `/api/functions/hello/stats`. It goes here, never in the name:// a name containing "/" is refused rather than percent-encoded into a 404.await client.functions.invoke("hello", undefined, { method: "GET", path: "stats" });
// A query string. Passed as `path`, with no separator inserted before `?`.await client.functions.invoke("reports", undefined, { method: "GET", path: "?days=30" });
// A function that answers text or a file (`c.text(csv)`, `c.body(pdf)`).// The answer is read as JSON unless you say otherwise: "text" gives a string,// "blob" a Blob, "response" the Response itself with its body unread.const csv = await client.functions.invoke<string>("export-orders", undefined, { method: "GET", responseType: "text" });Import from @rebasepro/server/functions, not from @rebasepro/server.
Both work. The subpath is the portable authoring surface: it pulls in nothing that requires Node, so a function written against it can run on any JavaScript runtime. The package root reaches the whole framework — the boot sequence, the file loaders, the WebSocket layer — which is right for a server entrypoint and more than a route handler needs. It also gives you typed context accessors (getUser, getDriver) instead of casting c.get("user") by hand.
See Runtime portability for the full contract.
Configuration
Section titled “Configuration”Enable custom functions by adding functionsDir to your backend config:
import path from "path";
const instance = await initializeRebaseBackend({ // ... other config functionsDir: path.resolve(__dirname, "../functions"),});Rebase will:
- Scan the directory for
.ts/.jsfiles - Validate each default export is a Hono app (duck-typed via
.fetch()+.routes) - Mount each app at
/api/functions/<filename> - Apply the auth middleware (see Authentication below)
Functions as values
Section titled “Functions as values”A directory is one way to produce what the server serves: a record from URL segment to Hono app. Pass that record yourself as functions, or read a directory into it with loadFunctions:
import path from "path";import { initializeRebaseBackend, loadFunctions } from "@rebasepro/server";import sendInvoice from "../functions/send-invoice";
await initializeRebaseBackend({ app, server, functions: { "send-invoice": sendInvoice } }); // → /api/functions/send-invoice// the same as functionsDir:await initializeRebaseBackend({ app, server, functions: await loadFunctions(path.resolve(__dirname, "../functions")) });Give functions or functionsDir, not both: the boot refuses the pair. loadFunctions(dir, { onSkip }) hands you each file it skipped, with the reason. loadFunctionsFromDirectory and loadFunctionsWithDiagnostics still work, are deprecated, and warn once. On its own, the functions group mounts at any path with app.route("/hooks", backend.routes.functions()), and getUser(c) and getDriver(c) work inside it; see Custom Server Integration.
File Naming and Route Mapping
Section titled “File Naming and Route Mapping”| File | Mount Path |
|---|---|
functions/hello.ts |
/api/functions/hello/* |
functions/send-invoice.ts |
/api/functions/send-invoice/* |
functions/webhooks.ts |
/api/functions/webhooks/* |
Functions are discovered at the top level of the directory only — there is no recursion. functions/admin/users.ts is compiled by rebase build but never mounted; flatten the name instead (functions/admin-users.ts). A subdirectory is reported at boot and counted on the listing endpoint rather than ignored silently.
Files that are skipped:
index.ts/index.js— reserved*.test.ts/*.test.js— test files*.d.ts— type declarations- Subdirectories, and
.mts/.cts/.tsx/.jsx/.mjs/.cjsfiles — reported as problems, since the build compiles more than the runtime loads
The name is the function’s identity everywhere else too: it is the URL segment, the target of the functions:invoke:<name> scope a key needs to call it, and the value REBASE_FUNCTIONS_ONLY selects by when you give one function its own process.
Export Formats
Section titled “Export Formats”The loader accepts two export formats besides defineFunction:
Hono App
Section titled “Hono App”import { Hono } from "hono";import type { HonoEnv } from "@rebasepro/server/functions";
const app = new Hono<HonoEnv>();app.get("/status", (c) => c.json({ ok: true }));export default app;Factory Function
Section titled “Factory Function”import { Hono } from "hono";import type { HonoEnv } from "@rebasepro/server/functions";
export default function () { const app = new Hono<HonoEnv>(); app.get("/status", (c) => c.json({ ok: true })); return app;}defineFunction returns exactly the Hono app these build by hand, so the three are interchangeable. It saves you declaring Hono<HonoEnv> and hands you the rebase singleton in the callback.
Under the Hood: The Duck-Typing Loader
Section titled “Under the Hood: The Duck-Typing Loader”In a monorepo your functions may resolve a different copy of Hono from the one Rebase uses, and then exported instanceof Hono is false for a working router. So the loader checks the shape instead (isHonoLike): a non-null object with a .fetch method and a .routes array.
ES Module Compiler Escape
Section titled “ES Module Compiler Escape”The loader turns each file path into a file URL (pathToFileURL(filePath).href), so it imports on Windows and POSIX alike, and calls import(url) through new Function("url", "return import(url)"), so a TypeScript build cannot rewrite it into a require() that fails under ESM.
Authentication and Context Propagation
Section titled “Authentication and Context Propagation”Custom functions are mounted with the same auth middleware as the data routes, but with requireAuth: false. This means:
- The user’s JWT is parsed and injected into the context if present
- But requests are not rejected if no JWT is provided
- You must explicitly protect routes that need authentication
A caller who presents a bad token never reaches your handler: an unverifiable or expired token is rejected with 401 by the middleware itself, so an expired session is never silently downgraded to an anonymous one.
Reading the caller
Section titled “Reading the caller”import { defineFunction, getUser, getUserId, getRoles, getScopes, isAdmin } from "@rebasepro/server/functions";
export default defineFunction((app) => { app.get("/me", (c) => { const user = getUser(c); // { uid, roles, ...claims } | undefined if (!user) return c.json({ error: "Unauthorized" }, 401); return c.json({ uid: user.uid, roles: user.roles, admin: isAdmin(c), scopes: getScopes(c) }); });});getUser returns a narrowed object: uid is a string and roles is always an array, whatever auth method the caller used. getUserId(c) and getRoles(c) are shortcuts. getScopes(c) is everything the caller may do, as scope strings: for a person, the data plane, the app’s own scopes and their roles’ scopes; for an API key, exactly what the key holds.
The caller’s account
Section titled “The caller’s account”getUser(c) reads the access token, and the token holds the caller’s id, roles and address. It does not say how the account signs in or what its display name is. getUserProfile(c) reads those from the auth store:
import { defineFunction, getUserProfile } from "@rebasepro/server/functions";
export default defineFunction((app) => { app.get("/whoami", async (c) => { const profile = await getUserProfile(c); if (!profile) return c.json({ error: "Unauthorized" }, 401); // { uid, email?, displayName?, photoURL?, emailVerified, isAnonymous, providers } return c.json({ name: profile.displayName ?? null, social: profile.providers.some(p => p !== "password") }); });});providers lists how the account can sign in: "password" when it has one, then each linked provider ("google", "apple", …) in the order it was linked. A guest account, or one that signs in only with a one-time code, has an empty list.
The read is fresh for each request: a provider the caller linked a moment ago shows on their next request, without waiting for the token to refresh. The first call in a request costs two keyed lookups, made together. Later calls in the same request reuse the result, and a request that never calls it costs nothing.
It returns undefined for an anonymous caller, for a service-key or API-key caller that acts as no account, and for an account that no longer exists. It also returns undefined on a backend whose accounts live with an external auth adapter: ask that provider instead. When an administrator sends x-rebase-impersonate, it returns the impersonated account.
Protecting Routes
Section titled “Protecting Routes”import { defineFunction, requireAuth, requireAdmin, requireRole, getUserId } from "@rebasepro/server/functions";
export default defineFunction((app) => { // Public endpoint — no guard, so anyone can call it. app.get("/public", (c) => c.json({ message: "Anyone can access this" }));
// 401 for anonymous callers. app.post("/protected", requireAuth, (c) => c.json({ message: `Hello, ${getUserId(c)}` }));
// 401 anonymous, 403 without the admin role. Order matters. app.post("/admin-only", requireAuth, requireAdmin, (c) => c.json({ ok: true }));
// Any one of the named roles. app.post("/publish", requireAuth, requireRole("editor", "admin"), (c) => c.json({ ok: true }));});Put guards in the route’s own middleware slot, as above, rather than app.use("/*", requireAuth). use() covers only the routes declared below it, so a route appended later — at the bottom of the file, months from now — is silently unprotected.
Reading getUser(c) is not a guard. An anonymous caller gets undefined and your handler runs anyway. Only a guard, or an explicit if (!user) return 401, stops the request.
Scopes and app scopes
Section titled “Scopes and app scopes”requireAdmin admits the admin role and nobody else. For an action a narrower role or an API key should reach, guard the route with requireScope. It takes a built-in scope, or one the app declares under auth.scopes on the users collection, such as "project:deploy": { label: "Deploy projects", target: "project" }:
import { defineFunction, requireAuth, requireScope, hasScope } from "@rebasepro/server/functions";
export default defineFunction((app) => { // 403 SCOPE_MISSING unless the caller holds project:deploy, or project:deploy:<this project>. app.post("/:project", requireAuth, requireScope("project:deploy", c => c.req.param("project")), (c) => { return c.json({ deploying: c.req.param("project") }); });
// The same question inside a handler. app.get("/:project/can-deploy", requireAuth, (c) => c.json({ allowed: hasScope(c, "project:deploy", c.req.param("project")) }));});Every signed-in person holds every app scope, so for a person requireScope decides nothing: check in the handler whether this person may deploy this project. What the scope adds is a way to narrow a key: a key holding project:deploy:p1 passes for p1 only. A key also needs functions:invoke, or functions:invoke:<name>, before it reaches the function at all. See App scopes.
Rate limits
Section titled “Rate limits”A route that costs something per call takes rateLimit middleware, which counts across replicas. See Rate limits in functions.
Service Key Authentication
Section titled “Service Key Authentication”Rebase supports a static REBASE_SERVICE_KEY defined in your .env for script or server-to-server calls.
When an external request passes the service key via the Authorization header (Authorization: Bearer <service_key>), the auth middleware automatically:
- Validates the key using constant-time comparison to prevent timing attacks.
- Grants admin-level access, setting the caller to
{ uid: "service", roles: ["admin"] }. - Injects a
DataDriverscoped as that same service identity. Row-Level Security still applies — it is evaluated as{ uid: "service", roles: ["admin"] }, not skipped.
Internal Self-Authentication
Section titled “Internal Self-Authentication”If you haven’t configured a REBASE_SERVICE_KEY, Rebase generates a random internal per-boot key. The rebase singleton uses this key automatically when calling the server’s own control-plane APIs (like rebase.auth or rebase.storage). This means your server-side logic can always perform administrative tasks even without a manually configured service key.
Accessing the Database & Services
Section titled “Accessing the Database & Services”1. The user-scoped driver — for anything serving a request
Section titled “1. The user-scoped driver — for anything serving a request”getDriver(c) returns the driver scoped to the caller, so every read and write is evaluated against your Row-Level Security policies as that user:
import { defineFunction, requireAuth, requireDriver } from "@rebasepro/server/functions";
export default defineFunction((app) => { app.get("/", requireAuth, async (c) => { const driver = requireDriver(c); const myProducts = await driver.fetchCollection({ path: "products", limit: 10 }); return c.json(myProducts); });});requireDriver(c) is getDriver(c) without the ! — it throws a message naming the wiring problem instead of failing twenty lines later on undefined.
fetchCollection and fetchOne return the rows GET /api/data/<table> returns: dates as RFC 3339 strings, a belongsTo as its foreign key (authorId), and a related row only when include names it — driver.fetchOne({ path: "articles", id, include: ["author"] }).
2. rebase.dataAsAdmin — for trusted background work
Section titled “2. rebase.dataAsAdmin — for trusted background work”import { defineFunction, requireAuth, requireAdmin } from "@rebasepro/server/functions";
export default defineFunction((app, { rebase }) => { app.post("/:id/approve", requireAuth, requireAdmin, async (c) => { const id = c.req.param("id"); await rebase.dataAsAdmin.table<Record<string, unknown>>("jobs").update(id, { status: "published", approved_at: new Date().toISOString(), }); return c.json({ success: true }); });});rebase.dataAsAdmin is untyped until you register your generated Database.
RLS-Scoped Driver vs. Rebase Singleton
Section titled “RLS-Scoped Driver vs. Rebase Singleton”getDriver(c) (request-scoped) |
rebase.dataAsAdmin (service identity) |
|
|---|---|---|
| Runs as | The caller (uid, their roles) |
{ uid: "service", roles: ["admin"] } |
| RLS enforcement | ✅ Yes (evaluated against the caller) | ✅ Yes (evaluated against the service identity) |
| Ideal for… | General user CRUD, search, and queries | Background jobs, system triggers, webhooks |
| API style | Driver-level methods (fetchCollection, save) |
Fluent table accessors (rebase.dataAsAdmin.jobs.find) |
What dataAsAdmin is, precisely
Section titled “What dataAsAdmin is, precisely”rebase.dataAsAdmin is admin-scoped, not RLS-bypassing. The driver is scoped once, at boot, with withAuth({ uid: "service", roles: ["admin"] }), so every read and write runs inside a transaction that has switched to the restricted rebase_user role with app.uid = 'service'. Your policies are evaluated — against that identity.
For most projects the distinction never surfaces, because the default policies Rebase injects onto every table admit serverContext() OR rolesOverlap(['admin']), and the service identity clears the second arm. It surfaces the moment you write your own policies:
policy.serverContext()is false for it. That helper compiles torebase.uid() IS NULL, and this accessor’suidis'service'. A table withdefaultPolicies: falsewhose only write rule isserverContext()will refuse adataAsAdminwrite with Postgres error42501, and a read against such a table returns zero rows with HTTP 200 — the silent direction. WriterolesOverlap(["admin"])(or add it alongside) when you mean “my backend”.- Its reach equals an
adminuser’s reach. Granting theadminrole to an application user grants them exactly the rows this accessor sees. It is not a private channel.
3. getSql(c) — SQL as the caller
Section titled “3. getSql(c) — SQL as the caller”When the SDK does not express a query or a write cleanly — a conditional upsert, a compare-and-swap UPDATE … WHERE rev = $3 RETURNING, count(*) FILTER (…), a CTE — write the SQL, and run it as the caller:
import { defineFunction, getSql, requireAuth } from "@rebasepro/server/functions";
export default defineFunction((app) => { app.get("/my-stats", requireAuth, async (c) => { const sql = getSql(c); const rows = await sql( "SELECT lower(artist) AS artist, count(*) FILTER (WHERE liked) AS likes FROM songs WHERE lang = $1 GROUP BY 1", { params: [c.req.query("lang") ?? "en"] } ); return c.json(rows); });});The values are Postgres’s, with two spelled as /api/data spells them: a timestamptz is RFC 3339 in UTC (2026-11-18T10:52:23.500Z), and a bigint is a number when it fits a safe integer (past 2^53 it stays the digits, as a string). A numeric is a string, so no digit is lost; cast it in the query (total::float8) when a number is what you want.
The statement runs in the caller’s own transaction, as the restricted rebase_user role with their identity — the transaction the user-scoped driver opens — so your tables’ rls rules decide every row, exactly as they do for the SDK. A query that asks for every row gets the caller’s.
- Read-only by default. Pass
{ write: true }to insert, update or delete; the insert and update policies still apply. - The query text is yours; values go in
params($1,$2, …). The caller’s identity lives in transaction settings, which SQL can change, so a statement that could —SET,RESET,set_config,pg_settings,DO, more than one statement — is refused with400 SQL_NOT_ALLOWEDbefore it runs. Interpolating user input into the text is how that guard would be tested; don’t. - What it shares with the SDK. The policies, and three rules Postgres holds for both: a materialized view serves its rows only to its
roles, a row of a table declaringtenantcannot be moved to another tenant except by abypassRolescaller (TENANT_IMMUTABLE), and the server’s own functions (rebase.record_history,rebase.enqueue_job) are refused. A column the caller may not read —.private(), or an.access({ read })they lack — is dropped from the rows, as the API drops it, when it is a plain reference to the column (SELECT *,password_hash AS h); a value computed from one (md5(password_hash)) is not recognised, so don’t compute from it. - What it does not share.
beforeQueryandafterRead, validation, save hooks and history live in Node and do not run.
From a script, openRebase gives you the same: (await rebase.withAuth(user)).sql(…).
rebase.sqlAsAdmin() — SQL as the service identity
Section titled “rebase.sqlAsAdmin() — SQL as the service identity”A function that enforces its own rules (one ticket a day, a timing check) over tables only admins may read cannot use getSql(c): the caller would need policies that admit them, and those same policies would open the tables on the public data API too. rebase.sqlAsAdmin runs the statement as { uid: "service", roles: ["admin"] }, the identity rebase.dataAsAdmin uses, under the same row-level security:
import { defineFunction, rebase } from "@rebasepro/server/functions";
export default defineFunction((app) => { app.post("/claim", async (c) => { const { device } = await c.req.json(); const rows = await rebase.sqlAsAdmin( "INSERT INTO tickets (device, day) VALUES ($1, current_date) ON CONFLICT DO NOTHING RETURNING id", { params: [device], write: true } ); return c.json({ claimed: rows.length === 1 }); });});It is getSql(c) with a different identity: the restricted request role, the admin arm of your policies, read-only unless { write: true }, and the same SQL_NOT_ALLOWED guard. Unlike the owner’s rebase.sql(), it cannot run DDL, and of the auth store it reaches only what an admin reaches through the users collection: sessions, keys and MFA secrets are withheld from the request role, and a password hash is dropped from the rows. A lone statement costs one round trip, as rebase.sql() does. From a script, openRebase() has it too.
4. rebase.sql() — owner SQL, and the one Node-only accessor
Section titled “4. rebase.sql() — owner SQL, and the one Node-only accessor”If you genuinely need an unconditional bypass, rebase.sql() is it: raw SQL on the owner connection, no policies, every row. It is the most privileged thing in a function’s context — more so than the accessor with “admin” in its name.
It is not for making tables. A table is declared with defineTable in backend/schema/ and created by boot; one made with CREATE TABLE in a function has no validation, hooks, row-level security posture, admin view or SDK type. rebase.sql() runs such a statement, and logs a warning naming the table to declare instead.
import { defineFunction, requireAuth, requireAdmin } from "@rebasepro/server/functions";
export default defineFunction((app, { rebase }) => { app.get("/stats", requireAuth, requireAdmin, async (c) => { const rows = await rebase.sql( "SELECT count(*) AS total FROM jobs WHERE status = $1", { params: ["published"] } ); return c.json({ totalJobs: Number(rows[0]?.total ?? 0) }); });});It runs on a TCP connection to your database, which makes it the only accessor tied to a Node process. That costs nothing on any deployment that exists today — it is simply the one thing to know about if a function may later move. See Runtime portability.
Configuration and Secrets
Section titled “Configuration and Secrets”Read configuration inside the handler, never at module scope:
import { defineFunction, requireEnv, lazyResource } from "@rebasepro/server/functions";
// Built once, on the first request that needs it — not at import time.const apiKey = lazyResource((env) => env.PRICING_API_KEY ?? "");
export default defineFunction((app) => { app.get("/price", async (c) => { const endpoint = requireEnv(c, "PRICING_API_URL"); const response = await fetch(endpoint, { headers: { authorization: `Bearer ${apiKey(c)}` } }); return c.json(await response.json()); });});Why this matters on any runtime, including Node:
// Don't. If STRIPE_SECRET_KEY is unset, this throws while the file is being// imported — and the loader reports that as a *skipped function*. The route// 404s, with the reason buried in a boot log line.const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);A module-scope read is evaluated when the file is imported, before any request exists. On Node that means one missing variable takes the whole file down and every route in it with it. On a host that attaches configuration to the request rather than the process, there is nothing to read at import time at all.
getEnv(c)— every variable visible to this requestenv(c, "NAME")— one variable, trimmed; blank counts as unsetrequireEnv(c, "NAME")— the same, but throws a message naming the variablelazyResource(factory)— build an expensive client once, on first use
rebase doctor reports module-scope process.env reads in your functions directory.
Background Work
Section titled “Background Work”Moved to its own page: Background Work.
Runtime portability
Section titled “Runtime portability”A custom function is a Hono app, so whether it could run somewhere other than a Node process comes down to what its own file imports. rebase.sql(), a directly imported database client and Node built-ins tie it to Node; the rest of rebase and the web platform do not, and nothing fails today because of either. Runtime portability lists what is portable, how rebase build and rebase doctor report it, and how to branch on the runtime.
Route Registration Order
Section titled “Route Registration Order”Custom functions are loaded and mounted after initializeRebaseBackend() completes the core setup. The initialization order is:
- Bootstrappers — Database connections, auth tables, realtime services
- Auth routes —
/api/auth/*,/api/admin/* - Storage routes —
/api/storage/* - Data routes —
/api/data/*(CRUD for tables) - Custom functions ←
/api/functions/* - Cron jobs —
/api/admin/cron/* - WebSocket — Realtime subscriptions
This means your custom functions have access to all initialized services. Register any routes that need to run before Rebase on the Hono app directly, prior to calling initializeRebaseBackend():
const app = new Hono<HonoEnv>();
// This runs BEFORE Rebase routesapp.get("/health", (c) => c.json({ status: "ok" }));
// Rebase initialization — registers all /api/* routesconst instance = await initializeRebaseBackend({ app, /* ... */ });Example: Webhook Handler
Section titled “Example: Webhook Handler”import { defineFunction, requireEnv, waitUntil, lazyResource } from "@rebasepro/server/functions";
/** Constructed on the first request, from that request's configuration. */const secret = lazyResource((env) => env.STRIPE_WEBHOOK_SECRET ?? "");
export default defineFunction((app, { rebase }) => { // Deliberately public: Stripe has no token to send. The signature is the // authentication, so verify it before doing anything else. app.post("/", async (c) => { const signature = c.req.header("stripe-signature"); const body = await c.req.text();
if (!signature || !verifySignature(body, signature, secret(c))) { return c.json({ error: "Bad signature" }, 400); }
const event = JSON.parse(body) as { type: string; data: { object: Record<string, string> } };
if (event.type === "checkout.session.completed") { const session = event.data.object; await rebase.dataAsAdmin.table("subscriptions").create({ user_id: session.client_reference_id, stripe_id: session.subscription, status: "active", }); // Fulfilment can outlive the response; the 200 tells Stripe to stop retrying. waitUntil(c, notifyFulfilment(requireEnv(c, "FULFILMENT_URL"), session)); }
return c.json({ received: true }); });});
declare function verifySignature(body: string, signature: string, secret: string): boolean;declare function notifyFulfilment(url: string, session: Record<string, string>): Promise<void>;Debugging
Section titled “Debugging”Log from a function with logger from @rebasepro/server/functions, not console.log: see Logging. When functions load, the boot logs Loaded custom functions with their count. Each function’s own line is logged at debug (LOG_LEVEL=debug):
Loaded function route: helloIf loading fails, the loader provides diagnostic output:
[functions] broken-function.ts: default export is not a Hono app or factory. Skipping. export type: object (SomeClass) prototype methods: constructor, someMethod Hint: ensure the function exports a Hono app created with the same hono version as the server. Author with `defineFunction(...)` from @rebasepro/server/functions for a typed, checked contract. The loader checks for .fetch() and .routes — any Hono-compatible app will work.The router is mounted for the directory, not for the functions in it. If every file fails to import — one missing environment variable at module scope is enough to take all of them down — GET /api/functions still answers 200 with an empty list plus a skipped count, so “nothing loaded” is distinguishable from “this build shipped no functions”. The listing itself requires a signed-in caller, an API key holding the plain functions:invoke scope, or the service key — the functions stay callable by whoever each one admits, but the inventory of them is not public. The reasons stay in the boot log.
Timeouts and Rate Limits
Section titled “Timeouts and Rate Limits”Two ceilings apply to /api/functions/*:
- Request timeout — 30 seconds by default, answering
504with codeFUNCTION_TIMEOUT. Configure it for every function withfunctionsTimeoutMs(orREBASE_FUNCTIONS_TIMEOUT_MS);0disables it. A function that waits on a slow service, such as an LLM, declares its own as the second argument ofdefineFunction:defineFunction((app) => { … }, { timeoutMs: 150_000 }). It replaces the server-wide timeout for that function only, longer or shorter, counts from the moment the request reached the functions router, and applies even where the server-wide one is0; the server caps it atREBASE_FUNCTIONS_MAX_TIMEOUT_MS(300000, 5 minutes, by default), and it cannot be0. The 504’s message says which limit applied and where it was set, anderror.detailscarries it as{ timeoutMs, source }(sourceisdefault,env,optionorfunction). The handler cannot be stopped from the outside, but it is told:getSignal(c)from@rebasepro/server/functionsis aborted at the moment of the 504, so pass it tofetchand anything else that takes a signal (fetch(url, { signal: getSignal(c) })). Work not handed the signal carries on — the timeout frees the client and the socket, not the work. That the handler keeps running after the 504 is a property of a long-lived Node process, not a guarantee of the contract; anything that must complete belongs inwaitUntil. - Rate limit — API-key and signed-in callers share the data API’s buckets. Anonymous callers get their own, much looser allowance (3000 per window) because this router is public by default for webhook receivers. Override with
rateLimit.anonymousFunctions;nullswitches it off.
Unhandled promise rejections are logged rather than fatal: a fire-and-forget call in one function would otherwise end the whole process. Set REBASE_EXIT_ON_UNHANDLED_REJECTION=1 for Node’s default behaviour.
On Rebase Cloud, the edge in front of your functions has limits of its own, and module-level state, the filesystem and outbound ports behave in ways worth knowing before you design around them. See Managed backend runtime.
Next Steps
Section titled “Next Steps”- Backend Overview — Full backend configuration reference
- Table hooks — Run logic on data changes
- Cron Jobs — Scheduled background tasks