$npx -y skills add butterbase-ai/butterbase-skills --skill function-devUse when developing, deploying, or debugging Butterbase serverless functions, or when the user needs to add backend logic like webhooks, scheduled jobs, or custom API endpoints
| 1 | # Serverless Function Development on Butterbase |
| 2 | |
| 3 | Guide for developing and deploying serverless functions on Butterbase's Deno runtime. Covers handler signatures, trigger types, database access, environment variables, and testing. |
| 4 | |
| 5 | --- |
| 6 | |
| 7 | ## 1. Handler Signature |
| 8 | |
| 9 | Every function exports a single `handler` function with this signature: |
| 10 | |
| 11 | ```typescript |
| 12 | export async function handler( |
| 13 | request: Request, |
| 14 | context: { |
| 15 | db: PostgresClient, // RLS-aware DB client |
| 16 | env: Record<string, string>, // env vars set on the function |
| 17 | user: { id: string } | null, // present for HTTP+auth:required; null for cron |
| 18 | waitUntil: (p: Promise<unknown>) => void, // background work after Response (≤30s) |
| 19 | idempotency: { |
| 20 | claim: (key: string, opts?: { scope?: string; ttlSeconds?: number }) => Promise<boolean> |
| 21 | } // atomic dedup for webhook retries |
| 22 | } |
| 23 | ): Promise<Response> |
| 24 | ``` |
| 25 | |
| 26 | **CRITICAL**: The handler MUST return `new Response()` (Web API standard). Do NOT return plain objects. |
| 27 | |
| 28 | **Correct:** |
| 29 | ```typescript |
| 30 | return new Response(JSON.stringify({ message: "ok" }), { |
| 31 | status: 200, |
| 32 | headers: { "Content-Type": "application/json" } |
| 33 | }); |
| 34 | ``` |
| 35 | |
| 36 | **Wrong (will fail):** |
| 37 | ```typescript |
| 38 | return { status: 200, body: "ok" }; // NOT a Response object! |
| 39 | ``` |
| 40 | |
| 41 | --- |
| 42 | |
| 43 | ## 2. Trigger Types |
| 44 | |
| 45 | ### HTTP Trigger |
| 46 | |
| 47 | Invoke the function via an HTTP request. |
| 48 | |
| 49 | ```json |
| 50 | { |
| 51 | "trigger": { |
| 52 | "type": "http", |
| 53 | "config": { "method": "POST", "path": "/my-endpoint", "auth": "required" } |
| 54 | } |
| 55 | } |
| 56 | ``` |
| 57 | |
| 58 | **Auth options:** |
| 59 | - `"required"` — request must include a valid JWT; `ctx.user` is always set |
| 60 | - `"optional"` — JWT is parsed if present; `ctx.user` may be `null` |
| 61 | - `"none"` — public endpoint; no auth needed; `ctx.user` is always `null` |
| 62 | |
| 63 | --- |
| 64 | |
| 65 | ### Cron Trigger |
| 66 | |
| 67 | Execute the function on a schedule. |
| 68 | |
| 69 | ```json |
| 70 | { |
| 71 | "trigger": { |
| 72 | "type": "cron", |
| 73 | "config": { "schedule": "0 9 * * *", "timezone": "UTC" } |
| 74 | } |
| 75 | } |
| 76 | ``` |
| 77 | |
| 78 | Uses standard 5-field cron expressions: |
| 79 | - `"*/5 * * * *"` — every 5 minutes |
| 80 | - `"0 0 * * 0"` — weekly, Sunday at midnight |
| 81 | - `"0 3 * * *"` — daily at 3am UTC |
| 82 | - `"0 9 * * 1-5"` — weekdays at 9am |
| 83 | |
| 84 | Cron functions run as `butterbase_service` (RLS bypassed). `ctx.user` is always `null`. |
| 85 | |
| 86 | --- |
| 87 | |
| 88 | ### WebSocket Trigger |
| 89 | |
| 90 | Fire when a connected client sends a matching event over the realtime WebSocket. |
| 91 | |
| 92 | ```json |
| 93 | { |
| 94 | "trigger": { |
| 95 | "type": "websocket", |
| 96 | "config": { "event": "chat-message" } |
| 97 | } |
| 98 | } |
| 99 | ``` |
| 100 | |
| 101 | Fires when client sends matching event via realtime WebSocket connection. The `request` body contains the event payload sent by the client. |
| 102 | |
| 103 | --- |
| 104 | |
| 105 | ### S3 Upload Trigger _(placeholder — not yet implemented)_ |
| 106 | |
| 107 | ```json |
| 108 | { |
| 109 | "trigger": { |
| 110 | "type": "s3_upload", |
| 111 | "config": { "prefix": "uploads/", "contentTypes": ["image/*"] } |
| 112 | } |
| 113 | } |
| 114 | ``` |
| 115 | |
| 116 | --- |
| 117 | |
| 118 | ## 3. Database Access |
| 119 | |
| 120 | Use `ctx.db.query(sql, params)` for all database queries. Always use parameterized queries to prevent SQL injection — NEVER use string interpolation. |
| 121 | |
| 122 | ```typescript |
| 123 | // Always use $1, $2 placeholders — never string interpolation |
| 124 | const { rows } = await ctx.db.query( |
| 125 | 'SELECT * FROM posts WHERE author_id = $1', |
| 126 | [ctx.user.id] // params array |
| 127 | ); |
| 128 | ``` |
| 129 | |
| 130 | ### SELECT |
| 131 | |
| 132 | ```typescript |
| 133 | const { rows } = await ctx.db.query( |
| 134 | 'SELECT * FROM posts WHERE author_id = $1 AND published = true', |
| 135 | [ctx.user.id] |
| 136 | ); |
| 137 | ``` |
| 138 | |
| 139 | ### INSERT |
| 140 | |
| 141 | ```typescript |
| 142 | await ctx.db.query( |
| 143 | 'INSERT INTO logs (event, user_id) VALUES ($1, $2)', |
| 144 | ['page_view', ctx.user.id] |
| 145 | ); |
| 146 | ``` |
| 147 | |
| 148 | ### UPDATE |
| 149 | |
| 150 | ```typescript |
| 151 | await ctx.db.query( |
| 152 | 'UPDATE posts SET title = $1, updated_at = now() WHERE id = $2 AND author_id = $3', |
| 153 | [newTitle, postId, ctx.user.id] |
| 154 | ); |
| 155 | ``` |
| 156 | |
| 157 | ### RLS Behavior by Invocation Type |
| 158 | |
| 159 | | Invocation | Role | RLS | |
| 160 | |------------|------|-----| |
| 161 | | End-user JWT | `butterbase_user` | Enforced — `ctx.db` queries filtered by policies | |
| 162 | | API key (`bb_sk_`) | `butterbase_service` | Bypassed — sees all data | |
| 163 | | Cron trigger | `butterbase_service` | Bypassed — sees all data | |
| 164 | |
| 165 | --- |
| 166 | |
| 167 | ## 4. Environment Variables |
| 168 | |
| 169 | - **Set at deploy time**: pass `envVars` parameter to `deploy_function` |
| 170 | - **Update without redeploying**: use `update_function_env` |
| 171 | - **Access in handler**: `ctx.env.VARIABLE_NAME` |
| 172 | - **Encrypted at rest**: values are never exposed in logs or API responses |
| 173 | |
| 174 | Common uses: API keys, webhook secrets, external service URLs. |
| 175 | |
| 176 | ```typescript |
| 177 | const apiKey = ctx.env.OPENAI_API_KEY; |
| 178 | const webhookSecret = ctx.env.WEBHOOK_SECRET; |
| 179 | const serviceUrl = ctx.env.EXTERNAL_SERVICE_URL; |
| 180 | ``` |
| 181 | |
| 182 | --- |
| 183 | |
| 184 | ## 5. Complete Working Examples |
| 185 | |
| 186 | ### Example 1 — Protected API Endpoint (auth: required) |
| 187 | |
| 188 | Returns the authenticated user's posts. |
| 189 | |
| 190 | ```typescript |
| 191 | export async function handler(req, ctx) { |
| 192 | const { rows } = await ctx.db.query( |
| 193 | 'SELECT id, tit |