The long tail of app-development - load that skill first for the core workflow (write a function, wire gipity.yaml, deploy, test). This reference covers the function runtime's module system in depth, verifying signed webhooks, choosing between a button-driven function and a workflow, plus operational details you reach for on demand.
ES module syntax - what you can write
The runtime compiles your code as a real ES module (since 2026-05-29). Any valid single-file ESM parses cleanly:
// All of this works in one file:
import { z } from './schemas.js'; // relative imports (multi-file only - see below)
export const VERSION = 3; // top-level const, exported or not
export function validate(input) { ... } // named exports alongside the default
const cfg = await loadConfig(); // top-level await
export default async function handler(ctx, { db }) { ... }
What does NOT work and the exact error you'll see:
- Bare imports (
import _ from 'lodash') → "Bare import 'lodash' is not allowed in function code. Use a relative path like './helpers.js'." Nonode_modules, no built-in Node modules (fs,path,crypto- for secrets use the injectedrandomToken(chars)service, for hashing/HMAC the injectedcryptoservice). - No default export → "Function must `export default` a callable handler."
- Default export isn't a function → "Function 'export default' must be a function (got object)."
- Genuine parse error → "Function file 'index.js' did not parse:
" - the file name in the message tells you which file the error is in (helpful in multi-file functions).
Multi-file functions
When a function grows past a single file - testable helpers, shared constants, etc. - turn it into a directory:
functions/
song-render/
index.js # entry - must have `export default async function ...`
sanitize.js # helper - `export function sanitizeRenderOptions(...)`
constants.js # `export const DEFAULT_MODE = 'preview'`
index.js is the entry; sibling files are reached via relative import:
// functions/song-render/index.js
import { sanitizeRenderOptions } from './sanitize.js';
export default async function songRender(ctx, { db, jobs, guid }) {
const opts = sanitizeRenderOptions(ctx.body?.render_options);
// ...
}
Why use multi-file:
- Testable helpers. Unit-test directly from
tests/*.test.jswithimport { x } from '../functions/song-render/sanitize.js'. Single-file helpers can only be exercised through end-to-end function calls. - Cleaner separation. Pure helpers stay pure.
Pass services into helpers as arguments. The entry's handler receives (ctx, services). The service names also resolve as free globals in any module, but a helper that reaches for a global db can't be unit-tested from tests/, so keep helpers pure: if a helper needs the DB, the entry passes it in:
// functions/song-render/sanitize.js - PURE helper, no service access
export function sanitizeRenderOptions(raw) { /* validates raw, returns clean obj */ }
// functions/song-render/persist.js - needs db, so accept it as arg
export async function saveRender(db, songGuid, opts) {
await db.query('INSERT INTO renders ...', [songGuid, opts]);
}
// functions/song-render/index.js - entry passes db down
import { sanitizeRenderOptions } from './sanitize.js';
import { saveRender } from './persist.js';
export default async function (ctx, { db }) {
const opts = sanitizeRenderOptions(ctx.body);
await saveRender(db, ctx.body.song_guid, opts);
}
Import rules and errors:
- Imports must be relative -
./helper.jsor./utils/foo.js(bare specifiers rejected as above) - Imports can't escape the function directory -
../../etc/foo.jsfails with "Import '../../etc/foo.js' escapes the function directory." The one sanctioned exception is the shared_lib/module dir (next section). - A missing sibling fails clearly: "Cannot resolve import './nope.js' → 'nope.js' - file not in function payload. Available: index.js, sanitize.js"
- Circular imports work (a → b → a) - ESM cycles resolve via the module loader's link cache
- The entry filename is always
index.js
Limits: up to 20 files per function (shared _lib files count toward this), 256 KB total source, max 4 levels of nesting.
Pick the shape that fits: single functions/foo.js for simple handlers; functions/foo/ directory once you have a helper you'd like to unit-test.
Shared modules across functions (functions/_lib/)
When two or more functions need the same code - a schema registry, validation, SQL builders - put it in functions/_lib/ instead of copy-pasting it into each function directory (copies drift):
functions/
_lib/
registry.js # shared - `export function describeObject(...)`
record-read/
index.js # imports it: `import { describeObject } from '../_lib/registry.js'`
record-write.js # single-file functions can import it the same way
At deploy, _lib/ files are bundled into every function's payload, so editing a shared module re-deploys all functions automatically. The rules:
- Import as
../_lib/<file>.jsfrom any function file (single- or multi-file)._lib/is a rooted shared target, so the count of../doesn't matter:./_lib/x.js,../_lib/x.js, and../../_lib/x.jsall reach the same shared module from any depth _libfiles may import each other (./fmt.js) but can't import function files - shared code stays function-agnostic- Keep
_libfiles pure like helpers: the entry passesdb/ctx/services in as arguments, so the module stays unit-testable fromtests/. Naming is free: a_libexport calledrandomTokenordbdoesn't clash with the injected services _libis reserved: a function named_libor a_lib/subdirectory inside a function directory is a deploy error- Unit-test shared modules from
tests/*.test.jsviaimport { x } from '../functions/_lib/registry.js'
The function runtime supports single-file ESM (shipped 2026-05-29), multi-file functions with relative ./helper.js imports (2026-05-30), and shared _lib modules imported as ../_lib/<file>.js (2026-06-09).
Kits that ship backend pieces (gipity add contacts ...)
Some kits install more than frontend code. A kit whose manifest declares
functions: true / migrations: true copies its functions/ and
migrations/ trees into the app's own functions/ and migrations/:
contacts (contact-* functions and the contact tables), stripe
(payment-events, payment-status, the payments/subscriptions tables) and
leaderboard (leaderboard-* functions and the board tables). They need a
database template (web-fullstack or api). Rules:
- Kit-owned files are sealed. Functions,
_libmodules, and migrations a kit installs are upgraded by re-runninggipity add <kit>at a newer version, which overwrites them. Never edit them in place; put app code in your own function/migration files. - Kit migrations order themselves by filename (
000-kit-*.sqlsorts before your001-*.sql). If the app has nosqldeploy phase, the install adds one. - The kit's
gipity.yamlfunction entries declare only the kit's own tables. If a kit function must touch one of your tables, append it to that entry'stables:yourself. Your edits survive re-install: entries are merged by name, a newer kit version only adds the list items it needs, and your scalar settings (auth,limits) are kept. - Kits can require other kits (
requires: ["<kit-key>"]in the manifest) -adderrors with the missing prerequisite's name.
Versioning & Rollback
A function is deployed from its source file, and every file save keeps a version. To roll a function back, restore the file and redeploy:
gipity file versions functions/my-function.js
gipity file restore functions/my-function.js 3
gipity deploy
Management Commands
gipity fn list # List all functions
gipity fn logs <name> # Execution logs
gipity fn call <name> [body] # Call one
gipity fn delete <name> # Delete
Rate Limits
- 300 requests per 5-minute window, counted per caller: each project API key has its own budget, a signed-in user (or app player) has theirs, and anonymous traffic counts per IP. So several devices behind one home router each get a full budget when each uses its own key. Shared across all Gipity servers. Waived during
gipity test(all test runs share one sandbox IP, so the platform exempts a project's own test run; see "What else is isolated" in app-testing) - Per-invocation governors (queries, rows, fetches, service calls) and the 1 MB function response: see app-database and app-function-services
Verifying webhook signatures (via crypto)
Third-party webhooks (Stripe, GitHub, Shopify, Slack, Svix/Clerk) sign the raw request body with an HMAC of a shared secret and send the signature in a header. Point the provider at https://a.gipity.ai/api/<appGuid>/fn/<name> (an auth: public function, the default), store the signing secret with gipity secrets set WEBHOOK_SECRET <secret>, and verify before doing anything:
// functions/github-webhook.js
export default async function (ctx, { secrets, crypto }) {
const secret = await secrets.get('WEBHOOK_SECRET');
const expected = 'sha256=' + crypto.hmac('sha256', secret, ctx.rawBody);
const got = ctx.headers['x-hub-signature-256'] || '';
if (!crypto.timingSafeEqual(expected, got)) return { error: 'bad signature' };
// Verified: now trust ctx.body (the same bytes, parsed).
return { ok: true, action: ctx.body.action };
}
- Sign
ctx.rawBody, neverJSON.stringify(ctx.body). Re-serializing changes whitespace, key order and numbers like1.0, so the HMAC never matches. - Compare with
crypto.timingSafeEqual(a, b), not===(which leaks how much of the signature matched). - Per-provider shapes: Stripe signs
t + '.' + ctx.rawBodyand sendsstripe-signature: t=...,v1=<hex>(also reject a stalet); Shopify sends base64, so pass'base64'as the 4th arg; Slack signs'v0:' + ts + ':' + ctx.rawBody; Svix/Clerk secrets arewhsec_<base64>, so strip the prefix and pass{ encoding: 'base64', keyEncoding: 'base64' }. - API:
crypto.hmac(algorithm, key, data, encoding?)andcrypto.hash(algorithm, data, encoding?)take strings and return a digest string; algorithm is'sha1' | 'sha256' | 'sha384' | 'sha512', encoding'hex'(default)| 'base64' | 'base64url', or an options object{ encoding, keyEncoding }wherekeyEncodingis'utf8'(default)| 'hex' | 'base64' | 'base64url'.crypto.timingSafeEqual(a, b)compares two strings (false on different lengths).crypto.randomUUID()returns a v4 UUID. Data is capped at 10 MB per call, keys at 4 KB. No declaration needed ingipity.yaml. - Stripe payments through Gipity's own
stripekit are already verified by the platform before they reachpayment-events; this recipe is for webhooks you receive directly.
On-demand actions: button to function vs. a Gipity workflow
When the user wants to "trigger" or "run on demand" something, pick by where it runs:
- A button in the app → frontend button calls
Gipity.fn(name, body)→ your function (the pattern above). Use this whenever the action needs the browser: the user's current GPS location, a file they picked, form input - anything client-side. "Record my location on a button" is this: only the browser has the device's location. - A Gipity workflow (
workflowskill) → server-side automation that runs with no browser, on atrigger:schedule(cron),manual(gipity workflow run <name>),webhook, or arecord.after_insert/update/deletedata change. Author it asworkflows/<name>.yamlwith aworkflowsdeploy phase. Use it for recurring / time-driven / event-driven server jobs ("every morning", "when a row lands").
A workflow can't read the user's device or DOM, so don't model a browser-driven button as one.
Related Skills
app-development- the core guide: function shape,ctx,gipity.yamlpermissions, and the deploy/test loopapp-function-services-fetch, app services,secrets,envandconsolefrom a functionapp-files-storage- thestoragehelper: import a file from a URL (e.g. a webhook's finished render), check an upload's owner, deleteapp-database- the per-app Postgres database: migrations, thedbhelper, transactions, table permissionsapp-testing- testing deployed functions:ctx.fn.call/callAs, the isolated test DB, fixturesdeploy- the deploy pipeline andgipity.yamlmanifest