--- title: Turn Zero Cloud description: Start using Turn Zero Cloud from your AI coding tool: connect it, deploy a first application, and find the guide for every other task. slug: / order: 1 visibility: public redirects_from: [/concepts/what-turn-zero-cloud-is] --- # Turn Zero Cloud Turn Zero Cloud hosts applications built with AI coding tools such as Claude Code and Codex. It provides Node.js hosting, PostgreSQL, file storage, user sign-in, a secrets vault and application services. Each server has a size; [a site of static files alone](/cloud/guides/publish-a-static-site/) needs none. Charges follow usage and monthly items; the [pricing page](https://turnzero.ai/pricing) gives the current rates. Connect through Model Context Protocol (MCP) to configure services, deploy applications, and read their status and logs. Build and test the code with your coding tool. Deploy directly to production, or add a development environment and promote tested versions. ## Start here Setup prompt: ```text Set me up with Turn Zero Cloud and a small demo app. Read https://turnzero.ai/cloud/getting-started/set-up/index.md in full and follow the steps. ``` Follow [Set up Turn Zero Cloud](/cloud/getting-started/set-up/) to connect and build a demo. For manual connection instructions, use [Connect your AI assistant](/cloud/getting-started/connect-your-tool/). To deploy an existing application, start with [Deploy from your computer](/cloud/getting-started/deploy-an-application/). For the sequence from code through local tests, development and production, follow [Build, test and publish an app](/cloud/getting-started/build-test-and-publish-an-app/). For a new service, use [Build a database-backed service](/cloud/getting-started/build-a-database-backed-service/) or [Build a mobile app's backend](/cloud/getting-started/build-a-mobile-app-backend/). For a public form that saves entries in PostgreSQL, use [Build a form backed by a database](/cloud/guides/build-a-form-backed-by-a-database/). Check local requirements in [What your computer needs](/cloud/getting-started/prerequisites/), and what your code must provide in [What a deployed application needs](/cloud/concepts/what-a-deployed-application-needs/). [Find the guide for a task](/cloud/getting-started/find-a-guide/) covers the other workflows. ## The served version Read the content version these pages describe in the page manifest or on the [management contract's source page](/cloud/reference/sources/schemas/management-api/). ## What the platform does not do The platform does not build your source, approve destructive actions for you, or make your application portable on its own. ## Features ### Built from the ground up for AI coding tools | Feature | | | --- | :---: | | MCP server for Claude Code and Codex | ✓ | | Tools and APIs provide hints to your AI | ✓ | | Documentation your AI reads directly, written for AIs | ✓ | | Context for each action: what it needs before your AI calls it | ✓ | | Skills: ready procedures your AI can run | ✓ | | An integration guide written for your AI in every feature package | ✓ | | Test doubles, so your AI's tests run offline | ✓ | | A library of feature packages that your AI adds to your project and uses | ✓ | | Scaffolding for your AI | ✓ | | Deployment status, logs, and counters available directly to your AI for diagnosis | ✓ | | Permanent deletes require your approval | ✓ | | Send feedback to Turn Zero from your chat session | ✓ | ### Deploy and run | Feature | | | --- | :---: | | Node.js hosting for your built app, at its own address under ai.host | ✓ | | Your own domain for any application's production environment, with two DNS records; a paid monthly item | ✓ | | A production environment, and a development environment when you want one: deploy, promote, roll back, restart, version history, pause and resume | ✓ | | A health check before each new server version takes over; a failed deploy leaves the running version serving | ✓ | | Unattended deploys from a continuous integration (CI) job, on a limited token | ✓ | | Local runs on your own machine, before you deploy | ✓ | | Schedules, with each run's outcome recorded | ✓ | | Egress firewall: your app reaches only the hosts you declare, watched first, then enforced | ✓ | | Request limits: a time limit on every request | ✓ | | Per-address and per-user rate limits on every request | ✓ | | [WebSockets](/cloud/guides/use-websockets/) for apps that declare them, open beyond the request deadline within their limits, and streamed responses up to it | ✓ | | Runtime isolation: each server app runs in its own container, with its own credentials, secrets, database, and files | ✓ | | One API for your AI coding tool, your scripts with limited, revocable tokens, and the turnzero.ai dashboard | ✓ | | A choice of Shared 0.5 GB or Shared 1 GB for each server, and each application's usage for the month, read from your tool or the dashboard | ✓ | | Export of each application's database and files, and account deletion with your approval | ✓ | ### Backend feature packages | Feature | | | --- | :---: | | Accounts for your app's users: sign-in with Google, GitHub, a passkey, an emailed code, or a work account (Microsoft SSO), with sessions, invitations, and open or invitation-only sign-up | ✓ | | End-user management from your AI session: invite, list, suspend, and delete your app's users | ✓ | | Database: PostgreSQL for each environment, with migrations | ✓ | | File storage: named areas | ✓ | | Short-lived upload and download links, so your app moves files straight to and from storage | ✓ | | A secrets vault with file, terminal, and dashboard entry; also accepts values you choose to share in chat. Gateway keys can be replaced without redeploying | ✓ | | External API calls on your stored keys, streaming included | ✓ | | [AI calls](/cloud/concepts/glossary/#ai-calls) on the platform's key draw the account's balance at the provider's published price plus a markup; also bring your own AI key | ✓ | | Logging, and hosting safeguards: request checks and time limits | ✓ | | Push notifications to iPhone and Android | ✓ | | Email from your app: confirmations, receipts and invitations, without running a mail provider; charged per recipient | ✓ | | Each application can have its own issue space for issues and feedback. | ✓ | ### Web app backends | Feature | | | --- | :---: | | Your web client's files served beside your backend, at the same address: its page, scripts, styles, fonts, and images, with no backend action per file | ✓ | | Browser sign-in held in one session cookie on your app's own address: HttpOnly, Secure, and SameSite=Lax, carrying a signed session token the Account package verifies | ✓ | | Ready-made sign-in pages on your app's own address, under `/__account/`, so your AI builds no sign-in screens | ✓ | | A sign-in gate for invitation-only and work-account apps: a visitor without a session goes to the sign-in page, and an API call is refused 401 | ✓ | | Cookie isolation: your app's own cookies stay on its own address, the platform removing any `Domain` attribute | ✓ | ### Mobile and desktop app backends | Feature | | | --- | :---: | | Native sign-in: standard mobile OAuth, Sign in with Apple, and Google sign-in | ✓ | | Sessions that last months, and token authentication on every request | ✓ | | Universal and app links | ✓ | | A minimum supported app version | ✓ | | From inside your app, a user registers a passkey, ends a session, and deletes the account | ✓ | | Desktop apps for macOS and Windows sign in through the system browser, as [native clients](/cloud/concepts/glossary/#native-client) (OAuth/PKCE) | ✓ | ## How it works Your AI coding tool writes the app; Turn Zero Cloud runs it, providing hosting, database, sign-in and scaling. Your tool writes, builds, and tests the application on your computer. Provided test doubles let your tool test integrations locally without calling live services. For a server application, the platform installs its runtime dependencies, builds the hosting image, runs it in production at the application's address, and records its logs, counters, and usage. A static site serves the files you deploy, with no install, image build or server to start. A new application uses production alone. If you ask to try versions before they serve, your tool [turns on development](/cloud/guides/turn-on-development-and-promote/). Each deploy then runs there first, and a promote moves a version to production. [Applications and environments](/cloud/concepts/applications-and-environments/) explains the environments. Three kinds of caller use the same actions: your AI coding tool through the MCP server, a script or pipeline through the HTTP API with a [minted token](/cloud/guides/mint-a-token/), and you through the signed-in website. Each server has a size; [a site of static files alone](/cloud/guides/publish-a-static-site/) needs none. The [pricing page](https://turnzero.ai/pricing) gives the rates for usage and monthly items, and `read_rate_card` returns them. ## Machine surfaces of this documentation This documentation is published at `https://turnzero.ai/cloud/`. An AI coding tool can read it without a browser through five machine surfaces: - **The index**, at `https://turnzero.ai/cloud/llms.txt`, has one line per page with the page's title, address, and description. - **The whole text**, at `https://turnzero.ai/cloud/llms-full.txt`, contains every page except the generated reference, which is read page by page. - **The page manifest** is at `https://turnzero.ai/cloud/docs.json`. - **The Markdown copy** of a page is at the page's address followed by `index.md`. - **The OpenAPI 3.1 document** for tzCloud management actions is at `https://turnzero.ai/cloud/openapi.json` for client generators and API tools. For Turn Zero account actions, use `https://turnzero.ai/openapi.json`. A fetch tool that summarizes what it reads, such as Claude Code's WebFetch, can leave pages out of its summary of the index, which lists every page. To find the page for a task, read [Find the guide for a task](/cloud/getting-started/find-a-guide/), search the whole text, or call `search_documentation` with a `query`. Such a tool can shorten a page's code samples too. To read a sample whole, download the page's Markdown copy, with `curl` for example. Signed in, `read_documentation` reads the page too, and never splits a sample that fits in one chunk ([How an AI reads these docs](/cloud/concepts/reading-this-documentation-as-a-tool/)). At the origin root, `https://turnzero.ai/llms.txt` introduces Turn Zero Cloud, then links to [Set up Turn Zero Cloud](/cloud/getting-started/set-up/) under **Start here**. The site's public pages follow, then this [documentation tree](/cloud/concepts/glossary/#documentation-tree), the pages under `/cloud/`. It also indexes the Turn Zero Docs tree, the pages under `/tzdocs/`. `https://turnzero.ai/llms-full.txt` contains the whole text of every documentation tree that every account can read. `https://turnzero.ai/sitemap.xml` lists public pages' addresses, the pages of this tree among them. Each hand-written page there carries the date its text last changed. The navigation beside each page lists pages alone, so these files do not appear in it, and their addresses do not change. Every account can read this tree. Turn Zero's production site is public, open to every visitor and to search engines. Its development site is private. Where a site is private, what a request receives depends on how it is sent: - A browser opening a page, a request that sends `Sec-Fetch-Mode: navigate` or `Sec-Fetch-Dest: document`, receives the invitation notice. The response is `401` with a `WWW-Authenticate` header that mentions the request header `Turnzero-Show-Page`. - The same browser request for a machine surface receives `404` with `not found`, never the notice. - Any other request, such as a tool's fetch, a script, or `curl`, receives a documentation page or a machine file, marked `X-Robots-Tag: noindex, nofollow`. The site's own pages, such as `/` and `/pricing`, answer it `401` unless it sends `Turnzero-Show-Page`; the terms and the privacy policy are served without that header. - A request that sends `Turnzero-Show-Page` with any non-empty value always receives the page or the file, and a Turn Zero Cloud [bearer token](/cloud/concepts/glossary/#bearer-token) always receives a machine file. A tool signed in to Turn Zero Cloud reads the index as the resource `docs://cloud/llms.txt` and the whole text as `docs://cloud/llms-full.txt`. With the `read_documentation` action it also reads one page or one section, and `search_documentation` finds the sections that match a few words, so it needs no download. [How an AI reads these docs](/cloud/concepts/reading-this-documentation-as-a-tool/) explains reading a long page in parts, going straight to a section, and searching. ## Related The [glossary](/cloud/concepts/glossary/) defines each term this documentation uses. [What a deployed application needs](/cloud/concepts/what-a-deployed-application-needs/) lists on one page what your code and files must provide: the port, the health path, the start, and the database settings and migrations. [What happens without asking](/cloud/concepts/what-happens-without-asking/) lists what your tool does on its own and which actions it asks you about first. The [refusals page](/cloud/reference/refusals/) lists all of the platform's refusals, with the cause and remedy of each; a backend package's own failures are listed on its package page. --- title: Set up Turn Zero Cloud description: Start setup with one prompt in your AI assistant, follow the connection and browser sign-in steps, then use the build prompt for a small demo app. slug: /getting-started/set-up order: 1 visibility: public redirects_from: [/getting-started/set-up-turn-zero-cloud-with-your-ai, /getting-started/set-up-turn-zero-cloud] --- # Set up Turn Zero Cloud If you're deciding whether Turn Zero Cloud fits your project, read [Before you start](https://turnzero.ai/turnzero/before-you-start/) for an overview of the tools, costs and terms for your data. **Working unattended?** [Deploy with nobody at the keyboard](/cloud/guides/deploy-with-nobody-at-the-keyboard/) covers existing signed-in connections and tokens, and work your AI can prepare before sign-in. **Already have an app?** Open the app's folder or workspace with your AI coding agent. Then follow [Use the app you already have](#use-the-app-you-already-have). Prompt: To try the notes demo, paste this into your AI assistant. > Set me up with Turn Zero Cloud and a small demo app. Read `https://turnzero.ai/cloud/getting-started/set-up/index.md` in full and follow the steps. This session sets up the connection and the demo folder or workspace, then gives you a build prompt. Paste that prompt into the session your AI assistant names to build the demo. On your computer, approve adding the Model Context Protocol (MCP) connection and the demo folder's full path before leaving it unattended. You can say: "Add the Turn Zero MCP server to this AI coding agent and use this folder: ``." In a cloud workspace or chat, add the connection in the product's settings. Complete browser sign-in when the steps ask for it. If your AI assistant is already signed in and has Turn Zero Cloud tools, use that connection. To create an app, submit its manifest, or deploy through MCP, use browser sign-in for your AI assistant's connection or [a minted token with the required access](/cloud/getting-started/connect-your-tool/#connect-an-unattended-ai-coding-agent-with-a-token). In ChatGPT on the web, sign in through [the Cloud plugin](/cloud/getting-started/connect-your-tool/#chatgpt-and-codex-in-chatgpt-s-cloud). For an MCP client on a computer without a browser, use [device sign-in](/cloud/concepts/sign-in-sessions-and-tokens/#device-sign-in-limits) and approve its code in a browser on another computer. This gives limited access, including tzTrack and some account and documentation tools. `turnzero login` and `turnzero login --device` authorize commands such as `turnzero check` and `turnzero deploy` on your computer for an existing app. What the prompt does: - Connects your AI to Turn Zero through MCP. - Has you sign in with your browser. If you're new, your free Turn Zero account is created. - On your computer, creates a `turnzero-demo` folder at a location you confirm. In a cloud workspace, uses the repository or workspace you selected. - Gives you a prompt to build and deploy a small notes app where you sign in and keep your own private notes. The session that builds it gives you the link. ## What you do Your AI assistant does most of the work. You: - approve the changes it asks for, such as adding the Turn Zero Cloud connection and creating a folder for the demo; - sign in once in your browser, with GitHub, Google, or a code sent to your email. If you're new, your free account is created at that first sign-in; - paste the build prompt your AI assistant gives you at the end; - depending on your AI assistant, you may be walked through a few steps to connect it by hand. Your AI coding agent's safety check may block adding the connection even after you approve it. If that happens, run the exact command it gives you in your own terminal, then tell it to carry on. **Prefer to connect by hand?** Follow [Connect your AI assistant](/cloud/getting-started/connect-your-tool/) for your product, then ask your AI assistant: *"Check my Turn Zero connection."* For local deploys, use the npx command the deploy tool returns. It needs Node.js and npm and runs without a global install. To install `turnzero` globally, run `npm install -g turnzero`. See [Install the turnzero command](/cloud/getting-started/prerequisites/#install-the-turnzero-command). For the `turnzero` CLI, [choose its platform address](/cloud/concepts/how-the-turnzero-command-finds-its-credential/#the-address-a-credential-goes-to) with `--origin` or `TURNZERO_CLOUD_ORIGIN`. This setting is separate from your AI coding agent's MCP connection. The linked section explains how the command checks that it sends the credential to the right address.
## For the AI assistant These steps are for you, the AI assistant. Do as much as you can yourself. When a step needs the person, tell them exactly what to do and wait for their response before taking that step. With nobody present, follow [Deploy with nobody at the keyboard](/cloud/guides/deploy-with-nobody-at-the-keyboard/) and keep working on what needs no person, in the folder or workspace the person approved. If the person already asked you to build their own app, skip the demo folder and the build-prompt hand-over. Follow [When to ask before changing setup](#when-to-ask-before-changing-setup) when setting up the connection, then build the requested app in the approved folder or workspace. Before deploying that app for the first time, read [Ways to deploy](/cloud/getting-started/ways-to-deploy/) to choose the route. Before writing code, follow [Before your AI starts](/cloud/getting-started/build-test-and-publish-an-app/#before-your-ai-starts). ### Use the app you already have If your session for this app has Turn Zero Cloud tools, call `start` to check the connection. If the tools are missing, read [When to ask before changing setup](#when-to-ask-before-changing-setup) before following the steps for your tool in [Connect your AI assistant](/cloud/getting-started/connect-your-tool/). Then follow [Bring an existing application](/cloud/guides/bring-an-existing-application/) from the app's folder or workspace. ### When to ask before changing setup Follow your permission rules and ask the person before making a setup change if you're unsure they approved it. ### Before you start There is no hosting plan or tier to choose. Your app's charges draw first from your account's monthly [Free Allowance](/cloud/guides/stay-inside-the-monthly-free-usage/), which also covers your other charged usage. Use the guide to estimate whether your setup fits. 1. Read this whole page. If your fetch tool gives you a summary, as Claude Code's WebFetch does, fetch the full page with a shell command or `read_documentation`. For `read_documentation`, set `tree: "cloud"` and `page: "/getting-started/set-up"`. Use `next_offset` to continue to the next part and `stamp` to keep reading the same page version. A summary leaves out steps and the text you must show the person word for word. 2. Read [Connect your AI assistant](https://turnzero.ai/cloud/getting-started/connect-your-tool/index.md) the same way when a step sends the person there, and show only the section for their tool. If you can't read it whole, don't rebuild the steps from a summary. Give the person [Connect your AI assistant](https://turnzero.ai/cloud/getting-started/connect-your-tool/) and tell them to open their tool's section and complete the connection there. 3. Check whether Turn Zero Cloud is already connected. Look for its tools, such as `start` and `tzcloud_deploy_files`, under any connector name; if your host loads tools on demand, search for them first. If you find them, call `start`. It returns the account and whether it is active or suspended. If `start` succeeds and this session has Cloud hosting tools, keep the existing connection. Call `read_account` to check the email address on the signed-in account. Ask the person to confirm it, or the account ID from `start` if the email address is unavailable. If the connection uses a different account, pause the demo and ask the person to switch accounts on the existing connection. Check the account again before building the demo. A successful `start` does not distinguish browser sign-in from device sign-in. Check that this session has Cloud hosting tools before building. A [device sign-in](/cloud/concepts/sign-in-sessions-and-tokens/#device-sign-in-limits) can read the account and cannot deploy Cloud apps. On the person's computer, still choose the demo folder (steps 1, 2 and 5 below: Check what is already set up, Ask once, and Make the folder). Then go to [Give the person the build prompt](#give-the-person-the-build-prompt). 4. Once the Cloud tools are available, call `start` if this session has yet to call it. To find an action, call `read_context` with `id: "tools"` and `limit: 16000`; it lists the available tools. For a platform rule, call `read_context` with `id: "overview"`. 5. Find where you run, and follow that section: | Where you run | Section | | --- | --- | | Claude Code (a terminal or the Claude desktop app's Code tab), or Codex (the CLI, the ChatGPT desktop app, or an editor), on the person's computer or a remote machine | [On the person's computer](#on-the-person-s-computer) | | Claude Code on the web, or Codex in ChatGPT's cloud | [In a cloud workspace](#in-a-cloud-workspace) | | Claude's chat (claude.ai, the desktop app, or the phone app), or ChatGPT's chat | [In a chat](#in-a-chat) | If your desktop or editor app shares the CLI configuration, reuse the existing Turn Zero connection by the name it uses. A separately configured chat or cloud workspace uses `turnzero-hosting` at `https://tzcloud.turnzero.ai/mcp`, following Connect your AI assistant. If you can't tell, ask the person which tool they're using. An existing connection may have been added earlier as `turnzero-cloud`. Reuse it if it is signed in and provides tzCloud tools; check its connection URL before changing or removing it. If the person's work account doesn't let them add Turn Zero, tell them. Suggest they ask whoever manages their work account to add it. If their company allows it, they can instead set up Turn Zero on their own computer: ask them to open Claude Code or Codex and paste this page's setup prompt. That new session does the setup and asks for any approvals it needs. ### On the person's computer **1. Check what is already set up.** These checks are read-only: - Claude Code: run `claude mcp list`. If it lists `turnzero` or the earlier `turnzero-cloud`, run `claude mcp get` with that name. Check that the demo session has Turn Zero Cloud's tools before reusing the connection. A connector added in Claude's chat settings shows in `claude mcp list` as `claude.ai turnzero-hosting`, and `claude mcp get` doesn't find it. If its tools are in this session, the connection is done. - Codex: run `codex mcp list`. For MCP servers configured on the same Codex host, the ChatGPT desktop app, the CLI, and the editor extension share this list. A turnzero-hosting plugin added in ChatGPT on the web also appears in the ChatGPT desktop app; if its tools are in this session, the connection is done. - Find the folder for the demo. If this session started in an empty folder, use that one. Otherwise, look for where the person keeps code, such as `~/code`, `~/projects`, or `~/Documents/GitHub` (on Windows, under `C:\Users\`), and pick an unused `turnzero-demo` beside their projects, never inside one. **2. Ask once.** Use [When to ask before changing setup](#when-to-ask-before-changing-setup) to check what the person has approved. Ask in one message for approval to add the server if needed and for any browser sign-in the connection needs. Ask the person to confirm the demo folder's full path in the same message if it is still unconfirmed. If the existing connection is signed in and ready, only the folder may need confirmation. Wait before taking a step that needs the person. For a blocked connection change, give the person step 3's exact command for their tool to run in their own terminal. Continue the setup once they say the command is done. **3. Add the server**, if step 1 (Check what is already set up) found none and the person has approved adding it: - Claude Code: `claude mcp add --transport http --scope user turnzero https://turnzero.ai/mcp`. If `claude mcp get turnzero` showed it at another scope, or failed to connect, remove it first with the scope it reported, such as `claude mcp remove turnzero --scope local`. - Codex: tell the person a browser window will open for sign-in, then run `codex mcp add turnzero --url https://turnzero.ai/mcp`. Let it run for at least five minutes while they sign in; if your command tool gives you a session handle, keep waiting on it. If the browser doesn't open and the command prints a link, give the person the link. Codex may ask the person to approve writing its settings file and reaching the network; both are expected. On Windows, if PowerShell says `claude` is not recognized, first read the [Claude Code PATH note](/cloud/getting-started/connect-your-tool/#claude-code). Check whether `%USERPROFILE%\.local\bin\claude.exe` exists yourself; this check is read-only. If it exists, check whether `%USERPROFILE%\.local\bin` is missing from the person's user `Path`. Ask before adding it as a new entry, keeping every existing entry. Once approved, add that entry. Ask the person to close and reopen the terminal. If PowerShell runs inside the Claude desktop app's Code tab, ask them to quit and reopen that app. If it runs inside an editor, ask them to restart the editor too. Wait for the restart before continuing in a new session. In that new session, run `claude --version` by its command name. When it answers, resume at step 1 (Check what is already set up), then step 3 (Add the server) where needed. Keep the build-prompt hand-over pending until this recovery and the connection check are complete. If the file is missing or the command still fails after the restart, follow [Claude Code's PATH troubleshooting](https://code.claude.com/docs/en/troubleshoot-install#verify-your-path). Where the tool's command is absent or remains unusable after its troubleshooting, the person connects by hand. Give them their tool's steps from [Connect your AI assistant](/cloud/getting-started/connect-your-tool/), word for word. Wait for them to confirm the connection was added before handing over. Then continue at step 5 (Make the folder). **4. Sign in.** It depends on the tool: - Claude Code: don't run `claude mcp login` yourself; without an interactive terminal it stops with "stdin isn't a terminal". The person signs in from the new session in step 6 (Hand over). - Codex: if the add printed `Successfully logged in`, it's done. Otherwise run `codex mcp login turnzero`. Then run `claude mcp list` or `codex mcp list` and check that `turnzero` is listed. Claude Code shows `Needs authentication` until the person signs in. In Codex, the Auth column shows `OAuth` once the person has signed in and `Not logged in` before. The new session's tool list is the final check. **5. Make the folder** and check that it's empty. If it already holds files, suggest `turnzero-demo-2` and ask again. **6. Hand over.** Leave the folder empty and go to [Give the person the build prompt](#give-the-person-the-build-prompt). ### In a cloud workspace Don't run `claude mcp add` or `codex mcp add` here: they configure the workspace, not the product's connection. Use the product's connector settings. 1. If Turn Zero Cloud's tools are missing, the person connects in the product's settings. Give them the steps from [Connect your AI assistant](/cloud/getting-started/connect-your-tool/), word for word: **Claude's chat and Claude Code on the web** or **ChatGPT and Codex in ChatGPT's cloud**. Wait for them to finish. 2. The demo is built later in the repository or workspace the person chose. Don't create a separate project, and don't commit or push unless the person asks. 3. Go to [Give the person the build prompt](#give-the-person-the-build-prompt). ### In a chat 1. If Turn Zero Cloud's tools are missing, give the person the steps for their chat from [Connect your AI assistant](/cloud/getting-started/connect-your-tool/), word for word, and wait. You don't need to ask before showing them. 2. Search or load your tools again and call `start`. 3. Go to [Give the person the build prompt](#give-the-person-the-build-prompt). When they paste it here, you deploy by uploading the app's files with `deploy_files`. ### Give the person the build prompt Don't build the demo yourself. The person pastes the build prompt, which shows them how little it takes to build and deploy an app. Show them the prompt and the steps that fit, word for word. If Turn Zero Cloud's tools are in this session, and on the person's computer this session runs in the demo folder, tell them to paste the prompt here: ```text Using Turn Zero, build me a notes app where I sign in and keep my own private notes. Put it online and give me the link. ``` Otherwise, show the list for the person's tool, with `` replaced by the demo folder's full path. Replace `` in item 1 with the one instruction below for their interface. Ask which interface they use if you cannot tell. Show no placeholder or alternative instruction to the person. Never show the terminal instruction where the tool's command was not found. Keep items 2 and 3, including the sign-in step. Choose the opening instruction from this table: | Interface | Opening instruction | | --- | --- | | Claude Code in a terminal | Open a terminal, run `cd ""`, then `claude`. | | The Claude desktop app's Code tab | In the Claude desktop app's Code tab, start a new session and choose ``. | | Codex in a terminal | Open a terminal, run `cd ""`, then `codex`. | | Codex in the ChatGPT desktop app | In the ChatGPT desktop app, choose Codex. Open a project whose primary folder is ``, creating one if needed, and start a new chat for that project. | If Codex sign-in is still pending, first say: "Turn Zero Cloud sign-in is still pending. Follow the sign-in step in the list below." Then show the complete three-item Codex list, including its sign-in step. Claude Code: 1. `` 2. Paste this prompt into the new session. In the Code tab, if sign-in is needed, finish step 3 before pasting. ```text Using Turn Zero, build me a notes app where I sign in and keep my own private notes. Put it online and give me the link. ``` 3. If the new session says a connection needs authentication, type `/mcp`, choose the Turn Zero connection by its listed name, and sign in in your browser. In the Claude desktop app's Code tab, `/mcp` does not reach a server added with `claude mcp add`. Run `claude` in a terminal and type `/mcp` there, or add it by hand with [the connector steps](/cloud/getting-started/connect-your-tool/#claude-s-chat-and-claude-code-on-the-web). Choose one route. If the command added `turnzero` and you want the connector instead, run `claude mcp remove turnzero` first. In the Code tab, after signing in, start a new session in the demo folder and paste the prompt from step 2. Codex: 1. `` 2. Paste this prompt into the new chat: ```text Using Turn Zero, build me a notes app where I sign in and keep my own private notes. Put it online and give me the link. ``` 3. If the new chat says Turn Zero Cloud needs a sign-in, sign in where the connection was added. If it was added with `codex mcp add`, run `codex mcp login turnzero` in a terminal and sign in in your browser. If it was added in the ChatGPT desktop app's settings, sign in again there. A cloud workspace or a chat: 1. In a cloud workspace, start a new session or chat in the same tool. Use the same repository if you chose one. If the tool asks which connectors to use, choose **turnzero-hosting**. In a chat, stay in this conversation. In Claude's chat, open **+** → **Connectors** and check that **turnzero-hosting** is on. 2. Paste this prompt into that session or chat: ```text Using Turn Zero, build me a notes app where I sign in and keep my own private notes. Put it online and give me the link. ``` When the person pastes it, the session builds through Turn Zero Cloud's tools and skills, and [Deploy from a chat](/cloud/getting-started/build-an-app-from-a-chat/) gives the steps for a session with no shell. ## If something goes wrong | What you see | What to do | | --- | --- | | `claude: command not found`, `codex: command not found`, or PowerShell says "The term 'claude' is not recognized as the name of a cmdlet" | Follow step 3's missing-command instructions in [On the person's computer](#on-the-person-s-computer). They check Claude Code's Windows `PATH` before using a by-hand connection. | | `claude` fails from your AI coding agent's zsh shell with "open terminal failed: not a terminal" or another wrapper message | `claude` may be a shell function or alias from a wrapper. In zsh, run the same arguments with `command 'claude'`, such as `command 'claude' mcp get turnzero`, to reach the installed program. | | `codex` fails with "The system cannot find the path specified" | An old Codex launcher may be first on the path. List them with `where.exe codex` (Windows) or `which -a codex`, and try only one that Codex's own installer put there. Don't reinstall it or change the path; if none works, use [Connect your AI assistant](/cloud/getting-started/connect-your-tool/). | | "Access is denied" or `Read-only file system` when adding the server | Your AI coding agent's sandbox can't write its settings. Approve the access it asks for. In a cloud workspace, connect in the product's settings instead. | | A fetch in a cloud workspace fails with a 403 or a proxy error | The workspace blocks that site. Allow it in the workspace's internet settings, or let your AI assistant use Turn Zero Cloud's own tools, which may still work. | | `Needs authentication` in `claude mcp list` | You haven't signed in yet. Type `/mcp` in a new Claude Code session and choose the existing Turn Zero connection by its listed name. In the desktop app's Code tab, use `/mcp` in a terminal's `claude` session instead, or add the connector by hand. | | The new session has no Turn Zero Cloud tools | Start one more new session. In a chat or cloud workspace, check that **turnzero-hosting** is turned on. If it is still missing, sign in again. | | The browser sign-in finishes but the tool still shows disconnected | Retry its sign-in once, using the address for your tool in [Connect your AI assistant](/cloud/getting-started/connect-your-tool/). Don't paste tokens or browser addresses into its settings. | | Codex asks which client registration to use, or sign-in fails while registering it | Run `codex mcp login turnzero --oauth-client-registration dcr`. The `dcr` option asks Codex to register this client dynamically. | | `invalid_client`, or a page titled Connect your tool again | Your tool's registration expired. Remove the connection and add it again. | [Setup troubleshooting](/cloud/troubleshooting/setup/) covers more problems, and [Refusals](/cloud/reference/refusals/) lists every refusal by name. ## Related - [Connect your AI assistant](/cloud/getting-started/connect-your-tool/): connect by hand, check, refresh, or remove the connection. - [Deploy from a chat](/cloud/getting-started/build-an-app-from-a-chat/): how an app is built with no shell. - [Deploy with nobody at the keyboard](/cloud/guides/deploy-with-nobody-at-the-keyboard/): sign in once, then run unattended. - [What your computer needs](/cloud/getting-started/prerequisites/): what the `turnzero` command needs. --- title: Connect your AI assistant description: Connect Claude Code, Codex, Claude's chat, or ChatGPT to Turn Zero Cloud by hand, sign in, and check, refresh, or remove the connection. slug: /getting-started/connect-your-tool order: 2 visibility: public redirects_from: [/getting-started/connect-claude-code-or-codex, /getting-started/connect-your-ai-tool, /getting-started/connect-your-ai-coding-tool, /guides/sign-in-and-sign-up, /getting-started/connect-your-ai-assistant] --- # Connect your AI assistant This page describes how to connect your AI assistant to Turn Zero Cloud yourself. To have your AI assistant do it for you, paste the prompt from [Set up Turn Zero Cloud](/cloud/getting-started/set-up/) instead. | If you use | Steps | | --- | --- | | Claude Code, in a terminal or the Claude desktop app's Code tab | [Claude Code](#claude-code) | | Codex: the CLI, the ChatGPT desktop app, or an editor | [Codex](#codex) | | Claude's chat (claude.ai, the desktop app, the phone app), or Claude Code on the web | [Claude's chat and Claude Code on the web](#claude-s-chat-and-claude-code-on-the-web) | | ChatGPT on the web, or Codex in ChatGPT's cloud | [ChatGPT and Codex in ChatGPT's cloud](#chatgpt-and-codex-in-chatgpt-s-cloud) | | An AI coding agent that runs with nobody at the keyboard, such as a scheduled run | [Connect an unattended AI coding agent with a token](#connect-an-unattended-ai-coding-agent-with-a-token) | Choose the address for your AI assistant: - For Claude Code or Codex CLI, including a desktop or editor sharing its configuration, use `https://turnzero.ai/mcp` named `turnzero` for tzCloud, tzTrack and tzMesh. - For a chat app using Turn Zero Cloud, use `https://tzcloud.turnzero.ai/mcp` named `turnzero-hosting` for tzCloud. - For a chat app using tzTrack or tzMesh, use `https://tztools.turnzero.ai/mcp` named `turnzero-tools` for tzTrack and tzMesh. Your account’s access still limits the tools you can use. The first time you sign in, Turn Zero asks you to confirm before it creates your free account. Each address has its own sign-in; connecting to one does not connect the others. A desktop or editor that shares the CLI configuration reuses `turnzero`; add no second connection there. The connection lists tzCloud tools as `tzcloud_`; for example, `"deploy"` is `tzcloud_deploy`. If a listed tool returns "Unknown tool", [refresh the connection](#refresh-or-remove-the-connection). **Already connected?** If your AI assistant has a signed-in connection with tzCloud tools, go to [Check the connection](#check-the-connection). Reuse it if it is signed in and provides tzCloud tools; check its address before changing or removing it. After your assistant's steps, [sign in](#signing-in) and [check the connection](#check-the-connection). An unattended AI coding agent has no browser sign-in; its section says how it checks the connection. ## What each sign-in lets you do Signing in to the website, connecting your AI assistant, and authorizing the `turnzero` command give access in different places. Use this table to see which connection your task needs. | Sign-in or credential | What it lets you do | What it does not do | | --- | --- | --- | | Your browser sign-in on turnzero.ai | Use your account's dashboard and approve actions that ask for your approval. | Signing in from the website's header does not connect your AI assistant or authorize the command on your computer. | | Your AI assistant's MCP connection, signed in through the browser | Create and configure applications, deploy through the connection, and mint tokens for commands or unattended jobs, within your account's access. | It does not store a credential for the command on your computer. Your AI assistant can [authorize the computer](#authorize-this-computer-for-deploys) through this connection. | | [Device sign-in to the MCP connection](/cloud/concepts/sign-in-sessions-and-tokens/#device-sign-in-limits) | Use tzTrack and limited account and documentation tools after approving a code in a browser on another device. | It cannot manage or deploy Cloud applications, mint tokens, or use Cloud storage and outbound-request services. For Cloud management, use the browser sign-in above or a minted token. | | The computer token stored by `turnzero login`, `login --device`, or `authorize` | Run commands such as `turnzero check` and `turnzero deploy` for an existing application, and take library packages. | It does not sign your AI assistant's MCP connection in. Creating the application and submitting its manifest still need MCP; [prepare an unattended deploy](/cloud/guides/deploy-with-nobody-at-the-keyboard/#what-this-computer-s-token-does-alone) describes the setup. | | A [minted token](/cloud/guides/mint-a-token/) kept for an unattended job | Use the actions allowed by its scope and grants, through a [token-connected MCP client](#connect-an-unattended-ai-coding-agent-with-a-token) or commands that accept `TURNZERO_CLOUD_MINTED_TOKEN`. | A token for one application cannot create another application. No minted token can mint another token. Configuring the MCP connection does not also supply the token to a command. | | Your application's platform credential, `TURNZERO_CLOUD_APP_TOKEN` | Let the backend use its own environment's services, such as storage, logs and outbound requests. Turn Zero supplies it to the deployed backend. | It cannot connect an AI assistant or authorize a deploy command. It is separate from your account's sign-in and your application's users' sessions. | [`turnzero login --device`](/cloud/concepts/how-the-turnzero-command-finds-its-credential/#sign-in-from-an-ai-coding-agent-without-a-terminal) authorizes the command on the requesting computer. It is different from device sign-in to the MCP connection, which has the limits in the third row. For credential lifetimes, revocation, application users' sessions and keys for external APIs, see [Sign-in, sessions, and tokens](/cloud/concepts/sign-in-sessions-and-tokens/). ## Claude Code To connect and build in one Claude Code session, run this in your own terminal before you start Claude Code. It adds the connection for every folder on this computer: ```bash claude mcp add --transport http --scope user turnzero https://turnzero.ai/mcp ``` On Windows, if PowerShell says `claude` is not recognized, the native installer's folder may be missing from `PATH`. If `%USERPROFILE%\.local\bin\claude.exe` exists, add `%USERPROFILE%\.local\bin` to your user `Path` as a new entry, keeping the existing entries. Reopen the terminal; if it is inside an editor, restart the editor too. Run `claude --version`, then retry the connection command above. If the file is missing or the command still fails, follow [Claude Code's PATH troubleshooting](https://code.claude.com/docs/en/troubleshoot-install#verify-your-path). Start Claude Code. When it needs a sign-in, its notice tells you to run `/mcp`. Type `/mcp`, choose `turnzero`, and complete the browser sign-in. You can build in that same session. If your AI runs the add command from a session instead, start a new Claude Code session before signing in. The session where your AI ran the command does not pick up the tools. In the Claude desktop app's Code tab, `/mcp` opens the app's connector settings, which do not list a server added with `claude mcp add`. Sign in from a terminal instead: run `claude`, type `/mcp`, choose `turnzero`, and complete the browser sign-in. Or add it by hand with [the connector steps below](#claude-s-chat-and-claude-code-on-the-web). A new desktop Code tab session can reuse the terminal connection. If you choose the custom connector instead, remove the terminal entry with `claude mcp remove turnzero` first. In the Claude desktop app's Code tab, a connector can appear under its ID rather than its name. Its instructions identify the Turn Zero connection. ## Codex Run this in a terminal: ```text codex mcp add turnzero --url https://turnzero.ai/mcp ``` It opens your browser to sign in. If it doesn't, run `codex mcp login turnzero`. Then start a new chat. If the desktop app or editor shares your Codex CLI configuration, reuse `turnzero`. If you already connected the ChatGPT plugin and it appears signed in on desktop, reuse that connection. If you also use the desktop app and it has neither connection, add the server there as follows. 1. Open **Settings**, choose **MCP servers**, then **Add server**. 2. Enter `turnzero-hosting` as the name and select **Streamable HTTP** as the type. 3. Enter `https://tzcloud.turnzero.ai/mcp` as the server URL. Leave the token and header fields empty. Save the server, then choose **Restart**. 4. If prompted to sign in with OAuth, choose **Authenticate** and finish signing in through your browser. Start a new chat, then [check the connection](#check-the-connection). ## Claude's chat and Claude Code on the web Follow these steps yourself. Your AI checks the connection after you finish signing in. 1. On claude.ai, open **Settings** → **Customize** → **Add** → **Add custom connector**. In the Claude desktop app, open **Settings** → **Customize** → **Connectors**, then choose **Add** → **Add custom connector**. 2. Enter the name and URL below. On claude.ai, the URL field is **MCP Server URL**. The desktop app labels it **MCP server URL**. Name: ```text turnzero-hosting ``` URL: ```text https://tzcloud.turnzero.ai/mcp ``` Choose **Continue**. 3. Keep **Sign in now**, choose **Register automatically** under **OAuth client**, and leave **Request headers** empty. 4. Choose **Add**, sign in on the Turn Zero page that opens, and choose **Allow access**. If you recently signed in, the sign-in page may be skipped; choose **Allow access** if the access page appears. 5. In your chat, open **+** → **Connectors** and check that **turnzero-hosting** is on. On claude.ai, keep the same conversation. Then ask your AI to check the connection. If Claude says this connector already exists, Turn Zero Cloud is already added to your account, so you don't need to add it again. Go to step 5 and check that **turnzero-hosting** is on. On a Team or Enterprise plan, an owner adds the connector under **Organization settings** → **Connectors**, and each member chooses **Connect**. Claude's Free plan allows one custom connector, as [Anthropic's instructions](https://support.claude.com/en/articles/11175166-get-started-with-custom-connectors-using-remote-mcp) state. ## ChatGPT and Codex in ChatGPT's cloud Use these steps for Turn Zero Cloud. For tzTrack or tzMesh, follow [Set up Turn Zero Tools for AI](https://turnzero.ai/tztools/getting-started/set-up/#chatgpt-or-codex-on-the-web). Your ChatGPT account must allow adding and using a custom MCP server. In a company workspace, your administrator controls the permissions that may be required. 1. Open **Plugins** in ChatGPT. Select **+**, then **Add custom MCP server**. 2. Enter `turnzero-hosting` as the name and `https://tzcloud.turnzero.ai/mcp` as the URL. Keep **OAuth**. 3. Check the address in the warning, choose **I understand and want to continue**, and choose **Create as a plugin**. 4. If **Install** is offered, choose it. Then choose **Connect turnzero-hosting**, sign in, and choose **Allow access**. 5. In ChatGPT, switch to **Work** and start a new chat. Type `@`, select **turnzero-hosting**, and ask it to use Turn Zero Cloud. After connecting, use Turn Zero Cloud’s tools from a new chat in **Work** with **turnzero-hosting** selected through `@`. If the tools do not appear, start another new chat in **Work**, select **turnzero-hosting** again and ask your AI assistant to check the connection. If the plugin appears signed in in your ChatGPT desktop app, reuse it there. If you need to add a local MCP server, follow [Codex](#codex). If **Add custom MCP server** is missing or blocked, ask your workspace administrator whether you can add Turn Zero. You can instead use [Claude Code](#claude-code) or [Codex](#codex) on your computer, where your company's policy permits it. ## Signing in You make the first sign-in yourself, in a browser: your AI assistant can't do it for you. Sign in with GitHub, Google, or a code sent to your email. If you registered a passkey, you can use it where the sign-in page offers it. If you signed in to Turn Zero in the same browser in the last 8 hours, you may not be asked again. The page that follows names the tool asking for access, such as claude.ai, and your account. Choose **Allow access** only if you just started that connection. Once you are signed in, ask your AI assistant to file feedback about anything that went wrong before sign-in. Connecting doesn't let the `turnzero` command deploy from your computer; that is a separate step, [Authorize this computer for deploys](#authorize-this-computer-for-deploys). ## Check the connection Ask your AI assistant: *"Check my Turn Zero Cloud connection."* It should call `start`, give your account’s standing, such as active, and check that tzCloud tools are available. A working `start` alone does not establish that the connection provides hosting tools. ## Try it After connecting and signing in, paste this prompt into your AI assistant. It creates and deploys a small app in your account. > Create a small hello-world web app and deploy it. ## If something goes wrong | What you see | What to do | | --- | --- | | Your AI coding agent refuses to run the `mcp add` command, for example in Claude Code's auto mode | Run the command for your tool from the steps above in your own terminal, then [sign in](#signing-in). Don't rewrite the refused command or change the AI coding agent's permissions. | | Your AI assistant lists Turn Zero's tools, but a call returns "Unknown tool" | The AI assistant has a stale tool list. [Refresh the connection](#refresh-or-remove-the-connection) or restart the AI assistant, then [check the connection](#check-the-connection) again. | | A call returns "No such tool available" | Your AI assistant may add the connection's name to each tool's name. In Claude Code, `read_documentation` is `mcp__turnzero__read_documentation`. Use the name your tool lists. | | The browser sign-in finishes but the tool still shows disconnected | Retry its sign-in once, using the address in your tool's setup steps above. Don't paste tokens or browser addresses into its settings. | | Claude says the connector already exists | Turn Zero Cloud is already added. Don't add it again: in a chat, open **+** → **Connectors** and check that **turnzero-hosting** is on. | | The ChatGPT plugin already exists | Open **Plugins** and find **turnzero-hosting** in your personal plugins or the workspace where you created it. Install it if needed. Then follow [step 4 of the ChatGPT setup](#chatgpt-and-codex-in-chatgpt-s-cloud). | | A connector added with a setting other than **Sign in now** won't connect | That setting can't be changed. Remove the connector and add it again. | | `invalid_client`, or a page titled Connect your tool again | Your tool's registration expired. Remove the connection and add it again. | | Your AI assistant cannot file feedback before sign-in | After [signing in](#signing-in), follow the feedback step above. | | Codex asks which client registration to use, or its sign-in fails while registering the client | Run `codex mcp login turnzero --oauth-client-registration dcr`. | [Setup troubleshooting](/cloud/troubleshooting/setup/) covers more problems, and [Refusals](/cloud/reference/refusals/) lists every refusal by name. ## Refresh or remove the connection To reload the available tools: - On claude.ai, open the connector's **…** menu and choose **Refresh tools list**. Keep the same conversation. After the refresh finishes, ask your AI to reload its tool list if it can and check the connection. - In Claude Code, type `/mcp`, or start a new session. - In ChatGPT on the web, open the plugin’s page in **Plugins**. If you can manage the plugin, refresh its connection there. Then open a new chat. - If you added the server directly in the ChatGPT desktop app, restart the app, then open a new chat. - In another AI assistant, start a new session or restart it. To end the connection without deleting your account or apps, choose **Disconnect** beside your AI assistant on the dashboard's **AI access** page ([Read and end connections](https://turnzero.ai/turnzero/guides/your-account/#4-read-and-end-connections)). Some AI assistants revoke their sign-in when you sign out. Turn Zero ends the connection if the assistant sends its refresh token or a valid, unexpired access token. Renewal stops. The storage, logging, and egress gateways can still use an earlier credential check for up to 30 seconds by default. If the store cannot answer, a gateway can use the earlier check for up to an hour from its last successful check by default. Removing only the assistant's stored copy leaves the connection live on Turn Zero. Disconnect ends it for any AI assistant. To remove the assistant's copy: - Claude Code: `claude mcp remove turnzero` - Codex: `codex mcp logout turnzero`, then `codex mcp remove turnzero`. Run both with the same Codex configuration you used to add the connection. If you set `CODEX_HOME` then, use that same value now. - Claude's chat: open **Connectors** as in [Claude's chat and Claude Code on the web](#claude-s-chat-and-claude-code-on-the-web), select the connector, open its **…** menu, and choose **Remove**. - ChatGPT: manage it on [ChatGPT's Plugins page](https://chatgpt.com/plugins). - For a server added directly in the ChatGPT desktop app, open **Settings**, then **MCP servers**, and remove that entry. If Codex reports no server named `turnzero`, check that configuration before trying again. If its logout cannot delete the stored sign-in from the keyring, choose **Disconnect** on the dashboard as above. This ends that connection at Turn Zero; its stored credentials no longer work. Then run `codex mcp remove turnzero` to remove its configuration entry. That does not prove the keyring copy was deleted. Other connections and separately minted tokens stay live. ## For your AI When you connect for the person, follow [Set up Turn Zero Cloud](/cloud/getting-started/set-up/). ### Before you start Check the connection before building or deploying an application. If a listed tool returns "Unknown tool" on claude.ai, ask the person to choose **Refresh tools list** in the connector’s menu. Wait for confirmation. Then reload your tool list if your client supports it and check the connection in the same chat. - With permission to change the connection, you can run the CLI add command for Claude Code or Codex if your tools allow it. The person completes the browser sign-in. In Claude Code, ask them to start a new session, type `/mcp` there and choose `turnzero`. In Codex, ask them to finish the sign-in opened by `codex mcp add`, or run `codex mcp login turnzero` if no browser opened. In claude.ai, give the person the connection steps above; you cannot perform them from the chat. Do not start a login where the person cannot see it. - If your permissions refuse the `mcp add` command, give the person the exact command for their tool from the steps above to run in their own terminal, then ask them to sign in. Never rewrite the command or suggest changing permissions. If a Turn Zero tool you can see returns "Unknown tool", your tool list is stale: ask the person to refresh the connection or to restart you, then check the connection again. - A request before sign-in returns status 401 and changes nothing. Ask the person to finish signing in, then retry. - Read [How an AI reads these docs](/cloud/concepts/reading-this-documentation-as-a-tool/) to read a page whole, one section at a time, or by search. - Without a shell, deploy with `deploy_files`, as [Deploy from a chat](/cloud/getting-started/build-an-app-from-a-chat/) describes. - Call `start` first. Report the account and its [standing](/cloud/concepts/glossary/#standing) when it succeeds. If it is refused, call `read_account` and report those details from that answer instead. An application-scoped token cannot call `start`; `token_scope_refused` does not mean it needs a new sign-in. Report the refusal if neither read succeeds. - When you need to find a tool, call `read_context` with `id: "tools"` and `limit: 16000`. The index starts with the path to the Turn Zero Cloud tool reference in `read_documentation`. It then lists each Cloud tool's name and the first sentence of its description, shortening long sentences at a word boundary. Its last line names the entry for each other product's tools, such as `id: "tools:tztrack"`. Read the `overview` with `read_context` when a task needs a platform rule you do not know. - When `start` succeeds, its `credential` field identifies the connection's credential and says whether it may create and sign in test end users on production. - Use `start`'s `versions` to check which build served you. `server` and `tzcloud` give the full build commit, also returned as `serverInfo.version` by MCP `initialize`. `tztrack` and `tzmesh` give the versions those products reported in the server’s last MCP handshake with each one. Each of those two keys appears only if this connection lists that product's tools and the server has read its version. Quote the full build commit in a report so it can be matched to the report's `seen_in.version`. - Connecting does not write project files or require platform approval. Authorizing a computer stores its credential outside the project. - Use dynamic client registration where Codex offers the choice: `codex mcp login turnzero --oauth-client-registration dcr`. - For unattended runs, first establish a signed-in connection. Call `mint_token`, have the person run the returned `token claim` command into the run's secret store, and set the stored value as `TURNZERO_CLOUD_MINTED_TOKEN`. See [Mint a token](/cloud/guides/mint-a-token/). ### Authorize this computer for deploys The `turnzero deploy`, `library take`, and `scaffold` commands use a credential stored on the computer or supplied for the command. Choose how to deploy with [Ways to deploy to Turn Zero Cloud](/cloud/getting-started/ways-to-deploy/). With a shell, try `npx --no-update-notifier -y turnzero@latest --version` once before deciding npx cannot run here. Use `npx.cmd` on Windows. Do not skip this check on a session note or a guess about the network. No global installation is needed. If the command cannot reach `turnzero.ai` or the npm registry, explain that the tool's setting for its shell's network access controls this. A change to that setting takes effect in a new chat. Ask the person before switching to deployment through `deploy_files`. Deployment with the command supports the scaffold's tests and a local run; `deploy_files` alone provides neither. If npx can't run here, use the installed command where `turnzero --version` responds. Otherwise, ask the person before using `deploy_files` within its limits. If no person is there to answer, use `deploy_files` and say in your report that you did and why. Use the [upload route](/cloud/getting-started/ways-to-deploy/#upload-a-zip-without-the-turnzero-command) past those limits. Install the command only if the person wants to keep it. Authorize this computer through your signed-in MCP connection: 1. Run `npx --no-update-notifier -y turnzero@latest authorize` with nothing sent to its standard input. On Windows, use `npx.cmd` in place of `npx`. 2. Call `mint_token` with the arguments that command prints. 3. Run its returned `command_npx`, or `command_npx_windows` on Windows, once, as given, on that same computer. It stores the computer's credential. 4. Tell the person the credential's label, its 30-day expiry, and [how to revoke it](/cloud/concepts/how-the-turnzero-command-finds-its-credential/#this-computer-s-token). On the same computer, `turnzero authorize` reuses an unexpired `turnzero login --device` request for the same platform address. If the device command is still waiting for that request, stop it before you finish with `authorize`. See [Sign in without a terminal](/cloud/concepts/how-the-turnzero-command-finds-its-credential/#sign-in-from-an-ai-coding-agent-without-a-terminal). `mint_token` returns npx and installed forms of `authorize --mint `. It adds `--origin` for another platform address, including Turn Zero's development platform. Both forms use the same credential file on this computer. The id names the pending token request and is not a credential. The earlier authorization command saved a random secret on this computer, called the verifier. The returned command uses that secret to complete the request once. It contains no code to copy or pipe. `authorize` refuses a code piped into it. If your permissions block npx, the installed command, installation, `mint_token`, or its returned command, follow the available routes in [Ways to deploy](/cloud/getting-started/ways-to-deploy/) and tell the person which you take and why. If authorization is refused and no available deploy route works, ask the person to run `turnzero login` in their own terminal. Give the [browser-login steps below](#browser-login-fallback), one step at a time. For a refused deploy or upload command, give the person that exact command only after the available routes cannot complete the deploy. Never rewrite a refused line or suggest changing permissions. Claude Code's auto mode blocked an older command, which piped a code; this command holds none. A connection using a minted token cannot call `mint_token`; supply `TURNZERO_CLOUD_MINTED_TOKEN` for one CLI command at a time instead ([Deploying unattended](/cloud/concepts/turnzero-command/#deploying-unattended)). After authorization, run the `deploy_command` action's returned `command_npx`, or `command_npx_windows` on Windows, once as given. If npx cannot work, use its installed form where `turnzero --version` responds, following Ways to deploy. #### Browser-login fallback Give the person these steps to run in their own terminal: Run `turnzero login` if the CLI is already installed. Otherwise, install it first with the commands below: ```text npm install -g turnzero turnzero login ``` On Windows, use `turnzero.cmd` instead of `turnzero` ([Windows PowerShell](/cloud/getting-started/prerequisites/#windows-powershell)). 1. In the browser that opens, sign in if asked. If you prefer another browser, copy the address printed by `turnzero login` into it. 2. Check the computer name and account, then choose **Approve**. If the account is wrong, choose **Sign out**, run `turnzero login` again, and sign in to the correct account. Use an emailed code if Google or GitHub keeps signing you back into the wrong account. 3. Tell your AI assistant when the terminal prints `authorized:`. This output names the platform address, account, computer, and expiry. For a remote computer or one without a browser, have the person run `turnzero login --no-browser`. They can open the printed address on any computer, approve access, and paste the page's code into the terminal. If they opened a normal login link on another computer, stop that login and restart with `--no-browser`: the normal callback expects a browser on the computer running the command. If the browser cannot open or return its code, `turnzero login` waits for the code shown on the page. Use `turnzero whoami` to check which account the CLI uses. Authorization lasts 30 days; `turnzero login` renews it. This authorization covers the whole account; for a token limited to one application, follow [Mint a token](/cloud/guides/mint-a-token/), where the person runs `token claim` in their own terminal. Local application setup can also work without login: `turnzero provision --application ` with nothing piped prints an MCP call. The returned command writes local settings without authorizing the CLI. See [Write the environment file](/cloud/guides/run-your-application-on-your-machine/#1-write-the-environment-file). ### Connect an unattended AI coding agent with a token An unattended MCP client can use a [minted token](/cloud/guides/mint-a-token/) instead of browser sign-in. Mint it from an existing signed-in connection and put the claimed value in the runner's secret store. Configure the client to send it as `Authorization: Bearer ` to `https://turnzero.ai/mcp`. A token connection lists tzCloud tools only. A program that needs tzTrack or tzMesh uses that product's own server with its own token. For Codex, make the stored value available as `TURNZERO_CLOUD_MINTED_TOKEN` in the environment that starts Codex. Add a separate connection with `codex mcp add turnzero-unattended --url https://turnzero.ai/mcp --bearer-token-env-var TURNZERO_CLOUD_MINTED_TOKEN`. The command stores the variable's name, not the token. Start a new chat and check the connection with `start`. If an application-scoped token gets `token_scope_refused`, call `read_account` instead; the token's existing limits still apply. See [OpenAI's MCP configuration reference](https://developers.openai.com/codex/mcp/) for other configuration options. The token limits which applications and actions the client can use. An application-scoped token cannot create another application, and a minted token cannot mint another token. A run that creates an application needs an account-scoped token; the token's grants must allow each action the run needs. [Deploy with nobody at the keyboard](/cloud/guides/deploy-with-nobody-at-the-keyboard/) covers the CLI credential and deployment steps. ### Refusals If connecting or signing in fails, the refusal's name gives the cause. The table below gives the common causes and remedies. The [refusals reference](/cloud/reference/refusals/) lists every platform refusal, and [Identities and passkeys](https://turnzero.ai/turnzero/guides/identities-and-passkeys/#refusals) covers passkey failures. On the MCP endpoint, a refusal appears in an OAuth challenge's `WWW-Authenticate` header or a response body. During sign-in, it can appear on the page or in the redirect back to the AI assistant. | Refusal | Status | Cause | Remedy | | --- | --- | --- | --- | | `authentication_required` | 401 | The connection presented no credential, or one that resolves to no account: expired, signed out. The detail says whether one was presented and names the scope to sign in again under, `tzcloud`. | In Claude Code, type `/mcp`, choose turnzero, and sign in. In Codex, run `codex mcp login turnzero`. This sign-in does not authorize the `turnzero` command; use the authorization steps above when your chosen deployment method needs it. | | `invalid_token` | 401 | The credential cannot sign in to this service, for example an expired or revoked access token. | Let your AI assistant renew or sign in again. Do not edit tokens by hand. | | `account_suspended` | 403 | Your account is suspended, so the sign-in also fails. | Ask platform staff to reinstate the account; nothing on your side clears it. | | `app_credential_not_admitted` | 401 | The credential is an application's platform credential, which cannot connect to the MCP server. | Connect under your own sign-in or a minted token. | | `transfer_grant_not_admitted` | 401 | The credential authorizes a file transfer only on the storage file routes. It cannot connect to the MCP server. | Connect under your own sign-in or a minted token. | | `secret_grant_not_admitted` | 401 | The credential authorizes only one secret write or setup for a local run. It cannot connect to the MCP server. That setup replaces the platform credential, and the database credential if the manifest declares a database. | Connect under your own sign-in or a minted token. | | `retired_host` | 421 | The configured URL uses a hostname the platform retired. The detail gives the current address. | Use the address in your tool's setup steps above. | | `context_changed` | 409 | The `stamp` sent by your AI assistant does not match the text it requested in parts. Turn Zero returns this value so you can tell whether all parts come from the same version of the text. The catalog or content changed while your AI assistant read it in parts, or the stamp came from another read, such as a page's stamp sent with `section`. | Ask your AI to restart the read at offset zero without a stamp. | | `sign_in_failed` | 400 | The provider sign-in could not be verified. | Start over from the AI assistant. | | `access_denied` | 302 | You declined at the identity provider, or chose **Cancel** on the page that asks you to allow an AI assistant. Your client receives `error=access_denied`. | Start the sign-in again, accept at the provider, and choose **Allow access**. | | `unrecognized_invitation` | 403 | No valid invitation for this address: none, one for another address, or one that is used, expired, or revoked. | Open the invitation URL issued to your address and sign in with a sign-in method that verifies that address. If it is used up, ask for a new one. | | `realm_creation_ceiling` | 403 | The platform's limit on new accounts is reached, so sign-ups are paused. The sign-in page says so instead of showing the refusal's name. | Try again later, or use an invitation: its link still creates an account while sign-ups are paused. | | `cloud_required` | 403 | The platform refused the call's Turn Zero Cloud access check. | Every account includes Turn Zero Cloud. Call `read_account` to confirm the account, then repeat the request. | | `address_held_by_another_account` | 409 | The address this sign-in method verified belongs to a different account; nothing is linked or merged. | Sign in with the sign-in method that account already uses. | | `signin_code_invalid` | 400 | The sign-in code is wrong, expired, replaced, or from another browser. The sixth wrong attempt ends the code. | Type the code from the latest message, in the browser that asked for it, or choose Request a new code. | | `signin_code_rate_limited` | 429 | Too many codes were sent to this address, or too many attempts failed within the hour, or the platform's sending limit was reached. | Wait for the hour to pass, or sign in with another method. | | `signin_rate_limited` | 429 | Too many emailed-code sign-ins started from your network. An IPv6 address counts as its whole /64 network. | Wait, then start the sign-in again. | | `email_domain_undeliverable` | 400 | An emailed-code start was for an address whose domain publishes no mail server, so no code could reach it. | Correct a typo in the address and start again. Where you entered no address, as when a code goes to the address an existing account uses, sign in with another method. | | `invalid_client` | 401 | The AI assistant's client registration is no longer on file, for example after a long time unused. In the browser, the sign-in shows a page titled Connect your tool again. | Remove this server's sign-in in your AI assistant and connect again; the AI assistant registers itself again. | | `invalid_grant` | 400 | The code or refresh token is unknown, expired, already used, or from a session that ended. A passkey offer ended by a sign out everywhere is also refused this way. | Sign in again through the host. To add a passkey, sign in again, open Settings → Account & security, and choose **Manage** in the **Passkeys** row. | ## Related - [Set up Turn Zero Cloud](/cloud/getting-started/set-up/): one prompt that connects your AI assistant and gives you the build prompt. - [Sign-in, sessions, and tokens](/cloud/concepts/sign-in-sessions-and-tokens/) - [Identities and passkeys](https://turnzero.ai/turnzero/guides/identities-and-passkeys/) - [Deploy with nobody at the keyboard](/cloud/guides/deploy-with-nobody-at-the-keyboard/) - [What your computer needs](/cloud/getting-started/prerequisites/) - Action reference: [start](/cloud/reference/actions/start/), [read_context](/cloud/reference/actions/read-context/), and [read_documentation](/cloud/reference/actions/read-documentation/) --- title: What your computer needs description: What your computer needs for Turn Zero Cloud. Connecting needs Claude Code or Codex and a browser; building on your machine also needs Node.js 24 and npm. slug: /getting-started/prerequisites order: 3 visibility: public redirects_from: [/getting-started/what-your-computer-needs] --- # What your computer needs To connect to Turn Zero Cloud, you need a supported AI client and a browser for the first sign-in. Your AI coding agent can check and install the software needed to build and deploy from your computer. You may need to approve changes or complete a step the tool cannot run. Chat clients can deploy small applications through `deploy_files` without installing the local build tools below. Before you start, read the [application and storage limits](/cloud/guides/plan-and-usage/#current-application-limits). The usual limit is 10 live applications, and [Size and usage](/cloud/guides/plan-and-usage/#1-choose-a-size) says when it does not apply. You can read the current limits without signing in. ## The list - **A supported AI client.** [Connect your AI assistant](/cloud/getting-started/connect-your-tool/) covers Claude Code, Codex, the Claude apps, and ChatGPT. - **Node.js 24 or later, for local builds and deploys.** Hosted server applications run on Node.js 24. The [turnzero command](/cloud/concepts/turnzero-command/) also requires Node.js 24 or later. - **npm, for local builds and deploys.** It ships with Node.js and installs the application's dependencies. - **The turnzero command, for local deploys.** Your AI coding agent first runs it through npx, without a global installation. [Install the turnzero command](#install-the-turnzero-command) explains the optional global install. A local deploy needs a credential supplied to the command or stored on this computer. Your AI coding agent follows [Authorize this computer for deploys](/cloud/getting-started/connect-your-tool/#authorize-this-computer-for-deploys). To authorize this computer yourself, run [`turnzero login`](/cloud/getting-started/connect-your-tool/#browser-login-fallback) in your own terminal, or [`turnzero login --device`](/cloud/concepts/how-the-turnzero-command-finds-its-credential/#sign-in-from-an-ai-coding-agent-without-a-terminal) and approve its link on any device. Cloud itself requires no SDK, compiler, signing certificate, or separate console. Deploying requires neither Git nor a Git repository. **For the AI coding agent:** The rest of this page addresses you directly. Check what is already installed before making changes. If a step needs the person, tell them what to do and wait for their response. Do not assume Git is installed. Before using a Git command such as `git diff`, check that `git` is available. The turnzero command can read a repository's commit without running Git; see [What it reads](/cloud/concepts/what-the-turnzero-command-reads-and-prints/#what-it-reads). ### Before giving the person a command If the person will run the commands, give them this checklist before their first command: - Check `node --version`: it must show 24 or later. If Node.js is missing or older, follow [Check your Node.js version](#check-your-node-js-version), including its Windows installer or archive route. - On Windows, use `npx.cmd` and `npm.cmd` with the same arguments. PowerShell's default execution policy blocks the script forms; do not change that policy. - If computer authorization needs browser sign-in, explain the prompt first. The person signs in and approves access in their browser. ## Check your Node.js version The commands below use bash or zsh on macOS and Linux. On Windows, read [Windows PowerShell](#windows-powershell) first. Check the Node.js and npm versions. ```bash node --version npm --version ``` The person decides whether to install or update Node.js on their computer; ask before doing either. The Node.js version must be `v24` or later. If Node.js or npm is missing, or Node.js is too old, install Node.js 24 or later and run both checks again. Use the existing installation method to update Node.js. For Homebrew, run `brew install node@24` and follow its instructions to put that version first on `PATH`. Do not run `npm install -g node`; it can conflict with the existing installation ([npm install -g node ends with EEXIST](/cloud/troubleshooting/setup/#npm-install-g-node-ends-with-eexist)). For nvm or fnm, load the manager first if the shell has skipped its startup files. In Bash or Zsh, load nvm with `. "$NVM_DIR/nvm.sh"`, where `NVM_DIR` points to the nvm installation. In Bash, load fnm with `eval "$(fnm env --shell bash)"`. In Zsh, use `eval "$(fnm env --shell zsh)"`. List installed versions with `nvm ls` or `fnm list`. If version 24 is already installed, select it with `nvm use 24` or `fnm use 24`. For a later installed version, use its version number in the same command. These commands select an installed version for that shell. If no suitable version is installed, ask the person before installing version 24 through the manager. If your AI coding agent starts a fresh shell for each call, load the manager, select the version, check `node --version` and `npm --version`, and run the returned npx line in one shell call. For a new installation, use the installer from nodejs.org or a Node.js version manager. If the machine cannot run an installer, use the Node.js 24 archive from nodejs.org: `.tar.gz` for macOS or Linux, or `.zip` for Windows. Check its SHA-256 against the accompanying `SHASUMS256.txt`, using `shasum -a 256 ` on macOS, `sha256sum ` on Linux, or `Get-FileHash ` on Windows. Unpack the archive into the person's home folder. It creates a versioned folder, such as `node-v24.11.0-darwin-arm64`. Add its `bin` folder to `PATH`; on Windows, add the unpacked folder itself. Make the change persistent in the shell profile on macOS or Linux, or in the user's environment variables on Windows. Start a new shell session and run both checks again. Once `node --version` shows 24 or later in the same shell, run the returned npx line unchanged. Do not wrap it in another npx command to select Node.js ([npm EUSAGE](/cloud/troubleshooting/setup/#a-nested-npx-command-fails-with-npm-eusage)). ## Install the turnzero command For a local deploy, first run `command_npx` from the `tzcloud_deploy_command` response. On Windows, run `command_npx_windows` from that response. This needs Node.js and npm, but no global turnzero installation. If npx can't run here, use the installed command when `turnzero --version` responds. Otherwise, ask the person before using `deploy_files` within its limits. If no person is there to answer, use `deploy_files` and say in your report that you did and why. Use the [upload route](/cloud/getting-started/ways-to-deploy/#upload-a-zip-without-the-turnzero-command) past those limits. Install the command only if the person wants to keep it. To install globally, run `npm install -g turnzero`. If that command can't run here, try another available deployment route before asking the person for a step. The installed version stays fixed until another install. On macOS and Linux, a global install can fail with `EACCES` if npm's global folder belongs to the system. Do not use `sudo`. Configure a global folder under the person's home directory: 1. Run `npm config set prefix ~/.npm-global`. 2. Add `~/.npm-global/bin` to `PATH` in the person's shell profile. 3. Start a new shell session and run the install again. A Node.js version manager also avoids this permissions problem by using a folder owned by the user. To write a command without a global installation, use `npx --no-update-notifier -y turnzero@latest` in place of `turnzero`, or `npx.cmd` on Windows. AI coding agents use the returned npx form first. [Ways to deploy to Turn Zero Cloud](/cloud/getting-started/ways-to-deploy/) explains what to do if it cannot run. npm may print nothing for several seconds while it downloads the package. The command's first output line names its version. ## Windows PowerShell On Windows, prefer PowerShell 7 for its HTTP and UTF-8 support. Run the Windows form the tool returns, such as `command_npx_windows`. If you build the deployment ZIP yourself, follow [Build and upload the artifact](/cloud/getting-started/deploy-an-application/#3-build-and-upload-the-artifact). Install PowerShell 7 with winget, included in current Windows 10 and Windows 11. ```text winget install --id Microsoft.PowerShell --source winget ``` Run subsequent commands in PowerShell 7 (`pwsh`) instead of Windows PowerShell. If using Windows PowerShell 5.1, apply these five adjustments to the commands on these pages: - **npm and the turnzero command.** In Windows PowerShell, the default execution policy, a machine setting, blocks scripts. In it, `npm` and the installed `turnzero` are scripts. Run `npm.cmd` with the same arguments, and `turnzero.cmd` in place of `turnzero`. Returned commands have Windows forms using `turnzero.cmd` or `npx.cmd`. For a command that no tool call returns, such as `turnzero hash` or an unattended `turnzero deploy`, write `turnzero.cmd` in place of `turnzero`. For npx, write `npx.cmd` in place of `npx`. - **A script you write.** The same policy blocks a `.ps1` file you write. This is the computer's policy; the platform ships no PowerShell script. Run it for one process with `powershell -NoProfile -ExecutionPolicy Bypass -File

Notes

    ``` The script calls the backend on the same address. So the browser sends the user's sign-in cookie with each request, and you need no cross-origin (CORS) setting. This script reads `GET /notes`, the route that [Build a database-backed service](/cloud/getting-started/build-a-database-backed-service/) adds. ```js // client/app.js fetch('/notes') .then((response) => response.json()) .then((notes) => { const list = document.getElementById('notes'); for (const note of notes) { const item = document.createElement('li'); item.textContent = note.title; list.append(item); } }); ``` A web client is optional. An application without one, such as the backend of a mobile app, ships no `client/` folder. Requests that the platform handles itself, such as a matching manifest redirect, stop at the router. The remaining requests reach the application's own routes. [Build a mobile app's backend](/cloud/getting-started/build-a-mobile-app-backend/) walks through that shape. ### 2. Know what the platform serves and what reaches your routes The [serving router](/cloud/concepts/glossary/#serving-router) checks for a matching [manifest redirect](#redirect-an-exact-path) before it serves a client file or calls your application. A `GET` for a client file has no per-request charge and never wakes your application. That applies when the router serves the file. If the file store fails on a server app, the request can reach and wake the app. With no matching rule, a `GET` of `/` or `/index.html` returns `client/index.html`, and `/app.js` and `/styles.css` return the shell's script and stylesheet. On a server application, when no manifest redirect matches the request, these requests reach your application: - every `HEAD` and `POST`, and every other method, even on a client file's path; - a path that names no client file, such as `/notes` or a single-page application's own route `/notes/7`; - a path holding `%`, since the router matches the path exactly as the browser sends it and never decodes it; - a request the platform's file store does not respond to in time, as step 5 explains. The file store is where the deploy keeps your client files. Only the requests listed above reach your deployed server. The router serves published files under `client/` on `GET`, so you do not need `express.static` to serve those files. For a serverless version with no matching manifest redirect, the router responds to both `GET` and `HEAD` for client files. If no client file matches, requests at or beneath a function's path go to that function on any method. See [Publish a static site](/cloud/guides/publish-a-static-site/) for page and 404 handling, and [Deploy functions](/cloud/guides/deploy-functions/) for function paths. For a server ZIP declaring at most 128 MiB in total, the image includes `client/`. Above 128 MiB, the image omits `client/`, but the router serves the published files as usual. Non-GET requests (including `HEAD`), paths containing `%`, and requests the file store does not respond to in time can reach your server. Handle them without reading `client/` from disk. A server that reads a missing template or build manifest can fail to start or return HTTP 500. If the deploy skips a client file because of its name, the router cannot serve it. Above 128 MiB of declared ZIP data, your server also loses the copy under `client/`. Check the skipped names in `client_notice`. Deploy smoke checks request each path directly from the new version of your server. Above that same limit, a check that relies on a file under `client/` fails unless your server can serve that path without the file. Choose a path your server handles itself. With `turnzero` 0.35.0 or later and a numeric port, the command also serves client files locally. Other local runs need your server to serve them (step 6). If a page should load at a path of its own, such as `/notes/7`, your server must return the fallback page itself. If your server reads that page from disk, include a copy outside `client/`. For a server application, the router provides no fallback page and does not automatically serve a folder's `index.html`. ### 3. Keep names and sizes within the limits The deploy checks each file name below `client/` before it writes anything. Each part of a file name between slashes may use only ASCII letters, digits, and the characters `-`, `_`, `.`, `~`, and `@`. No part may start or end with a dot. A name such as `logo@2x.png` is allowed. A name may hold up to 32 parts and 512 characters. Its first part may not be `__account` or `__router`, the platform's own folders, in any letter case. The deploy skips any other name, such as `.DS_Store`, `.env`, a name with a space, or a name with an accented letter. The platform never serves a skipped file. A version's client files have limits. A zip past any limit is refused 400 `artifact_layout_invalid` before a version is added, and the refusal names the limit: | Limit | Value | | --- | --- | | Files served | 2,000 | | One file | 25 MiB | | All files together | 250 MiB | The finished ZIP must fit within the 32 MiB upload limit, even with 250 MiB of client files. Images, video and other compressed files may shrink very little. Versions of `turnzero` with the earlier 50 MiB limit refuse larger client folders before upload. Each environment keeps client files for three distinct deployed versions, including the serving version. If cleanup deletes a version’s client files while its build is still kept, a rollback to it returns 409 `version_client_pruned`. [Manage versions and environments](/cloud/guides/manage-versions-and-environments/) explains how to choose a version for rollback. Keep long audio or video in a [storage area](/cloud/guides/store-files/) instead. A browser fetches it from there through a download grant. If `client/` holds a file beyond the shell, or a name the deploy skipped, the deploy's response includes `client_notice`. It counts the files the router will serve, names up to twenty beyond the shell, and names up to twenty skipped files, then counts the rest. It is a notice only and refuses nothing. Your AI assistant reads it after each deploy. To keep a backend route's per-file access check, leave its files outside `client/`. ### 4. Know the headers, the revalidation, and the compressed forms On a deployed copy, each client file is returned with these headers: - The file's type, `Content-Type`, from the platform's table of file extensions, such as `text/javascript` for `.js` and `.mjs`, `font/woff2` for `.woff2`, and `image/webp` for `.webp`. A text or JSON type carries `; charset=utf-8`. An extension the table does not name gets `application/octet-stream`. - The header `X-Content-Type-Options: nosniff`, so a browser uses that type and never guesses another. - `Cache-Control: no-cache` by default. The browser asks again before reusing the file. - The file's tag, `ETag`, contains the SHA-256 hash of the bytes the router sends, in quotes. The router serves matching client files before it calls your application. For a custom header, use an application route with no matching file in `client/`. Use a [manifest rule](#redirect-an-exact-path) for a redirect from one exact path to another on the same hostname. For redirects that match a pattern or go to another hostname, use an application route with no matching file in `client/`. A browser that asks again sends that tag in its `If-None-Match` header. If the file has not changed, the router returns 304 with no body, so the file is not sent again. An unchanged served form keeps its tag across deploys. A browser that sends that form's tag can reuse its copy after a 304 response. The deploy writes a gzip copy for eligible files of at least 1 KiB when gzip makes them a tenth smaller or more. Eligible extensions are `.html`, `.css`, `.js`, `.mjs`, `.json`, `.map`, `.svg`, `.txt`, `.md`, `.xml`, `.webmanifest`, and `.wasm`. If a copy exists and the request’s `Accept-Encoding` header accepts gzip, the router serves it with `Content-Encoding: gzip` and its own tag. When a file has a gzip copy, either form includes `Vary: Accept-Encoding`. Your server handles compression for the responses it returns. The router passes the browser's `Accept-Encoding` header to your server. The platform sets no content security policy on a client file. If the page needs one, set it in `client/index.html`. #### Cache one public folder for a year In the manifest, set `immutable_client_folder` to one folder below `client/`, such as `assets` or `static/build`. Give its path without a slash at either end. Use a path that the client-file rules above would allow for a file inside the folder. The first segment cannot be `__account` or `__router`, regardless of case. `check_manifest` and `submit_manifest` return `manifest_invalid` at this member for an invalid path or an `invited` or `workforce` audience. With a `public` audience, files served from that folder carry `Cache-Control: public, max-age=31536000, immutable`. Files outside the folder, files named `index.html` at any depth, and responses that set a session cookie keep `no-cache`. After you restrict the audience to `invited` or `workforce`, all client file responses use `no-cache`. This applies even if the serving version was published while the audience was `public`. The next deploy records the folder with the version it publishes. A promote carries the folder recorded with that version. A rollback to a version published without the member uses `no-cache`. Give each file a new name when its content changes. A bundler can add a content hash to each name. Keep page files outside this folder. A browser can keep a copy for up to a year, even if you later restrict the audience. On a custom domain declared with `proxied_by`, your own proxy can also keep a copy for the year. After deploying, request a published file other than `index.html` from the folder and a published file outside it. Confirm that both responses return HTTP 200. Check that `Cache-Control` is `public, max-age=31536000, immutable` for the file inside the folder and `no-cache` for the file outside it. #### Redirect an exact path Add `redirects` to `manifest.json` when an old path should send visitors to a new one on the same hostname. A manifest can list up to 200 rules. Each rule has a `from` path, a `to` path and a `status` of `301` (permanent) or `302` (temporary). This example sends visitors from `/old-pricing` to `/pricing`. ```json { "redirects": [ { "from": "/old-pricing", "to": "/pricing", "status": 301 } ] } ``` Use paths up to 512 characters that start with `/`. After the initial slash, use ASCII letters, digits, `-._~!$&'()*+,;=:@`, `/`, or `%` followed by two hexadecimal digits. Leave out query strings, fragments, backslashes, `.` and `..` segments, and escaped dots such as `%2e` or `%2E`. Give every rule a different `from`. The router matches that path character for character, so `/old`, `/old/` and `/Old` are three different paths. The platform reserves `/__account/` and `/__router/` paths as sources. Start `to` with a single slash. It may point to a platform page such as `/__account/signin`. Choose a destination that no rule uses as its `from`, including its own. On a static site, don't redirect a folder's path with its trailing slash to the same path without it, because the platform adds the slash back and creates a loop. Run `check_manifest`, then `submit_manifest` once the manifest passes. Both refuse an invalid rule with `400` and `manifest_invalid` and name its field in the manifest. Deploy the version, then request `/old-pricing?ref=email` without following redirects. The response has status `301`, `Location: /pricing?ref=email` and `Cache-Control: no-cache`. Check on the deployed hostname. `turnzero run` skips manifest redirect rules. A rule redirects a matching `GET` or `HEAD` before the router serves a client file, calls a function or sends the request to your server. Other methods and WebSocket upgrades follow their usual routes. The sign-in gate for an `invited` or `workforce` audience still runs first, except on paths listed in `session_free_paths`. Keep redirect sources clear of health and smoke paths if visitors need those paths to reach the app. The deploy checks still reach the app directly. A new or changed rule starts serving in an environment when you deploy the version there. Each version keeps the rules it was deployed with. A promote or rollback serves the rules of the version it puts live. A redirect response adds no data transfer, backend actions or use of the per-address request limit. If the application is over a traffic limit, the router returns `429` with `usage_over_quota` for the path, as it does for a client file. ### 5. Know what a client file counts, and who may read it When the router sends a client file, the bytes in the response body count as data transfer. Your account pays for them from its balance at the `data-transfer` rate. For a server app, the main page (`client/index.html`), script (`client/app.js`), and stylesheet (`client/styles.css`) are exempt. For a serverless app, those files count too. A file the router serves uses no backend actions and counts toward none of the [limits per address](/cloud/concepts/egress-firewall-and-request-limits/). A 304 response sends no file bytes. Every application pauses when the account uses its available balance. The pause ends when the account has Free Allowance available again or credit it can use ([Size and usage](/cloud/guides/plan-and-usage/)). Every request on either hostname is refused 429 `account_paused`, including the shell files and realm paths. A browser asking for HTML gets the platform's pause page; any other caller gets the JSON refusal. Each carries `Retry-After`. For a server application, if a read from the platform's file store fails, the router remembers that failed read for 30 seconds. In that time, a request for a file beyond the shell reaches your application as an ordinary request. It counts toward the per-address limits. If the router cannot read the version's file index, it also skips manifest redirect rules during the hold. Those requests follow the server's usual routing. If the store cannot return a serverless version's file index or a listed file, the router returns 502 `upstream_failed`. Under an `invited` or `workforce` audience, the router applies the sign-in check to client files, including the page's shell. The router sends a signed-out page visit to the sign-in page. Paths listed in `session_free_paths` can pass the audience check without a session ([The manifest](/cloud/concepts/the-manifest/#the-audience-kinds)). The router serves an admitted file without calling the application's routes. ### 6. Serve the files yourself in a local run With `turnzero` 0.35.0 or later, start `turnzero run --port 3000` in the application's folder. Where it holds `client/`, the command serves each client file at its own path, ahead of your routes. It gives your application a free port as `PORT`. Open the command's printed address. Files are read on each request, so an edit appears on the next load. Names match in their letter case on every disk. A name the deploy's zip leaves out, or a path containing a link, falls through to your application. `.deployignore` is not read, so a file it hides can still be served locally. `turnzero run` serves files locally with their content type, `nosniff`, and `Cache-Control: no-cache`, even when the manifest declares `immutable_client_folder`. It skips manifest redirect rules. Local responses omit `ETag` and gzip copies. If a file cannot be read, the command responds with 502 instead of passing the request to your app. Without `--sign-in`, the listener binds on all network interfaces. An application that binds only to loopback can therefore be reached through it from elsewhere. With `--sign-in`, it binds only to loopback; [Test a local run](/cloud/guides/test-sign-in-with-test-end-users/#7-test-a-local-run) describes browser sign-in. For an older command, no numeric port, or starting Node.js directly, keep static serving in your own server. The sample below serves `client/` while `APP_ENVIRONMENT` is `local`. On a deployed copy, this helper always returns `false`. If the router forwards a request during a file-store failure, your server handles it with its other routes. The sample returns 404. A test runs this sample over a client folder and checks a served file, a skipped name, and a path outside the folder. ```js // src/client_files_local.mjs: a local run alone. import { readFile } from 'node:fs/promises'; import { extname } from 'node:path'; const folder = new URL('../client/', import.meta.url); const types = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.woff2': 'font/woff2', }; const part = /^[A-Za-z0-9_~@-]([A-Za-z0-9._~@-]*[A-Za-z0-9_~@-])?$/; const reserved = ['__account', '__router']; export async function serveClientFile(req, res) { if (process.env.APP_ENVIRONMENT !== 'local' || req.method !== 'GET') return false; let path; try { path = new URL(req.url, 'http://localhost').pathname; } catch { return false; } const name = path === '/' ? 'index.html' : path.slice(1); const segments = name.split('/'); if (name.length > 512 || segments.length > 32) return false; if (reserved.includes(segments[0].toLowerCase())) return false; if (!segments.every((segment) => part.test(segment))) return false; try { const body = await readFile(new URL(name, folder)); res.writeHead(200, { 'content-type': types[extname(name).toLowerCase()] ?? 'application/octet-stream' }); res.end(body); return true; } catch { return false; } } ``` Your server calls it first, as the router would, and goes on to its own routes when it returns `false`: ```js // src/main.mjs import { createServer } from 'node:http'; import { serveClientFile } from './client_files_local.mjs'; createServer(async (req, res) => { if (await serveClientFile(req, res)) return; // Your routes, the health path among them. res.writeHead(404).end(); }).listen(process.env.PORT); ``` This local example checks file names. Keep only files you intend to serve in that folder. The example follows symbolic links in the folder and serves their targets, even files outside the folder. If a link points to something you did not intend to serve, remove the link itself. Leave the file or folder it points to in place. It does not apply `.deployignore`. ### 7. Serve a page from your own routes, and take a form post Your server can build a page itself, on a route of its own, with no file under `client/`. The router passes your response's status, `Content-Type`, and body to the browser unchanged. So a route can return `text/html` as well as JSON. Give such a page a path that names no client file. A `GET` for a client file's path is served from `client/` and does not reach your server (step 2). Where the application ships `client/index.html`, `/` is that file, so a page your server builds needs another path, such as `/guestbook`. A form with `method="post"` sends its fields in the body as `application/x-www-form-urlencoded`. The post reaches your server, since only a `GET` is served from `client/`. The router forwards a body up to its [request size limit](/cloud/concepts/egress-firewall-and-request-limits/#the-request-size-limit) and refuses a larger one 413 `request_too_large`. Your server reads the body and parses it with `URLSearchParams`. Set a smaller limit of your own, since a form's fields are short. Each page request and each post reaches your application. Each is subject to the [per-address limits](/cloud/concepts/egress-firewall-and-request-limits/#the-per-address-and-per-user-limits). After a post, respond `303` with a `Location` header. The browser then requests that address with `GET`, so a reload of the page does not send the form again. The router passes the `Location` header to the browser unchanged and does not follow it. A relative `Location`, such as `/guestbook`, is enough for a page on the same hostname. The browser resolves it against the address it posted to. So the same redirect works on the production hostname, on the development hostname, on your own domain, and in a local run. Build an absolute address from `APP_PUBLIC_HOST` where the address leaves the page, such as a link in an email or a return address you give another service. `APP_PUBLIC_HOST` holds the hostname without `https://`, so the address is `https://` followed by it. In a deployed copy, never build one from the request's `Host` header, which names the platform's internal address for the environment ([What the router sets on each request](/cloud/backend-packages/nodejs-runtime/#what-the-router-sets-on-each-request)). The router passes the request's `Cookie` header to your server and your `Set-Cookie` headers to the browser. It removes any `Domain` attribute, so each cookie belongs to the hostname that set it alone. Under an `invited` or `workforce` audience, a post without a signed-in session is refused 401 `authentication_required` before it reaches your server, unless its path is under a session-free prefix your manifest lists ([The manifest](/cloud/concepts/the-manifest/#the-audience-kinds)). Outside such a prefix, a page request without one goes to the sign-in page first. Escape every value a visitor sent before you write it into the page, as the sample's `escape` does. The text then shows as text and never runs as HTML. This server builds a guestbook page at `/guestbook` and takes its form post there. It keeps the entries in memory to stay short. A running copy's memory empties when the copy stops or restarts, and each copy has its own. So keep real entries in a [database](/cloud/getting-started/build-a-database-backed-service/). Its health path is `/health`. A test runs this sample as a server and checks the page, a form post and its redirect, an escaped entry, and a body past its limit. ```js // src/guestbook.mjs: a page the server builds at /guestbook, and the form that posts to it. import { createServer } from 'node:http'; const FORM_LIMIT = 16 * 1024; // A form's fields are short: read far less than the router forwards. const entries = []; // In memory to keep the sample short. const escape = (text) => text.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`); const page = () => ` Guestbook

    Guestbook

      ${entries.map((entry) => `
    • ${escape(entry)}
    • `).join('')}
    `; // The posted fields, or null for a body past FORM_LIMIT. The whole body is read either way. async function readForm(req) { const chunks = []; let size = 0; for await (const chunk of req) { size += chunk.length; if (size <= FORM_LIMIT) chunks.push(chunk); } return size > FORM_LIMIT ? null : new URLSearchParams(Buffer.concat(chunks).toString('utf8')); } const port = Number(process.env.PORT ?? 8080); createServer(async (req, res) => { // A target that does not parse as a URL names no route, so it gets a 404 below. let pathname = null; try { pathname = new URL(req.url, 'http://localhost').pathname; } catch {} if (req.method === 'GET' && pathname === '/health') return res.writeHead(200).end('ok'); if (pathname !== '/guestbook') return res.writeHead(404).end(); if (req.method === 'GET') return res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }).end(page()); if (req.method !== 'POST') return res.writeHead(405, { allow: 'GET, POST' }).end(); if (!String(req.headers['content-type']).startsWith('application/x-www-form-urlencoded')) return res.writeHead(415).end(); const form = await readForm(req); if (form === null) return res.writeHead(413).end(); const note = form.get('note')?.trim().slice(0, 200); if (note) entries.push(note); // 303: the browser requests /guestbook with GET, on the hostname it posted to. res.writeHead(303, { location: '/guestbook' }).end(); }).listen(port, () => console.log(`listening on ${port}`)); ``` ### 8. Deploy and check the page, a font, and a script Your AI assistant deploys the application as [Deploy from your computer](/cloud/getting-started/deploy-an-application/) describes, and reads `client_notice` in the response. Binary assets can go inline as base64, up to 512 KiB each, or as `stored` entries without that per-file cap. With no shell, ask your user to [upload assets you cannot read](/cloud/guides/store-files/#upload-a-file-from-the-application-s-page), then use stored entries. The `deploy_files` route still has its 4 MiB total and 200-entry limits. Beyond them, use the command returned by `tzcloud_deploy_command` or the ZIP upload route in [Ways to deploy](/cloud/getting-started/ways-to-deploy/). If your AI assistant has no shell, ask the person to deploy from a computer that supports the chosen route. Once the deploy ends in the state `deployed`, request three files on the environment's hostname with `GET`: ```sh curl -s -D - -o /dev/null https:/// curl -s -D - -o /dev/null https:///vendor/katex/fonts/KaTeX_Main-Regular.woff2 curl -s -D - -o /dev/null -H 'Accept-Encoding: gzip' https:///vendor/katex/katex.min.js ``` Check for 200, the file's type, `nosniff`, and an `ETag` on each response. Expect `Content-Encoding: gzip` for the script if this version has a compressed copy. Use `GET` on a path with no manifest redirect for these checks. On a server, `curl -I` sends `HEAD` to your application unless a manifest rule redirects it first. On a serverless version, the router responds to `HEAD` for a client file without calling a function. Under an `invited` or `workforce` audience, check in a signed-in browser instead. ## Expected result An admitted request for `/` returns the page. Accepted files under `client/` have their own paths, types, tags, and gzip copies where the deploy wrote them. Step 2 explains which requests reach the application. A page your server builds comes from its own route, and its form post ends in a `303` to a path on the same hostname. A file beyond the shell counts toward data transfer and never toward backend actions, except while the file store fails (step 5). ## Refusals See the [refusals reference](/cloud/reference/refusals/) for other platform errors. The deploy's own refusals are in [Deploy from your computer](/cloud/getting-started/deploy-an-application/#refusals). | Refusal | Status | Cause | Remedy | | --- | --- | --- | --- | | `artifact_layout_invalid` | 400 | The zip's client files pass a bound: more than 2,000 files, one file over 25 MiB, or more than 250 MiB together. The `detail` names the bound. | Ship fewer or smaller client files, keep long media in a storage area, and deploy again (step 3). | | `not_deployed` | 404 | The environment has no deployed version yet, so there is no page to serve. | Deploy to the environment, then request the page again. For production on an application with two environments, promote a version instead. | | `account_paused` | 429 | The account has used its balance. Every request is refused, including all client files and realm paths. A browser asking for HTML gets the pause page; other callers get JSON. Each response carries `Retry-After`. | Wait for Free Allowance to renew or for credit you can use. | ## Related - [Deploy from your computer](/cloud/getting-started/deploy-an-application/) builds the zip, uploads it, and deploys it. - [What the deploy zip holds](/cloud/concepts/what-the-deploy-zip-holds/) gives the zip's limits and the deploy's notices. - [Store files](/cloud/guides/store-files/) keeps files your users upload, and long audio or video, which the page fetches through a download grant. - [Size and usage](/cloud/guides/plan-and-usage/) reads the data transfer your client files count. - [Add sign-in to your app](/cloud/guides/add-sign-in-to-your-app/) lets the page's users sign in. - [Build a mobile app's backend](/cloud/getting-started/build-a-mobile-app-backend/) covers an application with no web client. - The [functions-sign-in example](/cloud/examples/functions-sign-in/) and [server-sign-in example](/cloud/examples/server-sign-in/) show the same web client with sign-in and private notes. The [server-ai-chat example](/cloud/examples/server-ai-chat/) shows a web client with sign-in and an AI conversation. --- title: Add a schedule description: Call an application handler on a timetable. Declare the schedule, deploy it, and verify that the handler ran. slug: /guides/add-a-scheduled-job order: 5 visibility: public redirects_from: [/guides/add-a-schedule] --- # Add a schedule Prompt: > Clear out the expired sign-up links every night, and show me how to tell whether it ran. Also works: - "Add a cron job." - "Send the daily summary every morning at six." - "Check every hour that the app still responds, and keep a record I can read." A schedule sends an HTTP request to your handler. Work that fits the request window can finish in the handler, and the schedule run records its result. On a server application, the handler can [start a separate job](/cloud/guides/run-a-job/#start-a-job-from-a-schedule-handler) for longer work and finish its request. Check the schedule run and the separate job run to see what happened. If an environment sleeps after 30 minutes without a request, a schedule that reaches it more often can keep it awake. An hourly schedule can wake a sleeping server for each run and leave it time to sleep between runs. The scheduled call counts as a request for the idle interval. After the handler finishes, the server can stay awake until the next idle stop. Other requests can keep it awake longer. Use `read_plan_quotas` to check the `free-idle-stop` interval for the server's size. Before choosing a schedule, ask where the work needs to run, what time it should run in the owner's time zone, and how long it takes. A Turn Zero Cloud schedule calls code in a hosted application. If the owner wants a personal reminder or the script needs files or tools on their computer, use a reminder app or a scheduler on that computer. Shared server compute charges use measured awake time, which can extend beyond the handler's run. [Size and usage](/cloud/guides/plan-and-usage/) explains where to read rates and charges. To send a weekly email to your users, [choose how to send it](/cloud/guides/send-email-from-your-application/) before writing the handler. Check whether occasional account notices fit the built-in email limits. Use your own mail provider for a newsletter or marketing mail. For an application with code of its own, new or deployed, [add the schedule to its manifest](#add-a-schedule-to-an-existing-application) and [choose a handler](#2-write-the-handler). A new application is created first, as [Deploy from your computer](/cloud/getting-started/deploy-an-application/#1-create-the-application) says. For a new service from the `server-scheduled-job` template, [start a new hourly heartbeat](#start-a-new-hourly-heartbeat). The [server-scheduled-job template](/cloud/concepts/turnzero-command/#the-server-scheduled-job-template) creates the service, heartbeat schedule, handler and tests. A heartbeat can log a line without saving state. Use `tzcloud_read_schedules` to see its recent runs. Your AI assistant declares the schedule, writes its handler, deploys it, and checks one manual run with `tzcloud_run_schedule`. The manual run checks the handler. If it starts a job, [check that job separately](/cloud/guides/run-a-job/#check-the-result). With one environment, your request for the schedule covers one [proving run of the handler on production](#4-confirm-it-runs). If the handler would start a job in production, ask the owner to approve that job start unless they already requested it. ## Production-only checklist Use this checklist for an app with only a production environment. If your app also has development, follow the two-environment instructions in [Deploy](#3-deploy). 1. [Declare the schedule](#1-declare-the-schedule), using the [hourly heartbeat recipe](#start-a-new-hourly-heartbeat) for a new service or the [existing-application steps](#add-a-schedule-to-an-existing-application) for code you already have. 2. [Write the handler](#2-write-the-handler) for the declared path. 3. [Deploy](#3-deploy) the application to production with the submitted declaration. 4. [Confirm it runs](#4-confirm-it-runs). A successful manual run shows the handler ran. `deployed: true` and a `next_due` time show the timetable is ready. To see a run started by the timetable, use the [completion checks](#expected-result) after its due time. ## What your AI does - Reads the `schedule` [skill](/cloud/concepts/glossary/#skill) (`read_context`, id `skill:schedule`) and follows it. - [Chooses a handler](#2-write-the-handler) and follows the [Schedule handler reference](/cloud/reference/schedule-handler/). - Asks what the schedule should run and when. On an application with two environments, asks before promoting. ## What you need - What the scheduled work does, and how often or at what time of day it runs. Times are in UTC, with a [one-minute minimum step](/cloud/concepts/how-the-plans-differ-technically/#schedules) for either size. - Whether the handler must remember anything from one run to the next, such as the last record it handled. ## Before your AI starts **For the AI assistant:** Check the following before starting. - A connected, signed-in AI assistant ([Connect your AI assistant](/cloud/getting-started/connect-your-tool/)). - Ask whether another host or service already runs this work. If it does, agree with the owner when the other schedule should stop before enabling this one. - For an application with code of its own, its identifier, from `tzcloud_create_application` for a new one or `tzcloud_list_applications` for one that already deploys, and its manifest ([Author the manifest](/cloud/guides/author-the-manifest/)). - Work that fits one run: one HTTP request that ends inside the [execution window](/cloud/concepts/glossary/#execution-window-and-grace-interval), 230 seconds by default. For longer work on a server application, have the handler [start a job](/cloud/guides/run-a-job/#start-a-job-from-a-schedule-handler) and return within the request window. A serverless application cannot declare a job. If the work will not fit in its handler's window, decide whether to split it into pieces that fit or run it through a server application. ## Steps ### 1. Declare the schedule #### Start a new hourly heartbeat This recipe starts a new service from the `server-scheduled-job` template. For an application with code of its own, new or deployed, use the next subsection. 1. Follow [Deploy from your computer](/cloud/getting-started/deploy-an-application/#1-create-the-application) to create the application with the size the person names. With no size named and nobody to ask, use Shared 0.5 GB with its default sleep setting. Report the size, that nobody was available, its awake-time charge and the option to request Shared 1 GB for more memory or CPU. Keep the connection and credential checks above. Use production alone unless the person asks to try versions on development first. 2. Run `turnzero scaffold --template server-scheduled-job`, or use the [server-scheduled-job example files](/cloud/examples/server-scheduled-job/) from a chat without the CLI. If you run the scaffold, skip the `tzcloud_create_application` step it prints. Use the application you created in step 1. The template already declares `heartbeat` at `/jobs/heartbeat`. Its handler [logs one line per run](#5-keep-state-between-runs). The CLI chooses a minute within each hour to spread schedule runs out. 3. Submit its manifest and [deploy](/cloud/getting-started/deploy-an-application/) to development if it is on, or to production if it is the only environment. Keep the schedule's name and path aligned with the handler. 4. [Confirm it runs](#4-confirm-it-runs) in the environment you deployed to. Tell the person which handler you will run and where. Call `tzcloud_run_schedule` for `heartbeat` with that environment, a new `request_id` and `wait_seconds: 45`. If the response includes `next`, use it to read the run. Confirm a successful run and read its console. 5. With two environments, [promote to production](/cloud/guides/turn-on-development-and-promote/#promote-to-production) after the development check passes and the account owner agrees, unless they already asked you to promote. A successful manual run confirms the handler ran. It leaves `next_due` unchanged. Reading a later timetable run is optional; that run appears with `trigger: "schedule"`. The manual run does not prove that a timetable run has happened. #### Add a schedule to an existing application Your AI assistant uses `tzcloud_read_plan_quotas` to read `schedule-minimum-interval` and `schedule-count-limit`. For a server, it passes the application’s size as `plan`, either `shared-0.5gb` or `shared-1gb`. For a serverless application, it uses `plan: "shared-0.5gb"`. It chooses a timetable within the returned limits. If a required quantity is `null`, it reports that the quantity is unset. A run's window, the time it has, is a platform setting, the same for every application, so `tzcloud_read_plan_quotas` has no row for it. It then adds a `schedule` entry to the manifest's `services` list, or a schedule to the entry already there. The entry's `schedules` list gives each schedule three members: - `name`, unique, of at most 64 characters, and matching `^[a-z][a-z0-9_]*$`, so `nightly_cleanup` passes and `nightly-cleanup` is refused `manifest_invalid`; - `cron`, a five-field expression in UTC, from minute to day of week, so `0 3 * * *` means 03:00 UTC every day; - `path`, the absolute path of the handler in the application. The path is never the health path, and never under `/__account/` or `/__router/`. This complete manifest declares `nightly_cleanup` at 03:17 UTC every day, with a handler that needs no Schedule package. When updating your application, keep its other services, packages and settings. If the handler starts a separate job, add that `job` entry to the same `services` array. Keep both entries when you submit the whole manifest. ```json { "manifest_version": 1, "application": "0f8fad5b-d9cb-469f-a165-70867728950e", "services": [ { "kind": "schedule", "schedules": [ { "name": "nightly_cleanup", "cron": "17 3 * * *", "path": "/jobs/nightly-cleanup" } ] } ], "health": "/health", "region": "usa", "egress": [], "audience": { "kind": "public" }, "packages": [] } ``` [Run scheduled work](/cloud/guides/author-the-manifest/#run-scheduled-work) describes the forms a cron accepts. If the work does not need an exact time, your AI assistant can choose different minutes for different schedules. For example, `17 * * * *` runs at 17 minutes past each hour in UTC. Your AI assistant keeps any time you requested and respects the one-minute minimum interval. The [server-scheduled-job template](/cloud/concepts/turnzero-command/#the-server-scheduled-job-template) starts its hourly heartbeat at the minute the service was created. You can change that timetable. If you named no time of day and the minute is flexible, your AI assistant can choose a minute shortly after the deploy should finish, so the first `next_due` falls within this session. For a request such as "every night", it asks you for a time and confirms it in UTC, or proposes a UTC time for your approval. Keep the timetable you asked for unless you ask for the [temporary shortest-interval check](#4-confirm-it-runs). That check observes a timetable run separately from the handler check with `tzcloud_run_schedule`, then restores your timetable. For a nightly run, agree on the local time and time zone. Ask whether the local hour should stay the same when the clocks change. A fixed UTC timetable can shift by the time zone's clock change. If the owner wants the same local hour, agree on who will update the timetable when the offset changes. For cleanup, ask what counts as expired and whether to preview the records the handler would remove. For the sign-up link example, use your app’s own records to find links whose expiry time has passed. If you preview the deletion, use the same expiry check for the preview and the deletion. Your AI assistant submits the whole manifest with `tzcloud_submit_manifest`. Submitting the manifest starts no run. Each schedule row of the response says in `starts_with` which deploy or promote starts the schedule. It also gives `window_seconds`, the seconds a run has. Each row also gives `cron_preview`, up to three times the cron yields after the submission, in UTC. Your AI assistant checks those times before deploying. Show them in the agreed local time zone. If that zone changes its clocks, show what the current UTC timetable means before and after the next change. ### 2. Write the handler Use the [Schedule handler reference](/cloud/reference/schedule-handler/) for the request headers, response status codes, and the private-path check. To start a separate job on the timetable, use the Schedule package option below with the [job-start example](/cloud/guides/run-a-job/#start-a-job-from-a-schedule-handler). Include both declarations in the same manifest and [deploy them in step 3](#3-deploy). If Cloud refuses the job declaration, see [Job refusals](/cloud/guides/run-a-job/#refusals). For a serverless schedule, make its `path` match the function file. For example, `functions/jobs/nightly-cleanup.js` serves `/jobs/nightly-cleanup`. [Deploy functions](/cloud/guides/deploy-functions/#run-a-function-on-a-schedule) explains how the platform calls a scheduled function. Write the handler to meet that reference's request and response contract. Start a deployed run by hand with step 4's `tzcloud_run_schedule`. A request you send to the deployed handler's path yourself receives 404 `scheduled_handler_only` before your code runs. [Run scheduled work](/cloud/guides/author-the-manifest/#run-scheduled-work) describes the declaration and when it starts in each environment. If your existing Node app has no dependencies, add a plain `node:http` handler to its server. Follow [A handler without the package](/cloud/backend-packages/schedule/#a-handler-without-the-package). This handler needs no `schedule` package entry. It checks `x-turnzero-cloud-invocation: schedule` and returns 404 for other requests. A heartbeat can log the due instant and respond 200. If your app uses the [Schedule package](/cloud/backend-packages/schedule/), use its router. It reads the headers, routes each run to its handler and gives the handler a key for the due instant. For a new service, use [the scaffold or example files](#start-a-new-hourly-heartbeat), which already include a handler. Before the first deploy, your AI coding agent can try a handler on the Schedule package's router on your machine. The package's test double, `createScheduleDouble` from `@turnzero/schedule/testing`, fires a run with the four headers the platform sets ([Test with the double](/cloud/backend-packages/schedule/#test-with-the-double)). ### 3. Deploy If your AI assistant signed in through a browser, it calls `tzcloud_deploy_command` from that connection. For a supplied-token connection, follow [The command's credential and path](/cloud/getting-started/deploy-an-application/#the-command-s-credential-and-path). Call `tzcloud_deploy_command` in this session. If you can run a returned command, supply `TURNZERO_CLOUD_MINTED_TOKEN` from the tool's secret store only for that command. Keep the token out of the command and chat. A schedule runs only when the environment's serving version was deployed or promoted with the current declaration. After changing the entry, call `tzcloud_deploy_command` unless you already called it in this step. Run the command if the reply supplies one and your AI assistant can run it. If the reply supplies no runnable command, follow `fallback` and use `tzcloud_deploy_files` ([Ways to deploy](/cloud/getting-started/ways-to-deploy/)). The environment works as follows: - On an application with one environment, the deploy reaches production and starts the schedule there. Nothing is promoted. Before deploying, confirm when the production timer will start and what the scheduled work may change. - On an application with two environments, the deploy starts the schedule in development. Production starts it at the next `tzcloud_promote`. Your AI assistant waits for the account owner’s approval unless they already asked for the promote ([Test in development, then promote](/cloud/guides/turn-on-development-and-promote/)). After the deploy, `tzcloud_read_schedules` shows the schedule's row with `deployed: true` and its next due time in `next_due`. With no `environment` named, it returns production's rows. Before the deploy, the row shows `deployed: false`, `next_due` null, and a `reason`. Use `tzcloud_read_schedules` for the full schedule list and run history. For the serving version and up to twenty schedules with their `last_run` and `next_due`, call `tzcloud_check_deploy` and read `last_release`. If `schedules_total` exceeds the length of the list, the environment has more schedules than the list shows. Every row also shows `cron_preview`: up to three future times matching the timetable, in UTC. This checks the cron expression; it does not prove a run started or succeeded. Use `next_due` for the next due time and `runs` for what actually happened. A halt, an overlapping run or another refusal can prevent a due run from reaching the handler. ### 4. Confirm it runs Before the check, your AI assistant tells you once which handler it will run and in which environment. With one environment, your request for the schedule covers one proving run of the handler on production. A job it starts needs separate approval unless the owner already requested that production start. With two environments, the proving run belongs on development. For any other manual run on production, your AI assistant asks and waits for your yes unless you already asked for that run. On development it needs no question. On production, with no prior approval and nobody to ask, it stops and reports. Your AI assistant then fires one run with `tzcloud_run_schedule`, naming the schedule, the environment, and a new `request_id`. The run reaches the handler as a due run does: the same path, the same four headers, the same window, and no retry. Its `trigger` is `manual`, its due instant is the time of the call unless you pass `due_at`, and it leaves `next_due` where it stood. A successful `tzcloud_run_schedule` run, with or without `due_at`, confirms that the schedule's handler ran. If it starts a separate job, [check that job's result](/cloud/guides/run-a-job/#check-the-result). The timetable is armed once its row shows `deployed: true` and a `next_due` time. No wait for a timetable run is needed to complete this check. If the handler starts a job soon after Cloud creates that job in the selected environment, the job run can stay `starting` for a few minutes. Wait and use `tzcloud_read_job_runs` to read the same job run by ID. If that start reply is lost, [recover the original job request ID](#5-keep-state-between-runs). To check the handler at one instant, pass `due_at`. It must be an instant in UTC, on a whole minute, at or before the call, that the cron yields, such as this morning's run time. The run is then due at that instant, and it reaches the handler by the same route a scheduled run at that instant would take. It still leaves `next_due` where it stood. The call is refused `invalid_request` for an instant still to come, one the cron does not yield, or one older than the platform keeps run records (30 days by default). Its `detail` says why. That instant may be earlier than the schedule's declaration. The check uses the schedule's current cron expression and the bounds above, not its declaration time. The current declaration must still have been deployed to the chosen environment before the run can start. It starts a manual run now, labelled with that earlier due time; it does not prove the timetable ran then or replay a historical version of the handler. A manual run uses the same `run.key` as the scheduled run for that due time. The key identifies the schedule and due time. A handler that records these keys can skip work it already did for a scheduled run. Both manual and scheduled runs go through the [serving router](/cloud/concepts/glossary/#serving-router). So if the environment has stopped while idle, the run wakes it first, as a due run would. The time the wake takes counts in the run's `duration_ms` and against its window. Each run reports `woke`. It is true if the environment had scaled to zero running instances before the run, even if the run later failed, and false if an instance was already running. It is null where the read failed or a start was already under way. A null means the platform could not tell whether this run woke the application. The run's outcome does not depend on that read; nothing needs doing for the null. Here, grain means how the environment runs: as a pod on shared compute or as its own container app. On the pod grain, `tzcloud_read_status`'s `compute_state` describes the current replica. `Running` means one is ready for a warm start. `Idle` means none is ready; it may be scaled to zero, halted, starting or crash-looping. `Idle` alone does not predict a cold start. For an environment running as its own container app, `woke` is always null, and `compute_state` does not predict whether the next run will start cold. With `wait_seconds`, a whole number from 1 to 45, the response waits until the run ends or that many seconds pass. When `settled` is true, `run` contains the outcome. When `settled` is false, the run was still going or the final read failed or ran past its bound. In the latter cases, `run` shows what the start call saw. A false `settled` does not mean the run failed. If the response includes `next`, follow its `tzcloud_read_schedules` call. Without `wait_seconds`, a new start returns at once with the run `running`. A repeat can return an ended run with no `next`. For a server, a run that ended inside the wait can include `console`, with up to 40 of the newest lines the environment wrote in the run's time window, within 4,096 bytes. Other requests can write lines in the same window. The handler's lines may be outside this tail or still arriving. Where `console.more` is present, follow its `tzcloud_read_logs` call. Use a run ID or another marker your handler writes to identify its own lines. For a serverless application's scheduled function, `console.outcome` is `unavailable` and `console.lines` is empty. Its `console.more` gives the `tzcloud_read_logs` call with `source: "pool"` to read the function's console lines and failures. Use a new `request_id` for each new run. Use a different ID for every new run in the application, including runs of different schedules or environments. Repeat only with the original schedule, environment, `request_id`, and any `due_at` from the first call. A repeat that reaches the lookup returns the earlier run and names its schedule and environment. Cloud checks the request before that lookup, so it can refuse a repeat even when the first run started. After a lost or refused reply, read `tzcloud_read_schedules` for the same environment before concluding that nothing started. Save the run ID, schedule and environment from the response. Find that run in the schedule's history with `tzcloud_read_schedules`. Use `wait_seconds` if the run is still going. After it ends, use `tzcloud_read_logs` with `source: "platform"` for its outcome event. For the handler's console, use `source: "container"` on a server or `source: "pool"` for a serverless function. If the platform ends the run at the end of its window, `source: "router"` shows `window_ended` with `kind: "schedule"` and the run's `schedule` and `run`. [Read logs and counters](/cloud/guides/read-logs-and-counters/) describes the sources. #### Check a run from the timetable Seeing a run started by the timetable is optional. Your AI assistant checks one only if `next_due` falls within this session or you ask to see it. For that check, call `tzcloud_read_schedules` after the row's `next_due` time. By default, the platform checks for due runs every 30 seconds. A run may start later if it must wake a stopped environment. Until the run starts, the row can still show that `next_due` with `in_flight` null. Read again after the next check. `wait_seconds` waits for a run already in flight; it does not wait for a future run to start. Nothing starts the timetable's run early: `tzcloud_run_schedule` always starts a manual run. The run the timetable started shows `trigger: "schedule"` in `last_run` and among `runs`. A manual run beside it shows `trigger: "manual"`. If the timetable's run is still running when you read, `wait_seconds` holds the read until it ends. For this optional check, where the minute is flexible, choose a minute in UTC a few minutes after the deploy should finish, such as for an hourly schedule. Submit that timetable and deploy once. Keep it as the real timetable. If a deploy makes a schedule effective after its first due time, the schedule starts from the deploy time. Its first run is the next due time after the deploy. Halting the environment holds the next due time and blocks manual starts. Resuming it moves the timetable past the halted period. Cloud records no missed rows for the halted times. For a schedule already in effect, the platform compares the oldest due time with its late tolerance, five minutes by default. If the check comes later than that tolerance, it writes one `missed` row whose `detail` counts the due times passed over. None of those runs is replayed. Within the late tolerance, the platform attempts the oldest due time once. If the schedule still has a run in progress, it records `skipped` with detail `overlap`. It advances `next_due` to the first time after the check. Any intervening times after the one it handled have no run or record. For this optional check, save the expected `next_due` before it passes. After that time, read `tzcloud_read_schedules` for the same environment. Look in `runs` for the expected `due` with `trigger: "schedule"`. Read its `outcome` and `detail`, even if it has no `started_at`. A `skipped` or `missed` row can already be the result. By default, `runs` shows the five most recent runs per schedule. You can set `limit` to any number from 1 to 100. The platform keeps 30 days of run history by default and keeps the last run even if it is older. One `missed` row can cover several due times. Report when no row covers the expected time. For a development check, use `environment: "development"`. Your AI assistant makes a temporary timetable check only if you ask for one. It uses development when it exists; no further question is needed there. On production, it asks for your yes before changing the timetable for this check. For that requested check on a timetable whose minute is fixed, choose a temporary cron that meets the application’s current `schedule-minimum-interval`. If the returned minimum is one minute, `* * * * *` runs every minute. Deploy and check the timetable's run as above. Then submit the real timetable and deploy again. The second deploy counts against the day's deploy limit. ### 5. Keep state between runs The process can stop or restart, so do not rely on memory between runs. A heartbeat needs no saved state. Use `tzcloud_read_schedules` to see recent runs and `tzcloud_read_logs` to read the handler's output. The run history keeps the due time and outcome even after the server sleeps. When a pod stops, its live console disappears. Only some lines may be saved at shutdown. [How log records arrive](/cloud/concepts/how-log-records-arrive/#how-long-console-lines-last) explains which lines you can still read. To keep a heartbeat record after the pod stops, pass a `record` function to `createScheduleRouter`. This example uses your existing `schedules` and `handlers`, and a [Logging client](/cloud/backend-packages/logging/#construction-and-options) named `client`. ```js const router = createScheduleRouter({ schedules, handlers, record({ schedule, run, status, duration_ms }) { client.log.info('Scheduled run', { schedule, run, status, duration_ms }); }, }); ``` Once the Logging client sends the entry, use `tzcloud_read_logs` in the same environment with `field: "run"` and `value` set to the run ID from `tzcloud_read_schedules`. To record what the handler did, write a separate entry in the handler with the same `run` field. A handler that needs something from the last run, such as the due instants it already handled, keeps it in one of two places: - a JSON file in a declared [storage area](/cloud/concepts/glossary/#storage-area), written with a conditional put: `If-Match` with the version read, or `If-None-Match: *` for the first write, so one run never silently overwrites another; - the database, where the manifest declares one ([Add a database](/cloud/guides/add-a-database/)). Counters are write-only tallies that `tzcloud_read_counters` totals, never a place to keep state. [Keep state between runs](/cloud/backend-packages/schedule/#keep-state-between-runs) shows a package-router handler that claims each run key in storage before attempting a send. When a handler starts a job, save the schedule run ID and the job run ID together with the job's request ID in your database or storage. Have the job record its own progress and the changes it finishes. Build the job's `request_id` from the job name and `run.key`. Keep it separate from the `request_id` you pass to `tzcloud_run_schedule`. If the start reply is lost, [recover the job's request ID from the schedule's due time](/cloud/guides/run-a-job/#start-a-job-from-a-schedule-handler) and retry with that same ID. After a missed run, check the schedule history for the expected due time and whether the work still needs to happen. If the run reached an outside service, check that service for a receipt or a record of the action before clearing a saved claim or trying the action again. A saved claim alone proves only that the attempt was reserved. If the result is still unclear, tell the owner what you could verify and ask how to resume. Agree on who should hear about a missed or failed run and where they will see it. Report the due time, the recorded outcome, and whether the work still needs attention. ## Expected result After the successful manual proving run, `tzcloud_read_schedules` for the environment shows the schedule's row with: - `deployed: true`, `reason: null`, and `next_due` set to the next due time; - `in_flight` null once the run has ended; - `last_run` with `trigger: "manual"`, the `due` instant, `started_at`, `ended_at`, `outcome: "succeeded"`, the handler's `status`, and `duration_ms`; - the same run among `runs`, the most recent runs by due time. `tzcloud_read_logs` with `source: "platform"` returns one event for the run. To read the line the handler wrote, use `source: "container"` for a server or `source: "pool"` for a serverless application's function. A later run started by the timetable shows the same, with `trigger: "schedule"`. Reading that timetable run is optional. Report which checks you completed. - The `cron_preview` times show when the submitted timetable is due to run. - A successful run with `trigger: "manual"` shows that the handler ran when you started it. - After the expected due time, check `runs` for that time with `trigger: "schedule"` and report its outcome. A `skipped` or `missed` row can give the outcome even if the handler never started. If the due time is still ahead, give the owner the time and the read to use later. - If the handler starts a separate job, [read the job's run](/cloud/guides/run-a-job/#check-the-result) and check the saved result by its work ID. ## Refusals See the [refusals reference](/cloud/reference/refusals/) for other platform errors. The deploy's own refusals are in [Deploy from your computer](/cloud/getting-started/deploy-an-application/#refusals), and the manifest's others in [Author the manifest](/cloud/guides/author-the-manifest/#refusals). | Refusal | Status | Cause | Remedy | | --- | --- | --- | --- | | `manifest_invalid` | 400 | The schedule entry does not match the schema, such as a name with a hyphen; `violations` lists the failing paths. | Correct each path and submit the whole manifest again. | | `invalid_request` | 400 | `tzcloud_read_schedules` or `tzcloud_run_schedule` named an environment other than `development` or `production`, a `wait_seconds` outside 1 to 45, or a `due_at` still to come, outside the cron, or too old; `detail` names the member. | Correct the named member and call again. | | `no_such_schedule` | 404 | The application has no schedule of that name in the environment the call named. | Name a declared schedule, and name the environment when it is not production. | | `schedule_interval_below_plan` | 409 | The cron's due times fall closer together than the one-minute `schedule-minimum-interval`; `gap` gives the shortest gap. | Choose a cron with gaps of at least one minute. | | `schedule_count_over_plan` | 409 | The manifest declares more than the `schedule-count-limit`, 25 schedules for either size. | Remove schedules to stay within the limit. | | `plan_schedule_conflict` | 409 | `tzcloud_set_app_size` found declared schedules that exceed the target size's limits. | Submit the manifest within those limits, then repeat the size call. | | `plan_quantity_unset` | 409 | The size has no value set for a schedule limit. Nothing is recorded. | Wait for platform staff to set the value. | | `schedule_not_deployed` | 409 | `tzcloud_run_schedule` named an environment with no deploy or promote since the schedule was declared. | With one environment, deploy to production, then fire again. With two, deploy and fire in `development`; name it explicitly in `tzcloud_run_schedule`. Use a new `request_id` for that development run. Production starts the schedule at the next promote. Your AI assistant waits for the account owner’s approval unless they already asked for the promote. | | `environment_not_created` | 409 | `tzcloud_run_schedule` named `development` on an application with one environment. | Fire the run in production, or turn development on and deploy there first. | | `run_in_flight` | 409 | A run of the schedule has not ended yet. A due time that falls during it is skipped, not queued. | After a lost or refused reply, read the schedule's run history in `tzcloud_read_schedules` to check what started. If you retry a lost call, use the original schedule, environment, `request_id`, and any `due_at`. If you receive `run_in_flight`, check the run ID named in the refusal. For a new run, wait until none is in flight and use a new `request_id`. | | `target_environment_halted` | 409 | `tzcloud_run_schedule` named a [halted](/cloud/concepts/glossary/#halted-environment) environment. | Call `tzcloud_halt_environment` with `resume: true`, then fire again. | If the account pauses for lack of balance, the router stops the schedule before the handler runs, and the due time counts nothing. The management call `tzcloud_run_schedule` returns its normal run response. Once the run settles, it shows `run.outcome: skipped` with `run.detail: account_paused`. If the call returns while the run is still in progress, follow `next` to see the result. Wait for Free Allowance to renew or for credit you can use. ## Related - [Start a job from a schedule handler](/cloud/guides/run-a-job/#start-a-job-from-a-schedule-handler) shows how to start a separately declared job and check its result. - [Schedule handler](/cloud/reference/schedule-handler/) gives the headers, response status codes, and private-path check. [Run scheduled work](/cloud/guides/author-the-manifest/#run-scheduled-work) describes the declaration, `starts_with`, and what a halt does. - [Schedule](/cloud/backend-packages/schedule/) describes the package's router, a handler without the package, and a handler that keeps its state in a file. - The `schedule` [skill](/cloud/concepts/glossary/#skill), which your AI assistant reads with `read_context` and the id `skill:schedule`, gives these steps as the rules your AI assistant follows. - [Read logs and counters](/cloud/guides/read-logs-and-counters/) reads the platform's events and the handler's lines. - [Store files](/cloud/guides/store-files/) covers the storage areas and the conditional put. --- title: Use WebSockets description: Declare WebSockets in the manifest, accept the upgrade in your server, connect from a page or a native app, and reconnect after a close. slug: /guides/use-websockets order: 6 visibility: public redirects_from: [] --- # Use WebSockets Prompt: > Show new chat messages to everyone in the room as soon as they are sent. Also works: - "Add live updates to the dashboard over a WebSocket." - "Why does my socket keep closing on the hosted app?" Declare `websockets` in the manifest ([step 1](#1-declare-websockets-in-the-manifest)), and accept the upgrade on the server's own port ([step 2](#2-accept-the-upgrade-in-the-server)). The page then connects to the same hostname with `wss://` ([step 3](#3-connect-from-the-app-s-page-or-list-another-origin)), and reconnects after a close ([step 5](#5-reconnect-after-a-close)). ## What your AI does - Adds the `websockets` member to the [manifest](/cloud/concepts/glossary/#manifest) and submits the whole manifest with `submit_manifest`. - Writes one server that answers requests and accepts the upgrade on the same port, with the `ws` library, and pings each connection every 30 seconds. - Writes the page's client, which reconnects after a close with a growing wait. - Deploys. If the application has a development environment, [promotes](/cloud/concepts/glossary/#promote) only when you have asked for production or confirmed the promote. - Tests the connection on your machine, then on the hosted hostname, and reads a refused upgrade's `error` and `detail` with `curl`. - If a page on another address opens the connection, asks for that page's origin before submitting the manifest. If production promotion needs your confirmation, asks and waits before promoting. No step needs a browser approval. ## What you need - An application that deploys ([Deploy from your computer](/cloud/getting-started/deploy-an-application/)). - A server built on Node.js's `http` module, directly or through a framework such as Express, so the WebSocket library can take the upgrade from it. ## Before your AI starts **For the AI assistant:** Check the following before starting. - Your AI assistant connected and signed in ([Connect your AI assistant](/cloud/getting-started/connect-your-tool/)). - `list_applications` returns the application's identifier and each environment's `grain`. Both Shared 0.5 GB and Shared 1 GB support WebSockets, on shared compute and in their own container. - The application's current manifest, because a submission replaces the whole document. - `ws` among the application's dependencies, installed before the build. ## Steps ### 1. Declare WebSockets in the manifest A server application accepts WebSocket upgrades only once its manifest declares the `websockets` member. Without it, every upgrade is refused 400 `websockets_not_declared` before it reaches the application. The member is an object holding at most `origins`. The empty object admits a page served from the application's own hostname, and a client outside a browser, such as a native app or a script. Serverless applications cannot accept WebSocket upgrades. `tzcloud_submit_manifest` returns 400 `serverless_no_websocket` for a serverless manifest that declares `websockets`. An upgrade that reaches a deployed serverless environment on the application’s own path gets the same refusal. On the platform’s reserved paths, the router returns 400 `upgrade_not_served` before it checks the application kind. See [Refusals](#refusals). ```json "websockets": {} ``` The declaration takes effect when `submit_manifest` records it, in both environments, with no deploy: the [serving router](/cloud/concepts/glossary/#serving-router) reads it within about 30 seconds. Removing the member, or an origin, closes the open connections it admitted with code 1008 within about the same time. A page on another address needs its origin listed, as step 3 says. [The manifest](/cloud/concepts/the-manifest/) lists every member. ### 2. Accept the upgrade in the server The upgrade reaches the application's own server, on the port its requests use. Hand that server to the WebSocket library, so one process serves both. This `server.mjs` answers the manifest's `health` path, here `/health`, and accepts connections on `/live`. It sends each message to every open connection, and pings each connection every 30 seconds, so the router's idle limit never closes a quiet one (step 4). The example admits any client, including a script with no session, and each data message the client sends counts as one backend action. For a room of signed-in users, [step 6](#6-sign-in-on-the-connection) says how to turn away a connection with no verified user. ```js import http from 'node:http'; import { WebSocketServer } from 'ws'; const server = http.createServer((req, res) => { if (req.url === '/health') { res.writeHead(200, { 'content-type': 'text/plain' }); res.end('ok'); return; } res.writeHead(404, { 'content-type': 'text/plain' }); res.end('not found'); }); const sockets = new WebSocketServer({ server, path: '/live' }); sockets.on('connection', (socket) => { socket.on('message', (data) => { for (const other of sockets.clients) other.send(data.toString()); }); }); const heartbeat = setInterval(() => { for (const socket of sockets.clients) socket.ping(); }, 30_000); server.on('close', () => clearInterval(heartbeat)); server.listen(process.env.PORT ?? 8080); ``` With Express, pass the app to `http.createServer(app)` in place of the handler above. Socket.IO attaches to the same `http` server in the same way, and serves its own path, `/socket.io/`. Socket.IO sends its own heartbeat as a data message every 25 seconds. Its client also starts on HTTP long-polling, and each poll is a request. So prefer `ws`. With Socket.IO, set `transports: ['websocket']` on the client and leave out step 4's ping. Use a path of the application's own. An upgrade under `/__account/`, `/__router/`, or `/.well-known/` is refused 400 `upgrade_not_served`, because the platform answers those paths itself. An upgrade on `/` reaches the application, even where the platform serves the web client's page there for an ordinary request. The upgrade request meets every check an ordinary request meets, the per-address limits and the sign-in gate among them ([Egress firewall and request limits](/cloud/concepts/egress-firewall-and-request-limits/)). A handshake carries no body: one with a body is refused 400 `invalid_request`. The connection opens only when the server answers 101. Any other answer, such as the one the library writes for a path it does not serve, reaches the client as an answer, and the connection closes. The platform's refusals carry a JSON body with `error`; the library's own answer does not. Once the server answers 101, the request deadline no longer applies, and the connection stays open within the limits in [Limits and metering](#limits-and-metering). Each environment runs one copy of the server, so one process holds every connection to that environment, and the loop above reaches every client. A deploy, promote, rollback, or restart starts a new copy and closes the old copy's connections (step 5). ### 3. Connect from the app's page, or list another origin Connect to the host that served the page. Use `wss:` for HTTPS or `ws:` for a local HTTP page. This script shows each message in a list with the id `messages`, and sends what the person types in the `text` input of a form with the id `send`. It reconnects after a close as step 5 describes. ```js const list = document.querySelector('#messages'); const form = document.querySelector('#send'); const STOP = new Set(['account suspended', 'account paused']); let socket; let wait = 1_000; function show(text) { const item = document.createElement('li'); item.textContent = text; list.append(item); } function connect() { const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:'; socket = new WebSocket(`${protocol}//${location.host}/live`); socket.onopen = () => { wait = 1_000; }; socket.onmessage = (event) => show(event.data); socket.onclose = (event) => { if (event.code === 1008 && STOP.has(event.reason)) { show(`Live updates stopped: ${event.reason}.`); return; } const delay = event.code === 1001 ? Math.random() * 1_000 : wait + Math.random() * 1_000; if (event.code !== 1001) wait = Math.min(wait * 2, 60_000); setTimeout(connect, delay); }; } form.addEventListener('submit', (event) => { event.preventDefault(); if (socket?.readyState !== WebSocket.OPEN) return; socket.send(form.elements.text.value); form.reset(); }); connect(); ``` Every browser sends an `Origin` header on the handshake, the address of the page that opens the connection. The router admits `https://` with the hostname the upgrade arrived on, and each origin the declaration lists. Any other origin is refused 403 `origin_not_admitted`, before the router reads the visitor's session. So a page on another site cannot open a connection that carries your visitor's sign-in cookie. A client that sends no `Origin`, such as a native app or a script, is admitted. List an origin only when a page on another address opens the connection, such as a web client hosted elsewhere. Only `https://` origins can be listed. A page served from `http://localhost` cannot connect to a hosted hostname, so run the server on your machine too (step 7). `origins` holds at most ten. Each is exact: `https://`, a lowercase hostname, and a port only when it is not 443, with no path, no wildcard, and no repeat. Write an origin on port 443 without a port, since `:443` is refused, and keep each dot-separated part of its hostname to 63 characters and the whole hostname to 253. A test checks this sample against the platform's rule for origins. ```json "websockets": { "origins": ["https://app.example.com", "https://staging.example.com:8443"] } ``` A submission whose list breaks a rule is refused 400 `manifest_invalid`. Each line of its `violations` gives the entry's path and the rule, such as `/websockets/origins/1: must omit the default port`. The router checks the handshake's origin before it reads the declaration. A page on another site sees 403 `origin_not_admitted` before `websockets_not_declared`, so a 403 does not mean the declaration is in place. ### 4. Keep the connection open An open WebSocket connection keeps production awake as a request in flight does, so the idle stop does not close it. The router closes a connection after 120 seconds with no byte in either direction, with code 1001. So the server sends a WebSocket ping at least every 60 seconds; step 2's server sends one every 30. Every browser and WebSocket client answers a ping with a pong by itself. Each data message from a client counts as one backend action, while ping and pong frames add none. A connection also closes two hours after it opened, with code 1001, whatever it carries. It can also close unexpectedly with code 1006 and no reason. In each case the client reconnects, as step 5 describes. ### 5. Reconnect after a close The router closes a connection with a code and a short reason, and the client reconnects. The code tells the client how soon: | Code | Reasons | What happened | What the client does | | --- | --- | --- | --- | | 1001 | `idle bound`, `lifetime bound` | No byte moved for 120 seconds, or the connection reached two hours. | Reconnects after a random wait of up to a second. | | 1012 | `compute replaced`, `router stopping` | A deploy, promote, rollback, or restart replaced the copy of the server, or the router replica stopped. | Adds a random delay before reconnecting and waits longer after each failed attempt. This spreads out reconnects across clients. | | 1013 | `standing stale` | `standing stale` means the platform could not confirm for a while that the account is in good standing, because the router could not reach the platform's records. Its requests are refused the same way until it can. | Reconnects with a growing wait. | | 1008 | The table below | The connection passed a limit, its sign-in was revoked, or a request on the environment would now be refused. | Reads the reason, and reconnects with a growing wait when the cause can pass. | A connection can also end without a close frame, which a browser reports as code 1006. A network fault does this, and so does the server ending the connection itself. It also happens when the router cannot send its close between two frames within one second. The client reconnects with a growing wait. For a growing wait, wait about one second before the first attempt, double the wait after each failed attempt up to about a minute, and add a random part to each wait. On `account suspended` or `account paused`, the sample shows “Live updates stopped” and stops reconnecting. Load the page again after the account can serve requests. Step 3's client does all of this. The reasons a 1008 close carries: | Reason | Cause | | --- | --- | | `message bound` | The connection passed its data-message limit for the minute ([Limits and metering](#limits-and-metering)). | | `source message bound` | The client's address passed its data-message limit for connections without a session. | | `user message bound` | The signed-in user passed their data-message limit, whatever addresses they came from. | | `signed-in source message bound` | The client's address passed its data-message limit for connections with sessions. | | `frame bound` | The connection passed its limit of frames of every kind for the minute. | | `account paused` | The application's account used its balance for the month, pausing the application and closing its open connections. The pause ends when the account has Free Allowance available again or credit it can use. Reconnects while paused receive 429 `account_paused`. The `Retry-After` header gives the wait in seconds if the pause lasts until the next UTC month. | | `account suspended` | The account was suspended. | | `environment halted` | The environment was halted. | | `not deployed` | The environment no longer runs a version. | | `application gone` | The hostname no longer names a live application, after a deletion or a rename. | | `target unreadable` | The router could not read where the environment runs. | | `websockets withdrawn` | The manifest no longer declares `websockets`. | | `origin not admitted` | The manifest no longer lists the origin of the page that opened the connection. | | `sign-in required` | The audience became `invited` or `workforce`, or the connection's path left `session_free_paths`, and the connection holds no valid session. | | `session revoked` | The session ended, by a sign-out or a revocation. | | `user revoked` | `set_end_user_standing` suspended the end user, which ends every session signed before. | | `realm revoked` | The platform revoked every session of the [realm](/cloud/concepts/glossary/#realm). | | `key revoked` | `revoke_app_sign_in_keys` revoked the key that signed the session. | | `realm unknown` | The router no longer finds the realm the session belongs to. | | `session unchecked` | The router could no longer keep the realm's revocations current, so it closed the connection rather than keep it unchecked. | ### 6. Sign in on the connection A page on the application's hostname sends the session cookie with the handshake, as it does with a request. The router verifies the session at the handshake and sets the header `x-turnzero-cloud-session` on the upgrade request. So the server tells which user opened the connection as [Tell which user sent a request](/cloud/guides/add-sign-in-to-your-app/#3-tell-which-user-sent-a-request) shows for a request, reading the upgrade request the `connection` event passes as its second argument. An expired cookie token is issued again on the 101, as on any response. Where the room is for signed-in users, close a connection whose request carries no verified user, and handle no message from it. A native app sends its [bearer token](/cloud/concepts/glossary/#bearer-token) in the handshake's `Authorization` header, when its WebSocket client lets it set headers. A browser's `WebSocket` cannot, so a page relies on the cookie. An expired or revoked bearer token is refused 401 `authentication_required` on every audience, so refresh it before reconnecting. The router reads the session once, at the handshake. After each scheduled refresh, the router checks open connections against the keys and revocations it holds. It closes a connection with code 1008 once those records show a revocation of the session, the user, the realm's sessions, or the signing key. The token's expiry alone does not close an open connection, and the two-hour limit still applies. Under an `invited` or `workforce` [audience](/cloud/concepts/glossary/#audience), an upgrade without a valid session is refused 401 `authentication_required`, when the request is a WebSocket handshake. The router sends no sign-in redirect because the handshake is not a page visit. A path listed in `session_free_paths` is admitted without one. ### 7. Deploy and test Test on your machine first. Run the server as [Run your app on your computer](/cloud/guides/run-your-application-on-your-machine/) describes, and connect to `ws://localhost:/live` at the command's printed port. The platform's checks and limits do not apply there. With `turnzero` 0.38.0 or later and `--sign-in `, sign in through the local browser page first; its cookie then reaches the local WebSocket upgrade too. Without `--sign-in`, hand your test a hosted session instead. [Test a local run](/cloud/guides/test-sign-in-with-test-end-users/#7-test-a-local-run) describes the sign-in and its browser and session limits. Then deploy. If the application has a development environment, promote once the owner has requested production or confirmed the promote. Both Shared 0.5 GB and Shared 1 GB serve WebSocket upgrades in production and development. This includes shared compute (`pod`) and environments in their own container (`container`). `list_applications` and `read_status` show each environment's `grain` ([Grain and development group](/cloud/concepts/glossary/#grain-and-development-group)). A refused upgrade answers with a status and a JSON body whose `error` names the refusal and whose `detail` says why, and the connection then closes. A browser's `WebSocket` does not show the answer, and reports a close with code 1006. Read the answer with a client outside the browser, such as `curl`, giving the application's hostname and the path. ```text curl --http1.1 --include -H "Connection: Upgrade" -H "Upgrade: websocket" -H "Sec-WebSocket-Version: 13" -H "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==" https://