Deploy functions #

View this page as Markdown

On this page

Prompt:

Add a small API to this site without keeping a server running.

Deploy a JavaScript function to handle a request and return a response. A serverless application can hold functions, static files, or both; nothing runs while it is idle. Turn Zero runs functions on Supabase Edge Runtime, the open-source server built on Deno.

Functions provide standard web APIs such as Request, Response, URL, global fetch, and Web Crypto (crypto.subtle). The function worker provides Buffer, process, and the immediate timers from node:buffer, node:process, and node:timers. For other built-ins, see Deno's Node.js compatibility guide and its node:crypto reference. Those pages describe current Deno. Test the specific APIs your code or dependencies use in a deployed Turn Zero function. For outbound HTTP, use global fetch and follow Call another service.

For a function that reads and writes files, start with Use Storage with fetch. For a complete Node.js server example, see Build a public upload gallery.

To test your handler before signing in, replace fetch with a test function. If you already have the Storage package, use its in-memory test double.

Before your AI starts #

For the AI assistant:

  • Read the deploy skill with read_context, id skill:deploy, through the person's connected, signed-in tool (Connect your AI assistant).
  • Check the choice of kind and isolation against the application's needs. Functions of different customers share a process; a server has its own container. Tell the person this when explaining the choice.
  • Read the function limits in Keep work within a call before choosing serverless for code.
  • For an existing application, read its kind with read_status and recover its complete manifest from the project or export_account. Kind is fixed at creation.
  • For a new serverless application, call create_application with its name and kind: "serverless", without a size. Keep the returned application identifier.
  • Add development only if the owner asks (Test in development, then promote).

Deploy functions with a database #

Use the serverless application and its ID from the setup above. The functions-database example has a complete notes app with a function, a web page, and a PostgreSQL database.

  1. Prepare the files. With a shell, run turnzero scaffold --origin https://dev.turnzero.ai --template functions-database --application <application id> and work in app/. Without a shell, use the example's From a chat instructions and copy its files with their listed paths.
  2. Submit the complete manifest. Call submit_manifest with the application ID. Keep { "kind": "database" } in the manifest's services list.
  3. Connect and migrate. Put handlers in functions/ and .sql migration files directly under migrations/. Connect from the function through APP_DATABASE_URL. Keep it out of browser code and logs. The platform runs the migrations before the deployed version serves.
  4. Deploy and check the result. Use Ways to deploy to choose how to send the folder. Read read_status with wait_seconds until the deploy ends. After it succeeds, check the deployed route that reads the database. The example's checks show what to expect.

Steps #

1. Put the handler under functions #

A function is a JavaScript module under functions/. Its default export has a fetch(request) method that returns a web-standard Response, or a promise of one. It receives a web-standard Request.

For a public notes page, turnzero scaffold --origin https://dev.turnzero.ai --template functions-database --application <application id> writes a notes app under app/. Use the identifier from create_application. The manifest declares a database, and the folder includes a web page, the /api/notes function, shared modules, migrations and tests.

For sign-in and private notes, use the functions-sign-in template. Its manifest declares the database and accounts services. Follow the functions-sign-in example to deploy the app and check sign-in at its deployed address.

Work from app/ with either template. Keep its generated manifest and submit it in step 2. Its function reads APP_DATABASE_URL; the platform applies its migrations before the deployed version serves.

For a minimal handler, save this as functions/hello.js:

export default { fetch: () => new Response("hello") };

The function's file path, without its extension, is its request path. This file handles /hello and paths beneath /hello/, for any method. Where several functions match, the longest matching path wins.

Keep shared modules under lib/ and import them from the functions. A file under lib/ creates no route. Every file under functions/ counts as a function, so keep helpers elsewhere.

Put optional pages, styles and images under client/. Keep the deploy folder's root as follows:

manifest.json
functions/hello.js
client/index.html

Only manifest.json and at least one of functions/ or client/ are needed. Optional runtime dependencies go in a root package.json; the platform installs them when building the function files. Carry local library packages as folders under lib/.

Use ordinary JavaScript imports. Supply JavaScript that can run as written: the platform installs dependencies but does not compile your application. Functions need no start script, root server.js or health path.

Use library packages #

The library packages proved in a function are account, ai_generation, database, egress, email, schedule, secrets and storage.

Follow Use the feature package library to take a package and its dependencies. Choose a server when the application needs a package outside this list. The deploy checks do not refuse a package merely because it is absent from the list.

How a request reaches a function #

The router checks manifest redirect rules first. A matching rule answers a GET or HEAD before any client file, folder page or function. For GET and HEAD, a matching client file or folder page takes precedence over a function. A folder with an index.html redirects a request without its closing slash to the path with it.

Next, the longest matching function path wins for any method. A file in functions/ answers its path without the file extension and paths beneath it. Function paths start below /. Use client/index.html for GET and HEAD at /. For an unmatched GET or HEAD, the router serves client/404.html with status 404 if that file exists. Otherwise it serves client/index.html only for page paths, where the last part of the path has no dot. Other unmatched requests return 404 not_found.

Publish a static site gives the client files' complete path rules and bounds. Keep a client file off a path that must reach your function.

2. Submit the manifest and declare services #

Submit the complete manifest.json with submit_manifest. For a public function with no other services, start with:

{
  "manifest_version": 1,
  "services": [],
  "region": "usa",
  "egress": [],
  "audience": { "kind": "public" },
  "packages": []
}

These are the six required members. Add any services and outgoing hosts before submitting; a submission replaces the whole manifest. Author the manifest explains each member.

Functions are not declared in the manifest, so adding one to an application with a recorded manifest needs no new submission by itself. Submit the complete manifest again if the function needs a new or changed declaration, such as a service, outgoing host, schedule or setting.

Read a function's settings #

Read a deployed function's settings from process.env.

  • Use APP_PUBLIC_HOST for the public hostname, APP_ENVIRONMENT for development or production, and APP_VERSION for the version serving. The hostname in request.url can be internal to Turn Zero. Build absolute addresses from https:// followed by APP_PUBLIC_HOST, never from the request's Host.
  • Read TURNZERO_CLOUD_APPLICATION for the application ID and TURNZERO_CLOUD_APP_TOKEN for the environment's platform credential.
  • Use TURNZERO_CLOUD_API for sign-in and account calls. Send storage, egress and logging calls to TURNZERO_CLOUD_GATEWAY_URL where the platform configures a separate gateway origin. Use TURNZERO_CLOUD_API when that setting is absent.
  • When the environment has a database, connect through APP_DATABASE_URL.
  • When the environment has a sign-in realm, TURNZERO_CLOUD_REALM_KEYS holds that realm's public keys. Give them to the Account package to verify sessions inside the deployed function.

Keep APP_DATABASE_URL and TURNZERO_CLOUD_APP_TOKEN secret. Keep both out of browser code, responses and logs. The runtime settings table describes the values and when they are present.

Anyone can reach a public application. For a browser route only the owner can use, check that the signed-in user's verified email matches the owner's before the function reads private data or makes changes. Follow Let only you reach an admin route.

Use a database #

Declare the database and keep schema changes as .sql files directly under the root migrations/ folder. Follow Add a database, including its function connection setting and migration refusals.

A function connects through APP_DATABASE_URL, with the server's certificate checked. It uses pooler port 6432 on shared and direct port 5432 on dedicated. A worker should hold at most one database connection.

Write function code to work with a pooler in transaction mode. The next transaction can use a different database connection, so avoid relying on session state between transactions. For a setting that should last only for the current transaction, use SET LOCAL inside it.

The platform applies migrations before a deploy, promote or rollback makes that version serve. The function receives no APP_DATABASE_DIRECT_URL and runs no startup migrations.

Files committed before a migration failure stay applied. A rollback undoes no migration. Keep every change compatible with the version still serving, and inspect a failed outcome before repeating the act.

Use Storage with fetch #

This example writes and reads one fixed file from a serverless function, without installing a package. Use a disposable app. Anyone with its address can read or update this demonstration file. Before adapting the example to user files, check the caller and which file they may access.

Create an app with kind: "serverless" and no size. Save this complete manifest.json, then submit it with submit_manifest:

{
  "manifest_version": 1,
  "services": [
    {
      "kind": "object_storage"
    }
  ],
  "region": "usa",
  "egress": [],
  "audience": {
    "kind": "public"
  },
  "packages": []
}

Save functions/storage-demo.js beside the manifest as shown below. The function sends the platform credential from its environment. It does not send a visitor's credential to Storage or return the platform credential to the visitor.

const area = 'functions-demo';
const file = `areas/${area}/files/hello.txt`;

async function storage(path, init = {}) {
  const origin = process.env.TURNZERO_CLOUD_GATEWAY_URL || process.env.TURNZERO_CLOUD_API;
  const token = process.env.TURNZERO_CLOUD_APP_TOKEN;
  const headers = new Headers(init.headers);
  headers.set('authorization', `Bearer ${token}`);
  return fetch(new URL(`/storage/v0/${path}`, origin), { ...init, headers });
}

function reply(upstream) {
  const headers = new Headers({ 'cache-control': 'no-store' });
  for (const name of upstream.ok ? ['content-type', 'etag'] : ['content-type']) {
    const value = upstream.headers.get(name);
    if (value !== null) headers.set(name, value);
  }
  return new Response(upstream.body, { status: upstream.status, headers });
}

async function write(condition, text) {
  return reply(await storage(file, {
    method: 'PUT',
    headers: {
      ...condition,
      'content-type': 'text/plain; charset=utf-8',
      'x-acting-identity': 'storage-demo',
    },
    body: text,
  }));
}

export default {
  async fetch(request) {
    if (new URL(request.url).pathname !== '/storage-demo') {
      return new Response('Not found', { status: 404 });
    }
    if (request.method === 'GET') return reply(await storage(file));

    if (request.method === 'POST') {
      const ready = await storage(`areas/${area}`, {
        method: 'PUT',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ account_keyed: false, version_keeping: false }),
      });
      if (!ready.ok) return reply(ready);
      await ready.body?.cancel();
      return write({ 'if-none-match': '*' }, 'Hello from a function.\n');
    }

    if (request.method === 'PUT') {
      const etag = request.headers.get('if-match');
      if (!etag || etag === '*') {
        return new Response('Send the ETag from GET in If-Match', { status: 428 });
      }
      return write({ 'if-match': etag }, 'Updated by a function.\n');
    }

    return new Response('Method not allowed', {
      status: 405,
      headers: { allow: 'GET, POST, PUT' },
    });
  },
};

Follow Deploy and check the handler with these two files. Replace https://<app-host> below with the serving address from the deployment. Run the commands against that app:

curl -i -X POST 'https://<app-host>/storage-demo'
curl -i 'https://<app-host>/storage-demo'

The first command creates hello.txt and returns 200. A repeated POST returns 412 version_mismatch. The GET returns Hello from a function. and an ETag header. Copy that header's value, including quotes, into the next command:

curl -i -X PUT -H 'If-Match: <etag-value>' 'https://<app-host>/storage-demo'
curl -i 'https://<app-host>/storage-demo'

The PUT replaces the file only if the stored version still matches the ETag. On success the second GET returns Updated by a function. Repeating the PUT with the old ETag returns 412. Read the current ETag before deciding whether to retry.

Storage uses the environment fixed by the platform credential, so the function sends no environment header. X-Acting-Identity labels the write. It provides no access control. To list files or handle missing files, see Call storage without end-user sign-in.

Call another service #

Use global fetch for outgoing HTTP requests. Calls to the platform API and gateway origins, including Storage, need no egress entry. For other destinations, declare each exact hostname in the manifest's egress list. A wildcard declaration does not admit that host for a function.

An undeclared host is refused egress_undeclared before any connection, in both observe and enforce modes. That refusal creates no outgoing-request record for the host. Correct the declaration and submit the whole manifest.

Functions cannot call localhost or a name ending .localhost; adding such a name to egress does not allow the call. Use the service's public hostname. A request hostname may have one final dot, but two are refused egress_undeclared. Remove the extra dot from the request URL; manifest entries have no final dot.

Outgoing HTTP calls follow at most twenty redirects. Each redirected external hostname must also be declared. A 303 changes any method except GET or HEAD to GET. A 301 or 302 changes POST to GET. These changes drop the body; other redirects keep the method and body.

A redirect to another origin removes authorization and cookie. A credential in another application header can still reach the new address. Use redirect: "manual" to read a redirect response without following it, or redirect: "error" to fail on a redirect.

A function cannot use Node's http or https modules, or a library with its own HTTP client. Use a library that calls global fetch, or ask the owner before choosing a separate server application. The egress firewall explains declarations and keyed upstreams.

Run a scheduled job #

Declare its schedule and handler path as Add a scheduled job describes. The platform invokes the function with POST. A normal request to that schedule path, or beneath it, returns 404 scheduled_handler_only; other paths handled by the same function remain available.

Finish the job before returning its response. Each scheduled invocation that runs a function counts as a function call.

3. Deploy and check the handler #

Check the handler locally #

With a shell, run turnzero run --origin https://dev.turnzero.ai from the deploy folder, then open the handler's path on the printed address. A module loads on its first request and stays loaded. Restart the command after editing a function; Ctrl-C stops the run.

For a database-backed local check, submit the manifest, then provision its local settings. This uses the development database, even when the application has production alone. Install the application's dependencies, including pg. Before serving functions, turnzero run --origin https://dev.turnzero.ai applies the .sql files directly under migrations/ to the database named by APP_DATABASE_URL. When migration files are present, a missing address, unavailable pg or failed migration stops the command before it serves. Check other platform services in the deployed environment.

The local run uses Node.js on your computer. It applies no pool limits or outgoing-host checks, and runs no scheduled jobs. A successful local request does not prove that the deployed function meets its runtime limits or permissions. Check the deployed version too.

Deploy the handler #

With production alone, the first deploy serves production and applies any migrations there before that version serves. With development enabled at the owner's request, deploy to development.

Choose a route from Ways to deploy and follow its signed-in checks. With the command, deploy the folder's contents so functions/ sits at the zip's root. For deploy_files, name each file with that same relative path, such as functions/hello.js.

Read read_status with wait_seconds until the act ends. If the initiating response is lost, read status before repeating the deploy. Read any failed outcome and its detail first.

Leave brief out or pass brief: false for the whole answer. The live deploy.step and deploy.step_started_at show where the run is and when that step began. deploy.timings lists entered steps and their times. During a functions deploy:

  • image_build builds the function files and installs dependencies where needed. While that step runs and its build run is recorded, build_progress beside the deploy member holds up to five newest scrubbed build lines, or unread if they could not be read. Lines can repeat between reads and do not mark a separate install phase.

  • migrations applies migration files where present.

  • function_settings writes settings to the function pool and waits for the function files to load. There is no separate function-registration step.

With brief: true, the live step and its start remain, but build lines, timings and the functions list are omitted.

A completed deploy reports the serving version's function paths in that environment's functions member. Call /hello on the returned hostname with your browser or request_route; this example returns hello.

On two environments, test development first and promote the tested version. A successful development deploy does not make production serve it.

Read logs and failures #

Call read_logs for the same application and environment with source: "pool". Function console lines and failures appear there, with the function path in fields.function where known. A warning named function log records dropped means some records were lost.

A function can run again in a reused worker, but another call can reach a new worker. Store durable data in the database or Storage, not in memory or a temporary file.

4. Keep work within a call #

A function returns one response. Finish required work before returning it: work after the response is unsupported. Functions cannot accept WebSocket connections, start child processes or threads, expose a listening port, load native modules, or load modules from the network.

Call read_plan_quotas with plan: "shared-0.5gb" for the function limits that serverless applications use. The figures can change; use the returned values when deciding whether a request fits a function.

Limit key What it bounds
function-memory-capacity Memory held by one worker.
function-cpu-time CPU time one call has at least. This is a minimum allowance, not an exact instant at which the call ends.
function-answer-time The runtime's time to return a response. The routing request window can end a request earlier.
function-calls-at-once Concurrent calls for one application environment on each pool replica.
function-temporary-capacity Temporary storage held by one worker.
function-tree-capacity Bytes of installed function files and dependencies before compression.
function-count-limit Files under functions/, each counted as a function.

A daily CPU limit applies to each account's function applications and environments, with a separate count on each pool replica for the UTC day. CPU is counted when each worker ends, so the count can trail the work already done. A replica's count is not kept across its restart.

At the limit, requests and scheduled invocations reaching that replica return 429 function_busy before the function runs. Another replica may still serve a request before 00:00 UTC. This limit is separate from the values returned by read_plan_quotas. Read detail to identify the daily limit, and retry after 00:00 UTC.

The installed tree also has an entry limit that counts files and folders, dependencies included. A failed build names the relevant limit. Worker limits also apply while earlier versions' workers are still present.

Use asynchronous file reads for files beside your code. Synchronous file reads during a call are refused. Temporary files can survive another call on the same worker, but are not durable; Node's appendFile is refused there.

Choose a server for longer work, larger per-request resources, any existing server, or a package that has not been proved in functions. Ask the owner before choosing one. A server is charged for the time it is awake. Kind cannot change later. Creating a server creates a separate application; it carries over no hostname, database, files or secrets.

From a server route to a function #

When adapting a server guide's sample, keep its request checks and response, then change the application and handler as follows.

Create a separate application #

An existing server stays a server: kind is fixed at creation in both directions. Create a new application with kind: "serverless" and no size. No platform act carries over the old application's hostname, database, files or secrets. Read Choose the kind before choosing the new application's kind.

Change the handler's shape #

Put each route in a JavaScript module under functions/. Its path without the extension is its request path, including paths beneath it, for any method. Export an object with fetch(request), which takes a web-standard Request and returns a web-standard Response. Check the method in the handler where the route accepts only one. Keep shared code under lib/, which creates no route. Do not copy the listening server, start script, root server.js or health path.

Calls can reach different workers, so a count, cache or limit in memory applies per worker, and durable state belongs in the database or Storage.

Read settings and use services #

Read APP_PUBLIC_HOST, TURNZERO_CLOUD_API and TURNZERO_CLOUD_APP_TOKEN from process.env, and TURNZERO_CLOUD_GATEWAY_URL where supplied. Keep the credential out of responses and browser code. Follow Read a function's settings for their uses and the gateway fallback.

For a database, use APP_DATABASE_URL; a function receives no APP_DATABASE_DIRECT_URL. The platform applies migrations before the deployed version serves, so the function runs none at start. Follow Use a database for the declaration and migration rules.

Check packages and outgoing calls #

The packages proved in a function are account, ai_generation, database, egress, email, schedule, secrets and storage. If the route needs another package, such as push, ask the owner before choosing a server. For outgoing HTTP calls, use global fetch. Declare each exact hostname in egress except the platform API and gateway origins. Node's http and https modules are unavailable. Call another service gives the restrictions.

Finish work before responding #

Work after the response is unsupported. A route that keeps working after it answers, holds a WebSocket or starts a process needs a server. Ask the owner before choosing one, and read Keep work within a call for the function limits.

Check locally and read function logs #

Run turnzero run --origin https://dev.turnzero.ai from the deploy folder and restart it after editing a function. Follow Check the handler locally, then check the deployed version too. Read function logs with read_logs and source: "pool", rather than "container".

A JSON route before and after #

For example, a Node server's /api/hello route can answer GET with {"message":"hello"} as JSON, and another method with 405. For a function with the same replies, save this as functions/api/hello.js:

// functions/api/hello.js
export default {
  fetch(request) {
    if (request.method !== "GET") {
      return new Response("Method not allowed", {
        status: 405,
        headers: { allow: "GET" },
      });
    }
    return new Response(JSON.stringify({ message: "hello" }), {
      headers: { "content-type": "application/json" },
    });
  },
};

The file handles /api/hello and paths beneath it. It needs no call to listen and no health route.

Expected result #

The deploy ends deployed, read_status lists the serving version's function paths, and /hello returns hello. Optional client files use the same hostname.

A function runs only for an admitted request. A function call that runs counts toward usage, including one ended at a limit; a refusal before a worker runs counts no function call. Read function_calls by environment with read_usage.

Refusals #

A rejected start returns a refusal before the deploy begins. After a deploy starts, read a failed row through read_status or list_versions. Runtime failures appear on the application's route; use read_logs for the same environment.

What you see Cause Remedy
function_native_module The supplied files or installed dependencies include a native .node module. Use a JavaScript dependency without native code. Otherwise, ask the owner before creating a separate server application, then deploy there.
function_count_exceeded Too many files are under functions/. Keep only handlers there and move shared modules to lib/. Follow the named limit.
function_tree_too_large or function_tree_too_many_entries The installed files or dependencies exceed the byte or entry limit. Remove unused dependencies or files and deploy again.
function_tree_link Packaging found a link it could not carry as files inside the deploy folder. Include the target as ordinary files within the folder and deploy again.
artifact_layout_invalid The deploy folder has neither a valid server start nor a root functions/ or client/ folder, or another layout bound failed. Read detail and correct the named layout or bound.
migrations_without_database, migration_busy or migrations_too_large The migration files lack a database declaration, no migration slot is free, or the files exceed the bound. Follow Migration refusals before retrying.
429 function_busy The environment or account has reached a worker or call limit, or the account has reached its daily CPU limit on this replica. Read detail. For a worker or call limit, reduce simultaneous calls and retry later. For the daily CPU limit, retry after 00:00 UTC. Another replica may still serve earlier. No retry time is returned.
503 function_unavailable The function did not run. The files, settings, worker network or replica could not serve the call. Retry the request. If it keeps failing, give the application owner the response detail and any reference. You can use submit_feedback if your management connection admits it.
502 upstream_ended The worker ended before returning its response, including at a runtime limit. Read function logs. Reduce the work or memory needed by the call. If it needs a server, ask the owner before creating a separate server application and deploy there.
502 upstream_failed The function request failed inside the platform. The detail may say whether the function ran. If the detail says nothing ran or an asset could not be read, retry. If the proxy failed before answering, check whether the operation took effect and repeat it only if safe. For a scheduled run, check its recorded outcome before starting another. Give a repeated refusal's detail to the application owner, or use submit_feedback through an admitted management connection.
404 not_found No function or client file matches the request. Check the deployed functions list, path, method and client-file precedence.
404 scheduled_handler_only A normal request reached a schedule's protected handler path. Use a public path for a normal HTTP request. To start the job, ask the application owner or use run_schedule if your management connection admits it. See Add a scheduled job.
serverless_no_websocket A request tried to upgrade to a WebSocket. Ask the owner before creating a separate server application for that work, then deploy there.
egress_undeclared A destination has no permitted exact hostname declaration, including a loopback name or a request hostname with two final dots. Declare a valid exact host and submit the complete manifest. A wildcard does not admit it. For localhost or a name ending .localhost, use the service's public hostname. Remove an extra final dot from the request URL.