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.

Before your AI starts #

For the AI tool:

  • 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).

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 starting application that uses a database, turnzero scaffold --template functions-app --application <application id> writes a notes application under app/. Use the identifier from create_application. Its manifest declares a database; the folder includes a web page, the /api/notes function, shared modules, migrations and tests.

Work from app/ when using that 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_allowance, database, egress, email, schedule, secrets and storage.

Follow Use the 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 #

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 platform looks for a function for any request method. If none matches, GET and HEAD use client/404.html with status 404 where that file exists. Without it, a page path can use client/index.html. 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.

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, using the platform's connection pooler with the server's certificate checked. It receives no APP_DATABASE_DIRECT_URL. The platform applies migrations before a deploy, promote or rollback makes that version serve; the function does not run 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.

Call another service #

Use global fetch for an outgoing HTTP request. Declare the destination by its 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.

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 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 after the owner has asked for development, submit the manifest, then provision its local settings. The local function reads development's database. If it needs tables from migrations/, deploy to development before running it locally, so the platform applies those migrations first. Without development, use tests that need no database, then deploy to production. 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 or platform migrations. 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.

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 bound that counts files and folders, dependencies included. A failed build names the relevant bound. 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.

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 bound.
function_tree_too_large or function_tree_too_many_entries The installed files or dependencies exceed the byte or entry bound. 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 files, settings, worker network or replica cannot serve the call. Retry later. Report a repeated failure with the application, environment and response through submit_feedback.
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. Retry later and report a repeated failure through submit_feedback.
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. Test through run_schedule, following 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 exact hostname declaration. Declare the exact host and submit the complete manifest. A wildcard does not admit it.