Write a function
Goal
Add a custom Netlify function when — and only when — the generic /api/admin-data endpoint cannot cover the case: specialized auth, inbound webhooks, heavy compute, or bespoke orchestration. Record CRUD must go through admin-data so permission, validation, audit, and trigger logic stay shared (Runtime records).
Steps
- Decide it is warranted.
admin-dataalready covers list/get/create/ update/remove/stats across every runtime table with permissions and triggers enforced (admin-data reference). Legitimate custom functions: public webhook receivers, scheduled sweeps, compute-heavy transforms, auth-bridging endpoints. Create the file. Put it in
custom/functions/(orcustom/apps/<slug>/functions/for app-scoped code) with acustom_prefix — assembly copies.framework/functions,custom/functions, andcustom/apps/*/functionsinto one flat Netlify dir and fails the build on a basename collision (scripts/assemble-functions.sh). All functions are reachable at/api/<basename>via the_redirectsrule (.framework/public/_redirects). Imports resolve in the assembled layout, not the source tree:./_shared/*and./<other-function>are sibling paths inside.assembled/netlify/functions/, and@shared/*is an alias to the same dir (config/tsconfig.functions.json). A function's ownfunctions/_shared -> .framework/functions/_sharedsymlink (as the existing app functions dirs carry) makes./_sharedresolve in the source tree too.// custom/functions/custom_my-endpoint.ts import { createHandler, error, json } from './_shared/middleware' import { adminDb } from './_shared/db' import { PermissionEngine } from './_shared/permissions' import { emitLog } from './_shared/logging' export const handler = createHandler(async (ctx, body) => { // ctx.requestId, ctx.principal, ctx.db, ctx.accountId, ctx.appId, // ctx.query, ctx.headers, ctx.trace — all populated by middleware if (!PermissionEngine.isSystemAdmin(ctx)) { throw new Error('System admin required') } const { data, error: err } = await ctx.db .from('items').select('id,title').eq('is_active', true).limit(10) if (err) throw err return data })Follow the
createHandlercontract (.framework/functions/_shared/middleware.ts):- The middleware resolves the principal (
x-api-key→ internal secret → Bearer JWT), buildsRequestContext, and wraps your return value in the{ data, error, meta }envelope. ThrownErrors become{ error }responses — don't build response objects yourself. ctx.dbis the principal-scoped client (humans get a user-scoped, RLS-bound client; machines/anonymous getadminDb).ctx.querymergesqueryStringParameters;ctx.query.methodcarries the HTTP method. Functions dispatching on?action=use aswitch (ctx.query.action)(see.framework/functions/timers.ts).- For endpoints that must accept anonymous or raw requests, use
createPublicHandlerinstead (same file,createPublicHandler).
- The middleware resolves the principal (
- Use the
_sharedmodules, don't reinvent them —db(adminDb,getUserDb),permissions(PermissionEngine,isSystemAdmin,sanitizeRecordData),principal(resolvePrincipal,SYSTEM_PRINCIPAL),audit/logging(emitLog,emitAudit),resolve-ids,rate-limit— see Shared modules reference and Functions index. - Assemble and run.
npm run assemble && npm run dev:netlify, thencurl http://localhost:8888/api/custom_my-endpoint— see Install and first run. Function typecheck is separate fromnpm run typecheck:npx tsc --noEmit -p config/tsconfig.functions.jsonchecks the assembled output (run it afterassemble).
Verify
GET /api/custom_my-endpointreturns the{ data, error, meta }envelope; unauthenticated calls return401 Authentication requiredfrom the middleware, not from your code.npm run assemblepasses (no basename collision error) andnpm run typecheckcompiles.
Common mistakes
- Duplicating a framework basename. Assembly hard-fails naming both sources — prefix custom files
custom_. - Returning raw Response objects.
createHandlerexpects a return value (serialized intodata) or a thrown error — don't emit Netlify{statusCode, body}shapes yourself inside acreateHandlerfunction. - Using
adminDbfor user-facing reads. It bypasses RLS — preferctx.dbunless you intentionally need service-role access. - Putting secrets in the response.
sanitizeRecordData/omitSecretFieldsexist for a reason — strip credentials before returning. - Writing record CRUD — if the function creates/updates
items,threads, etc., you are bypassingadmin-data; call it viaadminDataCreate//api/admin-datainstead.