Skip to content

Function runtimes ​

A function runtime is one self-contained source file, compiled to WebAssembly and run in Wasmtime for a single request. There is no npm, pip, Cargo, or Go modules on the platform. Pass language to edge_function_create as one of the values below. Ask your agent to start from the platform template for that language.

Walk through creating one in Add an endpoint. Caps are in Limits.

Languages ​

languageRuns asABIToolchain
javascriptinterpreted in wasmhandler-v1Javy 9.1.0 (QuickJS, source snapshotted in)
pythoninterpreted in wasmhandler-v1RustPython 0.5.0 (Python 3 dialect), Wizer snapshot
rustcompiled to wasmwasi-command-v1rustc --target wasm32-wasip1, std only
tinygocompiled to wasmwasi-command-v1TinyGo -target=wasip1, GOPROXY off
ccompiled to wasmwasi-command-v1wasi-sdk clang, -std=c17
assemblyscriptcompiled to wasmwasi-command-v1AssemblyScript with the WASI shim

All six are available. The request never includes headers, cookies, a query string, or auth.

handler-v1 — JavaScript and Python ​

A top-level handler(request, env) returns {statusCode, headers, body} or a bare string (a 200). statusCode is 100–599, default 200. body is a string, or bytes for a file (see Binary bodies). request is {method, path, body, bodyEncoding} with body a string or null. env carries the distribution's stores — env.document, env.kv, env.sql, env.file and env.upload — each gated by a grant, env.queue, gated by the queue's senders, env.workflow, gated by the function's workflow_starts, and env.base64 for bytes. A handler that takes only request still works. edge.document, the older global, is the same object as env.document; the other stores are on env only.

JavaScript is a script, not a module: no import, require, or export. Bundle libraries locally with esbuild yourscript.js --bundle --format=iife --outfile=bundle.js and submit bundle.js. console.* goes to the log. async handlers settle on microtasks only — there are no timers, so awaiting anything that is not already resolved never completes. Math.random() repeats the same sequence for a given artifact; do not use it for tokens or ids.

javascript
function handler(request, env) {
  return {
    statusCode: 200,
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({ method: request.method, path: request.path })
  };
}

Python uses the same shape (def handler(request, env) with a dict). print() goes to the log. Only RustPython's bundled pure-Python standard library is importable. Vendor other pure-Python into the one file. C-extension packages (numpy, pandas, cryptography, lxml, pydantic_core) and socket, ssl, subprocess, threading, asyncio, http, urllib.request, and ctypes are refused at build time. RustPython is not CPython; check odd corners with edge_function_invoke. async def handler works only if nothing suspends — there is no event loop.

python
import json

def handler(request, env):
    return {
        "statusCode": 200,
        "headers": {"content-type": "application/json"},
        "body": json.dumps({"method": request["method"], "path": request["path"]}),
    }

wasi-command-v1 — Rust, TinyGo, C, AssemblyScript ​

The program is main (AssemblyScript: top-level). Stdin is one JSON object {"method","path","body","bodyEncoding"}. Method and path are also argv[1] / argv[2] and $METHOD / $PATH. Write exactly one {"statusCode","headers","body"} to stdout and exit 0. Anything else on stdout, or a non-zero exit, is a generic 500 for the visitor. Stderr is the log. Headers are an object of strings; body is a string. To return a file, add "bodyEncoding":"base64" and put base64 in body (see Binary bodies).

Standard library only:

  • Rust — no Cargo, no crates, no serde. include!, include_str!, include_bytes! and out-of-line mod name; are refused; modules must be inline.
  • TinyGo — no Go modules, no cgo. encoding/json works; prefer plain structs.
  • C — #include <header.h> from the wasi-sdk sysroot only. Quoted includes, #embed and .incbin are refused.
  • AssemblyScript — standard library and WASI-shim globals only. No JSON in the standard library.

Binary bodies ​

A function can take a file in and send a file back: a PDF receipt, a CSV export, a generated image.

Request. bodyEncoding tells you how to read body:

bodyEncodingWhenbody
"utf8"the request's content-type is text (text/*, JSON, XML, a form) or missing, and the bytes are valid UTF-8the text
"base64"anything else, such as image/png or application/pdfbase64 of the exact bytes
nullno bodynull

Request bodies stay capped at 1 MiB. For larger uploads, use a form upload instead of posting the file to a function.

Response. Set a content-type header and return the bytes:

LanguageReturn
JavaScripta Uint8Array or ArrayBuffer as body
Pythonbytes or bytearray as body
Rust, TinyGo, C, AssemblyScript"bodyEncoding":"base64" and base64 in body

Any language may also return a base64 string with bodyEncoding: "base64". The content-type header is required for a binary body; without it the visitor gets a generic 500. The decoded body may be up to 4 MiB (text bodies stay at 1 MiB).

javascript
function handler(request) {
  const csv = new TextEncoder().encode('id,total\n1,42\n');
  return {
    headers: {
      'content-type': 'text/csv',
      'content-disposition': 'attachment; filename="report.csv"',
    },
    body: csv,
  };
}

JavaScript has no Buffer, btoa, or atob in the sandbox. Use env.base64.encode(bytes) and env.base64.decode(text) (which returns a Uint8Array). Python has base64 in its standard library.

Returning bytes is cheap at any size: a JavaScript or Python handler hands them to the platform as raw memory, and the platform encodes them, so a 4 MiB body costs about as much fuel as a 4-byte one. Building the bytes is the handler's own work and does cost fuel: a byte-by-byte loop in JavaScript or Python is expensive, while new Uint8Array(n), TextEncoder, bytes(n) and bytearray(n) are cheap. Check large outputs with edge_function_invoke before mapping a route.

Files from a function ​

env.file reads and writes files — CSV, PDF, images, archives — in the distribution's file store. Access is granted per key prefix with edge_file_prefix_set, outside the source, so a function cannot widen its own access. A key with no grant is refused with not_granted.

JavaScriptPythonReturns
put(key, bytes | string, {contentType, ifMatch})put(key, data, content_type=..., if_match=None){etag, size}
get(key)get(key){bytes, contentType, etag, size}, or null / None
head(key)head(key){contentType, etag, size}, or null / None
read(key, {offset, length})read(key, offset=0, length=...)a range, as get
list(prefix, {cursor})list(prefix, cursor=None){items, cursor}
delete(key)delete(key){deleted: true}
create(key, {contentType})create(key, content_type=...)a writer: append, commit, abort
link(key, {ttlSeconds, disposition})link(key, ttl_seconds=900, disposition=...){url, expiresIn}
  • put creates a key; replacing one needs ifMatch with its current etag, otherwise precondition_failed.
  • One call moves at most 4 MiB. get refuses a larger file; page through it with read, or write one up to 5 GiB with create, append and commit.
  • put, get, head, list, delete, create, commit and link share the eight host calls per invocation with env.document. append and read are limited by bytes instead: 512 MiB per invocation, 5 GiB on a background route.
  • A writer still open when the handler ends is discarded. The platform replays a handler after every fetch, so do fetches before you start writing.
  • link returns a download URL valid for 60 to 3,600 seconds (default 900). Only images, PDF, text, CSV, JSON, audio and video open inline; everything else downloads.
  • Errors are thrown as Error with .code (JavaScript) or raised as FileError with .code (Python): not_granted, not_found, precondition_failed, too_large, quota_exceeded, budget_exhausted, invalid_key, writer_closed.

Bytes cross between your handler and the platform without re-encoding, so moving a file costs about the same fuel whatever its size. See Store and serve files from a function.

Visitor uploads from a function ​

env.upload — on the env argument of handler(request, env) (Python def handler(request, env)) — lets a function hand one visitor a ticket to upload a file straight to storage. The file is scanned for malware and its first bytes are checked against the declared type; the function can read it or keep it in the file store only once it is clean. Check the visitor before signing: a function does not see cookies or identity, so put the distribution behind visitor sign-in when only signed-in visitors may upload.

A maintainer turns uploads on per script with edge_function_upload_grant_set (distribution_id, script_id, enabled). The grant is stored outside the source and is MCP-only; there is no HTTP route or CLI command. edge_file_prefix_get lists the granted scripts as upload_scripts. Without the grant, every call fails with not_granted.

JavaScriptPythonReturns
sign({contentType, size})sign(content_type, size)a ticket (below)
parts(uploadId, from)parts(upload_id, start){upload_id, parts}: up to 100 more part URLs, from part from
complete(uploadId, [{n, etag}])complete(upload_id, parts){upload_id, status: "uploaded"}
status(uploadId)status(upload_id){status, reason, contentType, size} (Python: content_type)
read(uploadId, {offset, length})read(upload_id, offset=0, length=None){bytes, contentType, size} (Python: content_type)
keep(uploadId, key)keep(upload_id, key){key, size, etag, contentType} (Python: content_type)

A ticket has the same shape as the /_upload lane, with snake_case field names, because the visitor's page reads it:

modeTicketThe page then
single (up to 100 MiB){upload_id, mode, url, fields, expires_in}Posts multipart/form-data to url with every entry of fields, then the file last. Valid 10 minutes.
multipart (larger){upload_id, mode, part_size, part_count, parts: [{n, length, url}], expires_in}PUTs exactly length bytes to each part URL, then sends every part's ETag back to the function, which calls complete. Parts are 16 MiB; the first 100 URLs are in the ticket, and each is valid one hour.

status is one of:

statusMeaning
pendingSigned, but the file has not arrived
scanningArrived; the scan has not settled
cleanNo malware, and the first bytes match the declared type
rejectedreason is malware or type_mismatch
scan_failedNo verdict. The file can never be read or kept.
  • contentType must be on the same allowed list as form uploads: PDF, Word, Excel and PowerPoint (.docx, .xlsx, .pptx), ZIP, plain text, CSV, JSON, PNG, JPEG, GIF, WebP, HEIC, AVIF, MP4, QuickTime, WebM, MP3, M4A, WAV and Ogg. HTML, SVG, scripts and executables fail with type_not_allowed.
  • size is 1 byte to 5 GiB (too_large above). Storage accepts only exactly that many bytes, so the browser must send the size it declared.
  • Only the script that signed an upload can see it. Any other script gets not_found.
  • read and keep work only on a clean upload. Before that they fail with not_clean; a file whose contents are not the declared type fails with type_mismatch.
  • read returns at most 4 MiB per call.
  • keep copies the upload into the file store under an env.file prefix grant. It creates a key and never replaces one (precondition_failed), and the copy counts against the file store's quota. On a public prefix a file route can serve it; images, PDF, text, CSV, JSON, audio and video open in the browser, and other types download.
  • An upload that is never kept is deleted after a day.
  • sign, parts, complete, status and keep share the eight host calls per invocation with env.document and env.file. read counts bytes against the file read budget instead.
  • Uploads count against your organization's monthly upload quota, shared with form uploads: 100 GiB and 50,000 files a month. Usage is measured as uploads arrive, so a few may get through after the line is crossed; after that sign fails with quota_exceeded.
  • Errors are thrown as Error with .code (JavaScript) or raised as UploadError with .code (Python): not_granted, type_not_allowed, too_large, quota_exceeded, not_found, not_clean, type_mismatch, invalid_parts, precondition_failed, budget_exhausted, invalid_request, unavailable. invalid_parts means the part list passed to complete is incomplete, out of order, or does not match what storage received.

Agents read the same rules in the uploads section of edge://runtime/functions and the function_uploads entry of edge://limits. See Let signed-in visitors upload images.

Outbound HTTPS ​

The sandbox has no sockets. HTTPS is host-mediated: port 443, a DNS name (not an IP literal), no redirects, no private / link-local / metadata addresses, no visitor or platform credentials. At most four calls per invocation, 2 seconds each, 64 KiB request and 256 KiB response. Call with the same arguments in the same order every run — the platform replays the handler.

LanguageHow
JavaScriptInside handler only: fetch(url, {method, headers, body}) → {ok, status, contentType, body, error}
PythonInside handler: fetch(url, method="GET", headers=None, body=None) — same return object. urllib / http stay refused
Rust, TinyGo, C, AssemblyScriptWrite one stdout object {"fetch":{"method","url","headers","body"}} and exit 0. Replay stdin includes fetchResults. Methods: GET, HEAD, POST

ok is false when the platform refuses the URL or the call fails. error is a short public message, not the upstream body. For an origin you configure yourself, use a proxy endpoint instead.

Background jobs ​

A function can also run without a visitor request, as a background job. It is the same artifact and the same handler. It receives a POST to /_jobs/{kind}/{name} — kind is cron, queue or workflow — with a JSON string body:

json
{"type":"cron","job_id":"job_01M4X7T2K9Q0V3B8N6C5D1E2F3","attempt":1,"distribution_id":"d3f7a1c4-90b2-4e6a-8f15-6c2b7e0a9d38"}

Answer with the usual envelope. A 2xx succeeds; a 5xx is retried; a 4xx fails without a retry. A job can run more than once, so key any side effect on job_id.

Jobs run on a separate background runner with a longer budget: 300 seconds by default and up to 840 with background_timeout_seconds, 256 MiB, and 100 outbound calls. A visitor request never reaches it. See Limits and Test a function as a background job.

Data objects from a function ​

Handler code can read and write data objects on the same distribution through env.document. Grants are configured outside the source with edge_document_grant_set and edge_document_prefix_set (function.write). A function cannot edit its own grants; document.write cannot set them.

MethodReturns
get(key){body, etag}
put(key, body, ifMatch?){etag}
list(prefix, cursor?){keys, cursor} — 50 keys per page
delete(key){deleted: true}

JavaScript throws Error with .code. Python raises DocumentError with .code. Without a grant, get fails with denied even when the key does not exist. Public objects are the same keys you write with edge_document_write. Private objects are never served on GET /_api; use edge_private_document_* to manage them and a private grant so the function can call env.document.

At most eight document calls per invocation. Each body is capped at 1 MiB. Public keys with read-write grants are served to visitors with cache-control: no-store.

Rust, TinyGo, C, and AssemblyScript may import deca:document call with the same JSON operations; JavaScript and Python use env.document as shown above.

See Read and write data objects from a function.

Queues from a function ​

env.queue sends messages to a queue on the same distribution. A function may send only to a queue whose senders list its script id, or "*"; set them with edge_queue_create or edge_queue_update (queue.write). Function code cannot change them.

MethodReturns
send(queue, body, {delaySeconds?, idempotencyKey?}){id}
sendBatch(queue, [{body, delaySeconds?, idempotencyKey?}, …]){ids}

Python names them send(queue, body, delay_seconds=None, idempotency_key=None) and send_batch(queue, [{"body": …, "delay_seconds": …, "idempotency_key": …}]), and raises QueueError with .code. JavaScript throws Error with .code: denied (not a sender), not_found (no queue by that name), queue_full, rate_limited, too_large, invalid_request or unavailable.

A send returns once the message is stored; the queue's consumer handles it later on the background runner. A function on the request runner may send 10 messages per invocation; a background job may send 100. Queue sends do not count against the eight store calls. A send without an idempotencyKey gets one from the invocation, so when a function that fetches runs again from the start, its sends are not duplicated.

Rust, TinyGo, C, and AssemblyScript import edge:queue call with {"op": "send", "queue", "body", "delay_seconds"?, "idempotency_key"?} or {"op": "send_batch", "queue", "messages": [...]}, and read back {"ok": true, "id"}, {"ok": true, "ids"} or {"ok": false, "error"}.

Workflows from a function ​

env.workflow starts, signals and reads workflow runs on the same distribution.

MethodReturns
start(name, input, {scriptId?, idempotencyKey?}){runId, created}
signal(runId, name, payload, {idempotencyKey?}){delivered}
get(runId){run_id, name, status, step, waiting_for, output?, error?}

start runs the calling function's own script unless scriptId names another function. A function may start another function only when that script is in its workflow_starts grant. Set the grant with edge_function_update(distribution_id, script_id, workflow_starts=[…]) (function.write); ["*"] allows every function on the distribution and [] clears the grant. Function code cannot change it.

signal and get reach two kinds of run: runs this function started, and runs of a script it may start. A workflow step may start a child run but cannot signal its own run; its step answer (next, sleep, wait) is how a run moves itself forward. delivered is false when the run is not waiting for that signal yet. Edge then keeps the signal until the run waits for it.

Python names them start(name, input=None, script_id=None, idempotency_key=None) (returns {"run_id", "created"}), signal(run_id, name, payload=None, idempotency_key=None) and get(run_id). It raises WorkflowError with .code. JavaScript throws Error with .code:

CodeMeaning
deniedThe grant does not cover that script or run, or a step signalled its own run
not_foundNo such function or run on this distribution
run_finishedThe run has already completed, failed or been cancelled
limit_reachedThe distribution already has 1000 active runs
rate_limitedThe invocation's call cap is used up
too_largeThe input or payload is over 256 KiB
invalid_requestA malformed name, id or key
unavailableEdge could not take the call; retry later

A function on the request runner may make 10 env.workflow calls per invocation; a background job may make 50. They do not count against the eight store calls. A start or signal without an idempotencyKey gets one from the invocation, so when a function that fetches runs again from the start, it does not start or signal twice. A retried job is a new invocation and derives new keys: pass your own idempotencyKey to start a run exactly once across retries.

Rust, TinyGo, C, and AssemblyScript import edge:workflow call with {"op": "start", "name"?, "input"?, "script_id"?, "idempotency_key"?}, {"op": "signal", "run_id", "name", "payload"?, "idempotency_key"?} or {"op": "get", "run_id"}, and read back {"ok": true, "run_id", "created"}, {"ok": true, "delivered"}, {"ok": true, "run"} or {"ok": false, "error"}.

Inspect runtime logs ​

edge_function_logs returns recent invocations newest first. It covers visitor requests, direct edge_function_invoke tests, hook actions that run the function, and background jobs, and includes:

  • captured stdout and stderr
  • fuel, memory, and duration
  • the runtime error, when one occurred

Filter with an ISO 8601 since timestamp, a source (visitor, invoke, hook, cron, queue, workflow) or a job_id. A page contains at most 50 rows and captures are retained for seven days.

The response envelope written to stdout is not stored as a log line. Edge also never records the request body, query string, headers, or cookies in function logs. Your own console.*, print(), or stderr output can still contain visitor data, so do not log personal data or secrets.

Build failures are separate: edge_function_get returns build_log, capped at 32 KiB. Use edge_function_invoke before mapping a public path; it returns stdout, stderr, fuel, memory, and errors immediately.

See also ​