Functions, not SQL functions
A CubiBase Function is application code you deploy from the Console: a default-exported async handler that receives the request or event and a context with scoped database, storage and environment access. It runs on Node.js 22 in a separate, isolated environment per project and function, with no platform credentials and no access to other projects.
This is different from PostgreSQL SQL functions, which live inside your project database and are managed under Database → SQL Functions. Both exist; they do different jobs. Database Event Triggers bridge them: a committed INSERT, UPDATE or DELETE can invoke a CubiBase Function asynchronously.
Execution is regional today. CubiBase does not offer globally distributed edge execution.
Four ways to run
- HTTP: an HTTPS endpoint at https://{project}.api.cubibase.com/functions/{name}, supporting GET, POST, PUT, PATCH, DELETE and OPTIONS, with the exact raw request body preserved for signature verification.
- Database: after-commit INSERT/UPDATE/DELETE events on tables you subscribe to, captured atomically with your data change. A function failure never rolls back your transaction.
- Storage: object created, updated and deleted events from the existing Storage event stream, filtered by bucket and key prefix. Failed uploads never emit events; file contents never ride in the payload.
- Scheduled: standard cron expressions in UTC or a configured timezone, with last/next run visibility. Missed runs collapse into one catch-up run.
Database, storage and scheduled executions are asynchronous with at-least-once delivery, durable retries and a queryable dead-letter queue. Deduplicate on the event id — the templates show the pattern.
HTTP / HTTPS
Invoke backend logic through HTTP requests and webhooks.
/functions/{name}JWT, API key, public, or internal accessDatabase Events
Run logic in response to INSERT, UPDATE, and DELETE events on the tables you subscribe to.
public.orders · INSERTAfter commit · retriedStorage Events
Respond to objects being created, updated, or deleted in a bucket.
storage.object.createdBucket and prefix filtersScheduled / Cron
Execute backend jobs on cron schedules, in UTC or a configured timezone.
0 3 * * *schedule.tick
export default async function handler(request: any, ctx: any) {
const event = request.event;
// At-least-once delivery: skip work you already did for this eventId.
const seen = await ctx.db.from('processed_events').select({ event_id: event.eventId });
if (seen.rows?.length > 0) return { duplicate: true };
const record = event.operation === 'DELETE' ? event.oldRecord : event.newRecord;
await ctx.db.from('audit_log').insert([{
table_name: event.table,
operation: event.operation,
event_id: event.eventId,
record_id: String(record?.id ?? ''),
occurred_at: event.timestamp,
}]);
await ctx.db.from('processed_events').insert([{ event_id: event.eventId }]);
return { ok: true };
}
export default async function handler(request: any, ctx: any) {
const event = request.event; // storage.object.created, schemaVersion 1
console.log('New object:', event.path, event.sizeBytes, 'bytes');
const source = await ctx.storage.from(event.bucketName).download(event.path);
// ...transform source.body (a Buffer) here...
// Write derivatives to a DIFFERENT prefix so this function does not
// re-trigger itself. Function writes count toward the same quotas.
await ctx.storage.from(event.bucketName).upload(
event.path.replace(/^uploads\//, 'processed/'),
source.body,
{ mimeType: source.mimeType, overwrite: true },
);
return { processed: event.path };
}
export default async function handler(request: any, ctx: any) {
// request.event.type is 'schedule.tick'; the cron cursor already advanced.
// Equality filters only in ctx.db — for time ranges, find ids with
// read-only SQL, then delete by primary key.
const stale = await ctx.db.query(
"SELECT id FROM public.sessions WHERE expires_at < now() - interval '30 days' LIMIT 500",
);
let deleted = 0;
for (const row of stale.rows ?? []) {
await ctx.db.from('sessions').delete({ id: row.id });
deleted += 1;
}
console.log('Cleanup deleted', deleted, 'rows');
return { deleted };
}
Authentication and signed payloads
HTTP functions choose an authentication mode enforced by the gateway before your code runs: JWT (the default, using CubiBase Auth tokens), public, secret API key, or internal-only. Payload signature verification is a separate, independent setting.
- Built-in HMAC-SHA256: the gateway verifies the exact raw bytes with timestamp tolerance, constant-time comparison and single-use nonces (replay protection). Signing secrets are encrypted, shown once, and rotatable without dropped deliveries.
- Custom verification: Stripe, GitHub and other providers keep their own signature schemes. The function receives the untouched body and headers; the Stripe and GitHub templates verify them with constant-time checks.
- Secrets are encrypted at rest, never returned by read APIs, and redacted from logs. Functions reach your database and files through scoped CubiBase APIs with a short-lived, single-invocation credential — never a database password.
curl -X POST "https://example-project.api.cubibase.com/functions/openai-proxy" \
-H "Authorization: Bearer <USER_ACCESS_JWT>" \
-H "content-type: application/json" \
-d '{"prompt": "Summarize row-level security in one sentence."}'
curl -X POST "https://example-project.api.cubibase.com/functions/send-email" \
-H "apikey: cb_sec_YOUR_SECRET_KEY" \
-H "content-type: application/json" \
-d '{"to": "ada@example.com", "subject": "Welcome", "text": "Glad you are here."}'
import { createHmac, randomBytes } from 'node:crypto';
const body = JSON.stringify({ order: 4711, total: 4200 });
const timestamp = String(Math.floor(Date.now() / 1000));
const nonce = randomBytes(16).toString('hex'); // 16–128 chars, single use
const signature = createHmac('sha256', process.env.CUBIBASE_SIGNING_SECRET)
.update(`${timestamp}.${nonce}.`)
.update(body) // EXACT raw bytes you send — never re-serialize
.digest('hex');
await fetch('https://example-project.api.cubibase.com/functions/orders-hook', {
method: 'POST',
headers: {
'content-type': 'application/json',
'x-cubibase-timestamp': timestamp,
'x-cubibase-nonce': nonce,
'x-cubibase-signature': signature,
},
body,
});
Deployments that cannot break production
Every deploy builds an immutable version. Your code is bundled, never executed at build time, and imports are limited to Node built-ins plus a pinned dependency allowlist. A successful build atomically switches the active version; a failed build leaves the working version serving. Activate an older version to roll back.
Start from working code
Eight versioned templates generate editable, functional code with the right trigger and security defaults: Hello World, Stripe Webhook, GitHub Webhook, Send Email, OpenAI Proxy, Image Processing, Database Change Handler and Scheduled Cleanup. The Stripe template verifies Stripe-Signature on the raw body, deduplicates deliveries, and walks you through the Dashboard configuration — it never claims the integration is connected until a signed test event succeeds.
Every run is visible
Each invocation records its trigger, deployment version, duration, status, error category and captured console output — bounded, redacted and isolated per project. The Console shows execution history with filters, a delivery queue for async events, and per-function logs. Retention follows your plan.
Quotas on every trigger
Functions use the same subscription as the rest of CubiBase. Function count, concurrent executions and schedules are limited per project; invocations and compute (GB-seconds) are metered per organization per billing cycle, shared across all projects — the same convention as bandwidth. Every trigger type passes the same atomic reservations; there is no side door. By default, at a limit invocations are refused, not billed as overage (paid plans can explicitly enable metered additional usage with a spending limit); exhausting compute also refuses invocations even if invocation capacity remains. The Console’s Usage page shows live consumption, warnings at 50%, 75%, 90% and 100%, and exceeded state; the pricing page lists the current plan values.
HTTP/1.1 402 Payment Required
{
"error": {
"code": "FUNCTIONS_QUOTA_EXCEEDED",
"message": "Monthly invocation allowance exhausted…",
"details": { "quota": "functions_invocations_monthly", "limit": 100000, "used": 100000 }
}
}