Skip to content

Edge Functions

Edge Functions run your own code on the server: webhooks, calls to third-party APIs, work that needs a secret. A function is one handler that receives the request and a ctx with the database, the caller and your secrets. It is served at /functions/v1/<name>.

In the dashboard open Functions → New, pick a template (hello, db, stripe, email or blank), edit the code and deploy. Or use the CLI:

Terminal window
potalab base functions new hello --template hello --remote # writes potalab/functions/hello/index.ts
potalab base functions deploy hello # builds on the server and activates
potalab base functions list [--versions hello]
potalab base functions rollback hello [--to <64-hex hash>]
potalab base functions delete hello --yes

Names match [a-z][a-z0-9_-]{0,62}. Commands need --project <ref> (or BASE_PROJECT_REF), BASE_API_URL and BASE_ACCESS_TOKEN. Without --remote, new only writes the file; the function is created on the project by the dashboard or --remote.

Export a default function (req, ctx). The return value becomes the response: a Response is sent as is, an object as JSON, a string as text/plain, and undefined as 204 No Content.

export default async function handler(req, ctx) {
const { data, error } = await ctx.db.from("todos").select("*").eq("owner_id", ctx.user.id).limit(20)
if (error) return Response.json({ error: error.message }, { status: 500 })
return { todos: data }
}
Field Meaning
ctx.db A client bound to the caller’s JWT. Row level security applies as for the Data API.
ctx.user id, role, email, claims of the caller. For a public function: id: null, role: "anon".
ctx.env Your secrets, as strings.
ctx.admin A service-role client, present only when allow_service_role is enabled in the function settings. Each use is audited; use it sparingly and never return its token. Reaches data, ctx.admin.auth.admin.* (create, update, ban, delete users) and ctx.admin.storage, always for this project.

The SDK package @potalab/base/functions exports defineFunction(handler) as a typing helper. It changes nothing at runtime.

  • Node modules (fs, net, node:*) are rejected at build time; use fetch for HTTP. Any package from the npm registry can be used: send package_json and package_lock with the deploy (lockfile required, registry sources only, install scripts never run; see the npm section). Operators can restrict packages with an allowlist, and a project can restrict itself.
  • Avoid I/O at module top level: the bundle is evaluated on every invocation, so it would run on each request. Do it inside the handler.
  • jwt (default): the request needs Authorization: Bearer <user JWT>, otherwise it fails with 401. ctx.user is the caller.
  • public: anyone can call it and it runs as anon. Use it for webhooks and verify signatures yourself.

In both modes ctx.db follows RLS for the caller’s role.

Secrets are write-only. Set them in the dashboard or with the CLI, which reads the value from stdin so it stays out of your shell history, then read ctx.env.NAME in the handler.

Terminal window
printf '%s' "$RESEND_API_KEY" | potalab base functions secrets set RESEND_API_KEY
potalab base functions secrets list # names and timestamps only
potalab base functions secrets unset RESEND_API_KEY

Names are uppercase ([A-Z_][A-Z0-9_]*) and may not start with BASE_.

A function can fetch only the hosts in its egress allowlist (function settings). An empty list, the default, blocks all outbound internet access, and the check repeats on every redirect.

  • One entry per host: api.stripe.com, *.example.com for subdomains (it does not match example.com itself), host:port to pin a port.
  • Private, loopback and metadata addresses stay blocked even if listed.
  • ctx.db and ctx.admin are not egress and always work. A change applies within about 15 seconds.
  • The stripe and email templates pre-fill the hosts they need.

base.functions.invoke sends POST by default, with the same credentials as the Data API. Plain objects and arrays are sent as JSON; strings, Blob, ArrayBuffer, FormData and URLSearchParams as is.

const { data, error } = await base.functions.invoke("hello", {
method: "POST", // GET | POST | PUT | PATCH | DELETE
body: { name: "Ada" },
})
Terminal window
curl -X POST "$API_URL/functions/v1/hello" \
-H "apikey: $PUBLISHABLE_KEY" \
-H "Authorization: Bearer $USER_JWT" \
-H "Content-Type: application/json" \
-d '{"name": "Ada"}'

The response is parsed by content type: JSON becomes an object, text/* a string, anything else a Blob, and 204 gives null. Errors are returned in error (never thrown), including network failures and invalid JSON. Streaming responses are not supported yet: the body is read in full.

Functions can also be written in Python. It is a beta, opt-in runtime: on Cloud it needs a plan with the python_functions feature (Go and Pro); on a self-hosted Community install it is off until the operator sets BASE_FN_PYTHON_ENABLED=1.

Define handler(req) or handler(req, ctx) in main.py. ctx has user, env (secrets), fetch, db and admin; fetch, Response and HttpError are already in scope. The return value can be a Response, a (status, headers, body) tuple, a dict or list (JSON), a str, bytes, or None (204).

def handler(req, ctx):
r = ctx.db.get("todos?select=id,title&limit=20") # runs as the caller, RLS applies
return r.json() if r.ok else Response.json({"error": "db_failed"}, status=500)
Terminal window
potalab base functions deploy hello --runtime python --file main.py [--vendor ./vendor] [--requirements requirements.txt]
  • Python 3.14 on a WebAssembly sandbox. Only the standard library allowed by the engine plus pure-Python packages (vendored, or name==version wheels that are py3-none-any). C-extension packages such as numpy, pandas, pydantic-core, cryptography or psycopg do not work.
  • No sockets, urllib or requests: use the fetch helper, which follows the same egress allowlist as JS functions.
  • Module state is not kept between calls. Bundle at most 4 MiB.
  • Same auth modes, secrets, logs and plan limits as above. Beta: performance numbers are preliminary.
Terminal window
potalab base functions logs hello --follow [--level debug|info|warn|error]

console.log output streams live over Realtime. There is no log history yet, and secrets are redacted.

The first call of a function is a cold start (a few tens of milliseconds). After it, the host keeps the instance warm and serves later calls from it, so a warm call only pays for your handler. Reuse never weakens isolation: before each call the runtime resets the global scope and the built-in objects, and runs your module’s top level again in a fresh scope. Module variables, globals and prototype changes never carry over between calls or between users. If an instance cannot be reset it is discarded and the call runs on a new one.

  • Do not keep data in memory between calls. Use the database or Storage; an in-memory cache only helps within a single call.
  • Keep the module top level light. It runs again on every call. Build big tables or parse large constants lazily, inside the handler, on the paths that need them.
  • ctx.db, ctx.ai, ctx.credentials and ctx.media are created on first use. A handler that never touches them does not pay for them.
  • Small bundles run faster. Import only what you use and prefer the built-in fetch, URL and crypto over large packages.
  • Self-hosting: a cold start costs about 50 ms of CPU against about 2 ms for a warm call, so what matters is how many calls can be warm at once. The host keeps at least BASE_FN_WARM_INSTANCES idle instances per engine (default 4) and, under load, as many as the recent peak of concurrent calls, within BASE_FN_WARM_MAX_MB of memory (counted as estimated RSS, about 25 MB per instance: linear memory plus BASE_FN_WARM_RSS_OVERHEAD_MB, default 14). Size BASE_FN_WARM_MAX_MB and the container memory for the concurrency you expect: 10 concurrent calls need about 250 MB, 50 need about 1.25 GB.

The throughput of one Community functions container is bounded by its CPU: the JavaScript engine runs without a JIT inside the sandbox, so each call costs a few milliseconds of CPU, and capacity grows with the CPU given to the functions container.

Each invocation runs in a sandbox with caps enforced by the host:

  • Timeout: 10 s by default (the function’s own setting, capped by the plan). Exceeded returns 504.
  • CPU time, memory and subrequests (each fetch is one): exceeded returns 546. The values depend on your plan.
  • Bundle: at most 5 MB, rejected at build time.
  • Functions per project and monthly invocations depend on your plan. Beyond them the API answers 402 plan_limit_exceeded.

Your code runs in a WebAssembly sandbox (Wasmtime). Operators who host the service add layers around it, so that even a flaw in the sandbox itself does not reach the host:

  • Container: non-root user, read-only root filesystem, no Linux capabilities, no-new-privileges. Always on.
  • Syscall allowlist (seccomp): the function host may only call about a hundred and twenty kernel functions; ptrace, mount, bpf, unshare, new namespaces and similar are refused. On by default in the Docker Compose files; opt-in in Helm (functions.seccomp.type: Localhost).
  • gVisor (optional): run the function host on runsc (docker-compose.gvisor.yml, or functions.gvisor.enabled in Helm) so user code talks to gVisor’s kernel instead of the node’s. It costs some syscall-heavy performance.
  • Dedicated node pool (Cloud): higher plans can run on their own nodes (functions.dedicated in Helm), so they never share a machine with other tenants.
  • Patching: the Wasmtime version is pinned and reported as the base_fn_build_info metric; advisories are checked every night and security updates follow a fixed schedule (Critical within 24 hours).

Installation is covered in Install; the hardening options are described in the README of the base-selfhost repository.