Platform Functions
Platform functions are standalone serverless endpoints scoped to your project. Unlike component functions which are attached to a specific component, platform functions are independent — they receive HTTP requests and return HTTP responses, making them ideal for webhooks, API endpoints, integrations, and custom backend logic.
Overview
Each platform function consists of a name and one or more versioned expressions (JavaScript code). Functions run inside a secure sandbox with full access to the platform SDK and utility libraries.
Key characteristics:
- HTTP-native — receive request body, query params, headers, form data, and file uploads
- Must return a
responseobject — supports JSON, HTML, XML, redirects, and custom status codes - Versioned — separate dev and public versions for safe iteration
- Public access — optionally expose functions without authentication via signed URLs
- Environment variables — per-function and per-environment configuration
Creating a Function
API
A new function is created with an empty expression and a default dev version of 0.1.0.
Add run_as to name the identity the function runs as. Without it the function runs as Maintainer, which only the Owner and Maintainers can choose. Anyone else is refused with 403 identity_required, listing the identities they may choose.
See Run identity.
SDK
import { Functions } from "@ptkl/sdk"
const functions = new Functions()
const list = await functions.list()
const fn = await functions.get("send_welcome_email")
Signature
A platform function can declare a typed signature that describes its expected input and output. When set, $input.body is validated against signature.input before the expression executes — if the caller sends data that doesn't match, the call is rejected immediately with a structured error.
{
"signature": {
"input": {
"amount": { "type": "number", "required": true },
"currency": { "type": "string", "required": true },
"discount": { "type": "number", "required": false }
},
"output": {
"type": "object",
"fields": {
"net": { "type": "number" },
"vat": { "type": "number" },
"gross": { "type": "number" }
}
}
}
}
The signature is edited in the Signature tab inside the platform function editor. Types use the same TypeDef structure as component IDLs.
Validation is open (lenient) — extra fields on objects are accepted, only missing required fields and type mismatches cause failures. When no signature is set, no validation is applied.
Tip
When a signature is defined, the expression editor automatically provides $input autocomplete and type errors based on the declared input shape.
Writing a Function
A platform function is a JavaScript expression that processes an incoming request and returns a response using the response object.
Basic Example
Full Example
// Validate input
if (!$input.body?.email) {
response.status(400).json({ error: "Email is required" })
return response
}
// Use the SDK to interact with components
const { Component } = $sdk.version('0.9')
const users = new Component("users")
// Check if user already exists
const existing = await users.findOne({ email: $input.body.email })
if (existing) {
response.status(409).json({ error: "User already exists" })
return response
}
// Create the user
const user = await users.create({
email: $input.body.email,
name: $input.body.name,
status: "pending"
})
response.status(201).json({ user_id: user.uuid })
Running a Function
Authenticated
The {ref} can be the function's UUID, name, or tag.
Public (No Authentication)
Public functions can be called without any authentication using a signed URL:
POST /v1/system/function/public/{signature}/run/{ref}
GET /v1/system/function/public/{signature}/run/{ref}
To generate a public URL:
import { Functions } from "@ptkl/sdk"
const functions = new Functions()
const { data } = await functions.generateSignature("send_welcome_email", "live")
// Returns a ready-to-use public URL
Note
Public functions do not have access to $globalEnv or $initiator. SDK calls within the function are authorized as its run identity.
The response Object
Platform functions must build their response using the global response object. This is what differentiates them from component functions, which simply return a value.
All methods return this for chaining.
| Method | Description |
|---|---|
response.json(body) |
Send a JSON response (application/json) |
response.html(body) |
Send an HTML response (text/html) |
response.xml(body) |
Send an XML response (text/xml) |
response.send(body) |
Send a generic JSON response |
response.status(code) |
Set the HTTP status code |
response.redirect(url) |
Send a 307 redirect |
Examples
// JSON response with custom status
response.status(201).json({ created: true })
// HTML page
response.html("<h1>Welcome</h1><p>Your account has been created.</p>")
// XML response
response.xml("<result><status>ok</status></result>")
// Redirect
response.redirect("https://example.com/thank-you")
// Error response
response.status(422).json({
error: "Validation failed",
fields: { email: "Invalid email format" }
})
Execution Context
Request Input
The $input object contains the parsed HTTP request:
| Property | Type | Description |
|---|---|---|
$input.body |
object |
JSON-parsed request body |
$input.query |
object |
Parsed URL query parameters |
$input.headers |
object |
Request headers (only X-Func-* prefixed) |
$input.form_data |
object |
Parsed multipart form data fields |
$input.files |
array |
Uploaded files from multipart requests |
// Read JSON body
const email = $input.body?.email
// Read query parameters
const page = $input.query?.page || "1"
// Read custom headers
const source = $input.headers?.["X-Func-Source"]
// Access uploaded files
const file = $input.files?.[0]
if (file) {
console.log(file.key, file.filename, file.size)
}
Environment & Configuration
| Variable | Type | Description |
|---|---|---|
$env |
object |
Per-function environment variables for the current environment |
$globalEnv |
object |
Project-level global environment variables |
$currentEnv |
string |
Current environment name ("dev" or "live") |
$initiator |
object |
The user or service that invoked the function (authenticated only) |
$sdk |
object |
Protokol SDK factory — $sdk.version('0.9') |
// Per-function env var
const apiKey = $env.STRIPE_SECRET_KEY
// Global env var
const webhookSecret = $globalEnv.WEBHOOK_SECRET
// One group of global env
const stripeKey = $globalEnv.group("payments").STRIPE_KEY
// Environment check
if ($currentEnv === "dev") {
console.log("Running in development mode")
}
Versioning
Each function supports multiple versions, with two active pointers:
| Pointer | Description |
|---|---|
| Dev version | Used when the function runs in the dev environment |
| Public version | Used in all other environments (production) |
This allows you to iterate on a function in development without affecting production traffic.
Updating a Function
{
"settings": [
{ "version": "0.1.0", "expr": "response.json({ v: '0.1.0' })" },
{ "version": "0.2.0", "expr": "response.json({ v: '0.2.0' })" }
],
"dev_version": "0.2.0",
"public_version": "0.1.0"
}
import { Functions } from "@ptkl/sdk"
const functions = new Functions()
await functions.update("function-uuid", {
settings: [
{ version: "0.1.0", expr: "response.json({ v: '0.1.0' })" },
{ version: "0.2.0", expr: "response.json({ v: '0.2.0' })" }
],
dev_version: "0.2.0",
public_version: "0.1.0"
})
Environment Variables
Functions support per-environment variables stored in the function definition:
{
"env_variables": {
"dev": {
"STRIPE_SECRET_KEY": "sk_test_...",
"WEBHOOK_URL": "https://dev.example.com/hook"
},
"live": {
"STRIPE_SECRET_KEY": "sk_live_...",
"WEBHOOK_URL": "https://example.com/hook"
}
}
}
These are available as $env inside the function. The correct set is selected based on the execution environment.
Secret Values
A value that holds a key, token or password can be stored as a secret. Secrets are encrypted, write-only and never shown again. Read the security model for who can reach them. The same prefixes work in function env and in the project's global env:
| You write | Meaning | Reads back as |
|---|---|---|
secret::<value> |
Stores <value> as a secret, replacing the one at this key. |
secretref:: |
secretgen::random(n[, alnum\|alpha\|hex\|digits\|base64url]) |
Generated by the platform, only if the key has no secret yet. An existing value is kept. The generator is not stored. | secretref:: |
secretref:: |
Keeps the secret already stored at this key. | secretref:: |
literal::<value> |
A plain value that starts with a reserved prefix. | literal::<value> when the value starts with a reserved prefix |
{
"env_variables": {
"dev": {
"STRIPE_SECRET_KEY": "secret::sk_test_x1234567",
"SESSION_KEY": "secretgen::random(64)",
"WEBHOOK_URL": "https://dev.example.com/hook"
}
}
}
Reading the function back returns secretref:: for both secrets and the plain value as it is. Your code receives the real values in $env.
- A
secret::value is 8 characters to 32 KiB. A shorter or longer one is refused with422. nis at most4096. A generator that gives less than 128 bits of entropy is refused with422, as in component secrets.uuidis not a generator.secret::,secretgen::,secretref::,literal::andenc::are reserved. A value starting withenc::is refused with422.- A write replaces the whole env of the environment you send. Send
secretref::back for every secret you want to keep. A write that leaves a secret key out removes it.secretref::for a key with no stored secret is refused with422. - Every
422for an env value saysinvalid function env value(invalid global env valuefor global env) and does not echo the value.
Replacing a secret
A secret cannot be read back. To replace it, set it again with secret::<new value>. For a generated key, delete it and generate a new one.
Permissions
| Change | Permission |
|---|---|
| Set, generate, replace or remove a secret in function env | manage base_functions and secrets::write base_functions |
| The same in global env | manage global_env and secrets::write global_env |
Keep a secret with secretref::, or change plain values |
The resource's own permission only |
| Change a function's code, or the identity it runs as, when its env has encrypted values | secrets::read base_functions, and the function's run identity |
Without the permission, the request is refused with 403 and nothing is saved:
The dashboard shows an encrypted value as Encrypted, with the text "Write-only: this value is hidden and cannot be read back." Without secrets::write, the value is read-only: "Read-only: you need the secrets::write base_functions permission to change secret values here." No button or route shows the value.
A change to a function's code or run identity without secrets::read base_functions is refused with 403 and permissions_not_held, naming that permission.
Global Env
Global env is the project-level $globalEnv. It takes the same prefixes and rules as function env. Encrypted global values reach a run only when the identity the code runs as holds secrets::read global_env. Without it, the run gets the plain values and the encrypted keys are left out.
Global env can be split into groups. A group has its own keys and its own secret permissions, secrets::read global_env.<group> and secrets::write global_env.<group>. secrets::read global_env covers every group, while secrets::write global_env covers the default group only.
A run sees every group's keys at the top level of $globalEnv, with no group name in the path. A key name lives in one group only, so groups never overwrite each other.
To read one group, call $globalEnv.group(name). It returns a plain object with that group's keys and the same values the run sees at the top level. The default group is "default", and an unknown group returns {}. An encrypted key the run identity may not read is left out, as at the top level: reading a group needs secrets::read global_env.<group>, and secrets::read global_env covers every group. group does not appear in Object.keys($globalEnv), JSON or a spread.
group is a reserved key name, so a new key named group is refused. An existing key named group keeps its value, but then that project's code has no group() method until the key is renamed.
Public Functions
Making a function publicly accessible allows external services to call it without authentication — useful for webhooks, callbacks, and public APIs.
Setup
-
Choose the run identity, then enable public access:
A public run uses the function's run identity for SDK calls made inside the function, with no caller to take permissions from. A function with no
run_asruns as Maintainer. Before you make a function public, set a narrowrun_as: an identity that holds only what the function needs. See Run identity. -
Generate a signed URL:
This returns a URL with an embedded signature that encodes the project and environment.
-
Call the public endpoint:
Public function limitations
$globalEnvis not available$initiatoris not available- The function runs as its run identity (Maintainer when none is set), so set a narrow one first
Debugging
Console Logs
To retrieve debug data, include the X-Debug: true header (or ?_debug=true query param for public functions). Only data added with debug.add() is returned; console.log() output is not part of the response:
The response will include a _debug field with the data added through debug.add().
debug
Add structured debug data:
Available Libraries
Platform functions have access to the same libraries as component functions. See that page for the full list with usage examples.
Core Utilities
| Global | Description |
|---|---|
moment |
Date/time manipulation |
_ |
Lodash utility functions |
Handlebars |
Template engine |
Buffer |
Binary data operations |
Security & Encoding
| Global | Description |
|---|---|
bcrypt |
Password hashing — genSalt, hash, compare |
crypto |
Cryptographic operations — hash, hmac, encrypt, decrypt, sign, verify |
jwt |
JSON Web Tokens — sign, verify, decode |
Identifiers & Encoding
| Global | Description |
|---|---|
uuid |
UUID generation — uuid.v4(), uuid.v5(), uuid.validate() |
nanoid |
Nano ID generation — nanoid.generate(), nanoid.custom() |
btoa |
Base64 encoding — btoa(string) |
atob |
Base64 decoding — atob(base64) |
Expression & Authentication
| Global | Description |
|---|---|
jexl |
JavaScript expression language |
otp |
OTP/2FA token generation and verification |
Error Handling
Errors thrown inside a platform function are caught automatically and returned via the response object:
// The runtime catches uncaught errors and calls response.setError()
throw new Error("Something went wrong")
For structured error responses, set the status and body explicitly (on the authenticated run endpoint a 500 status is replaced by {"message": "internal server error"}, so use another status code for errors the caller should read):
response.status(500).json({
error: "Payment processing failed",
code: "PAYMENT_ERROR",
details: { provider: "stripe", reason: "card_declined" }
})
Permissions
| Action | Required Permission |
|---|---|
| Create, update, delete, list | manage base_functions |
| Set, generate, replace or remove an encrypted env value | secrets::write base_functions, in addition to manage base_functions |
| Create or change code with encrypted env values | manage base_functions and secrets::read base_functions |
| Choose the run identity | Hold the identity. See Run identity |
| Run a specific function | run function::{name} |
| Public execution | No permission required (runs as the function's run identity) |
Run Identity
A function runs as its run_as identity, with that identity's permissions as of each run. It does not run with the permissions of the person who calls it or last saved it. A function saved before run identities existed has no run_as and runs as Maintainer.
Whoever can change a function acts as its identity and reads its env. Changing it needs the run identity, manage base_functions, and secrets::read base_functions when its env has encrypted values. Making it public needs manage base_functions, as before.
A function that lets an input choose where data goes, or skip a check, has a bug. Treat the request body, query and headers as untrusted.
Full rules and refusals: Run identity.
Capabilities
A platform function runs as its chosen run identity and declares no capabilities. Code that can be narrowed lives in component functions and workflow expression nodes.
Execution Environment
| Property | Value |
|---|---|
| Memory limit | 128 MB |
| Timeout | 30 seconds |
| Async support | Full async/await |
| Call depth | Maximum 5 nested function calls |
| File upload | Up to 15 GB |
Warning
Functions run in an isolated sandbox. Node.js system modules (e.g. fs, path, net) are not available. Use the SDK and provided libraries instead.