Functions
Ship a worker with your Space. A single handler, a functions/ file router, or an OpenNext build, detected at publish and dispatched only for the paths it claims.
Functions can detect a supported worker layout when you publish, without an explicit runtime block. Custom layouts need a declaration, and Zero is always declared explicitly.
Functions runs your code as a worker. Use it when you need npm packages or framework output like OpenNext Next.js. If you want live queries in the browser and a schema the platform migrates for you, use Zero instead. Both can call fetch(). One version declares one runtime.
Functions is on for every account.
Where the code lives
Detection is the normal case. sf publish looks at the tree and picks the first match, in this order.
| Layout | What it is | Route table |
|---|---|---|
.open-next/worker.js |
An OpenNext build of a Next.js app | The build’s own classified routes, or the whole Space when the publish did not run the build |
handler.ts, handler.js, handler.mjs |
One hand-written worker at the root | The whole Space |
functions/ with at least one route module |
A file router | Exactly the routes its files declare |
A directory matching none of these is a static site, which is the safe default.
The OpenNext build wins over a stray handler.ts, because a framework build takes precedence over a leftover handler file.
The functions/ file router
A module’s filename is its route and the HTTP methods it exports are the methods it answers. Nothing is inferred from a module graph, so the table is exact.
- functions/
- index.ts
- hello.ts
- blog/
- index.ts
- haiku/
- “[topic].ts”
- posts/
- “[…rest].ts”
| File | Route |
|---|---|
functions/index.ts |
/ |
functions/hello.ts |
/hello |
functions/blog/index.ts |
/blog |
functions/haiku/[topic].ts |
/haiku/:topic |
functions/posts/[...rest].ts |
/posts and everything under it |
Route modules can be .ts, .tsx, .js, .jsx, .mjs, or .cjs. A name starting with _ or . is a colocated helper and is never routed. Neither are .d.ts files or anything matching *.test.* / *.spec.*. A catch-all is terminal or nothing: [...rest] in the middle of a path is skipped.
A path that exists at other methods answers 405 with an Allow header. A path in no file’s table is a plain 404 and the worker never wakes.
The handler
A file-router module exports one function per method it answers, or a default export that answers every method.
export async function GET(request: Request, context: { params: Record<string, string> }) {
return Response.json({ topic: context.params.topic });
}
export async function POST(request: Request) {
const body = await request.json();
return Response.json({ received: body }, { status: 201 });
}
context carries params, env, and ctx. A catch-all binds the remainder of the path as params.splat.
A root worker default-exports a plain handler object instead, the shape Workers already expects.
export default {
async fetch(request: Request, env: Record<string, string>): Promise<Response> {
const url = new URL(request.url);
if (url.pathname === "/api/hello") return Response.json({ hello: "world" });
return new Response("Not found", { status: 404 });
},
};
sf init my-app --runtime functions writes exactly that file plus the matching spacefast.config.ts.
Requests and responses are the standard Request and Response. There is no Spacefast wrapper around either.
Declare it
Declare a runtime block when detection cannot identify your layout or you need to specify entry or compatibilityDate.
{
"$schema": "https://spacefast.com/schemas/sf.json",
"runtime": {
"kind": "functions",
"entry": "handler.ts",
"compatibilityDate": "2026-07-01"
}
}
| Key | Type | Default | What it does |
|---|---|---|---|
entry |
string | detected | Path to the worker entry. Naming a file that does not exist fails the publish rather than falling back to a static publish |
compatibilityDate |
YYYY-MM-DD |
2026-07-01 |
The runtime semantics this worker was written against |
There is nothing to switch on. Every worker gets its database and outbound fetch(). A leftover database or fetch key is ignored with a warning.
Outbound HTTP
fetch() works in every worker. How far it reaches depends on who owns the space:
| Space | Reaches |
|---|---|
| Claimed | Any public HTTP or HTTPS host |
| Unclaimed | Only the trusted list: api.anthropic.com, api.openai.com, api.github.com, api.stripe.com, api.groq.com, api.mistral.ai, api.together.xyz, generativelanguage.googleapis.com, openrouter.ai |
Anything else from an unclaimed space answers 403 with “This host isn’t reachable from an unclaimed space. Claim the space to reach any public host.” Claiming opens it up without a republish.
Outbound requests from a worker leave from Cloudflare’s shared network addresses, not from a dedicated or fixed IP for your space. Other spaces can send from the same addresses, so an API that rate-limits or blocks by IP can count their traffic against yours and answer 429 on your first request. There is also no fixed address to put on an API allowlist. Plan for it:
- Send the key the API issues you. An API that limits per key then counts only your requests.
- Retry a
429with backoff. WhenRetry-Afteris longer than the request can wait, return an error and try again on a later request or cron run. - Cache responses in
env.DBso repeat requests are answered from the cache. - Call the API from the browser instead when it accepts cross-origin requests and the call needs no secret.
What is on env
env carries the space’s environment variables. See Environment variables for how to set them.
env.CONNECTORS calls your Space’s connector roles when the version declares any.
env.DB is always there. It uses the D1 API (env.DB.prepare(sql).bind(...).all()) and reaches the space’s own database through a broker, so no connection string ever lands in the bundle.
Two groups of variable names never reach a worker, dropped rather than blanked so your code reads them as absent instead of as “configured, but empty”.
| Withheld | Why |
|---|---|
DATABASE_URL, DATABASE_URI, MYSQL_URL, MYSQL_URI, MYSQL_DSN, POSTGRES_URL, POSTGRES_URI, POSTGRESQL_URL, POSTGRESQL_URI |
A worker reaches the database through the broker or not at all |
Anything starting with SPACEFAST_ or ZERO_ |
The platform’s own namespace |
Limits
| Limit | Value |
|---|---|
| Compiled bundle | 24 MiB |
| Routes per version | 256 |
| Next cache seed, one entry | 2 MiB minus 8192 bytes |
| Next cache seed, total | 8 MiB |
Per-request CPU and memory are the isolate’s own and are not restated here.
Local development
sf dev does not run a worker. It refuses runtime.kind: "functions" with runtime_dev_unsupported and exit code 2, rather than serving a static shell and none of your routes. Run your framework’s own dev server (next dev, vite), then sf publish.
Logs
Everything your handler writes lands in the runtime log stream, with the handler name and request id on each line.
sf logs runtime --follow
sf logs runtime --handler checkout
See Logs for filters, retention, and the paging rule.