---
title: Store files
description: Store files through your backend, private to each user or shared in a public upload service, and let a browser or app send or fetch one file directly.
slug: /guides/store-files
order: 3
visibility: public
redirects_from: []
---

# Store files

Add file uploads and downloads to your app, and control who can access each file. Read this page to set up storage, write file routes, or let a browser or mobile app transfer a file directly.

For a public gallery with no sign-in, use the [complete upload starter](/cloud/guides/build-a-public-upload-gallery/), including its server, gallery page and check script.

Prompt:

> Let users upload images, and keep each user's images private to that user.

Also works:

- "Save each generated report as a file the user can download later."
- "Let people attach a photo to a listing."
- "Let anyone upload images to a shared gallery, with no sign-in."

For a manual upload, use [Upload a file from the application's page](#upload-a-file-from-the-application-s-page). To add file handling to your app, read [Before your AI starts](#before-your-ai-starts), then follow these steps.

1. [Declare storage and its areas](#1-declare-the-service-and-the-areas) for the files the app will keep.
2. [Write the file routes](#2-put-fetch-list-delete). Follow the [private upload service](#a-minimal-upload-service) or the [complete public starter](/cloud/guides/build-a-public-upload-gallery/).
3. [Add a transfer grant](#3-hand-a-browser-or-a-native-app-a-transfer-grant) if a browser or mobile app should upload or download files directly.

The later steps cover [limits](#4-limits-and-metering), [area declarations outside the manifest](#5-declare-or-remove-an-area-outside-the-manifest) and [deploy uploads](#6-the-deploy-area-and-deploying-from-an-area-of-your-own). Check [Expected result](#expected-result) for successful responses or [Refusals](#refusals) for a remedy.

For a complete HTTP example without the Storage package, use [Call storage without end-user sign-in](#call-storage-without-end-user-sign-in): declare an area with a JSON body, write a file, list the area and fetch the file.

Your backend or a script can also call the [file routes](/cloud/backend-packages/storage/#file-routes) directly over HTTPS without the Storage package. The credential and environment requirements in [step 2 (Put, fetch, list, delete)](#2-put-fetch-list-delete) apply; your backend still checks which files each end user may access. An application calling those routes lists no Storage package row in the manifest's `packages`; with no library entry at all, it declares `packages: []` ([Author the manifest](/cloud/guides/author-the-manifest/)).

To use the package, get `@turnzero/storage` with `turnzero library take --origin https://dev.turnzero.ai --entry storage` (`turnzero.cmd` in Windows PowerShell), not from the npm registry. The command downloads the library entry, copies its compiled code into your app, and installs the local dependency; [Use the feature package library](/cloud/guides/use-the-library/) covers the credential and project layout.

For a small JSON value or list read and replaced whole, use a storage area with a conditional put, as [Files or a database](/cloud/getting-started/find-a-guide/#files-or-a-database-for-a-list-of-records) explains. For records you search, sort, transact on, or change individually from concurrent requests, use PostgreSQL. [Keep key-value records](/cloud/getting-started/build-a-database-backed-service/#keep-key-value-records) gives the scaffold command for a key column and a value column. Turn Zero Cloud has no separate key-value storage service.

## Upload a file from the application's page

You can upload a file yourself without a command or a file-upload feature in your app. This also helps when your AI cannot read a file's bytes, such as a photo attached to a chat.

The file address returned by `declare_storage_area` is an HTTP route. Opening it in a browser does not upload a file. A person or AI assistant with a shell and access to the file can call `mint_upload_grant` and run its returned command. For the upload from the application's page below, do not call `mint_upload_grant`; the signed-in page handles it.

1. Sign in at turnzero.ai, open **Applications**, and choose your application.
2. In the storage section, select **Upload a file** to open the dialog, then choose the area your AI named. If no area is listed, ask your AI to declare one first.
3. Choose your file. With production alone, the upload goes to production. With two environments, the dialog starts with the environment named in the page address, or development if none is named. For a file to include in a deploy, choose **development** when the app has two environments. Select **Upload a file**.
4. The upload keeps the file's own name. For files your app stores under a user ID, use your app's signed-in upload route. Give your AI the file name shown after the upload and the area name. To find those names later, choose the same environment and look in the file list below the storage areas. Expand the list if more files are available. Uploading the same name to the same area and environment replaces that file.

Uploads require a sign-in within the last 8 hours. If prompted, select **Sign in again to upload a file**, then upload.

**For the AI assistant:** Declare an area bound to the application with `declare_storage_area` if it has none. Ask the person to follow these steps and tell you the stored name. Do not call `mint_upload_grant` for this route; the page handles the upload, and no grant passes through the chat. `deploy_files` reads each stored file from the environment receiving the deploy: production when the application has production alone, and development when it has two environments. With production alone, the page uploads to production without offering an environment choice. With two environments, ask the person to choose development for a file the deploy will use.

Add the uploaded file to the complete `deploy_files.files` list. Reuse the serving version's `kept` hashes for files you know are unchanged in the target environment, as [Continue in a later chat](/cloud/getting-started/build-an-app-from-a-chat/#continue-in-a-later-chat) describes. If no hashes are available, use the original project files or ask the person for the missing files and their application paths.

For the uploaded file, send an entry like this.

```json
{ "path": "valley.png", "stored": { "area": "site-assets", "name": "valley.png" } }
```

`path` is where the file belongs in the version; `area` and `name` identify the uploaded copy. An optional top-level `sha256` checks the stored bytes. The platform copies those bytes exactly, and the answer's `stored` lists their size and SHA-256.

Stored entries have no 512 KiB per-file limit. They still count toward `deploy_files`' 4 MiB total and 200 entries. Inline files keep the 512 KiB limit.

If the file is missing, `artifact_not_found` points to the application's page. Check the area, file name and deploy environment, then ask the person to upload again if needed. `artifact_area_mismatch` means the area cannot be used for this application's deploy.

## What your AI does

- Reads the `add-service` [skill](/cloud/concepts/glossary/#skill) (`read_context`, id `skill:add-service`) and follows it.
- Copies the [Storage](/cloud/backend-packages/storage/) package for examples that use it, and the [Account](/cloud/backend-packages/account/) package where users sign in ([Use the feature package library](/cloud/guides/use-the-library/)).
- Writes the routes of [A minimal upload service](#a-minimal-upload-service). Each route checks the signed-in user and keeps that user's files under the user's id.
- Or writes the complete starter of [A public upload service with no sign-in](/cloud/guides/build-a-public-upload-gallery/), where anyone may upload and read every file: its server, its gallery page, and its check script.
- Adds the grant route of [step 3 (Hand a browser or a native app a transfer grant)](#3-hand-a-browser-or-a-native-app-a-transfer-grant) where a web page or a native app uploads or downloads directly from storage.
- Deploys the change and waits until the deploy finishes ([Deploy from your computer](/cloud/getting-started/deploy-an-application/)).
- Asks you which files each user may read and write before it writes the routes, where the prompt does not say.
- Asks you first before one action, `delete_environment`. It erases the development files in every area of the application, and runs only after you approve it in the browser ([Applications and environments](/cloud/concepts/applications-and-environments/#deleting-the-development-environment)).

## What you need

- A decision on which files each end user, a person who uses your application, may read and write. Your backend enforces it, because the platform doesn't separate files by user.
- Stored files and the database share the application's 100 GB stored-data ceiling. Read the [current application limits](/cloud/guides/plan-and-usage/#current-application-limits) without signing in, or call `read_plan_quotas` with `plan: "shared-0.5gb"` or `plan: "shared-1gb"` and `measure: "stored-data-capacity"`. File storage posts a day's share on its own line. Read its rate on the [pricing page](https://dev.turnzero.ai/pricing) or with `read_rate_card`.

## Before your AI starts

**For the AI assistant:** Check the following before starting.

- Before declaring storage or deploying, connect and sign in to Turn Zero Cloud ([Connect your AI assistant](/cloud/getting-started/connect-your-tool/)). Taking the Storage package with the CLI also requires a CLI credential ([Use the feature package library](/cloud/guides/use-the-library/)). A public upload service needs no end-user sign-in; a private service needs [application sign-in](/cloud/guides/add-sign-in-to-your-app/).
- The application's identifier, which `list_applications` returns. Your server code reads `TURNZERO_CLOUD_APPLICATION` and passes it as `mintArea`'s `application` option. `StorageWireClient` reads no environment variables. A deploy sets that setting, and the [`provision` command](/cloud/concepts/turnzero-command/#running-on-your-machine) sets it for a run on your machine.
- For a run on your machine, follow [Write the environment file](/cloud/guides/run-your-application-on-your-machine/#1-write-the-environment-file). The `provision` command writes the settings your backend uses to reach development storage. That guide explains which data and credentials the local run shares with production.
- An absolute link your backend returns is built from `APP_PUBLIC_HOST`, the environment's public hostname, never from the request's `Host` header, which names the platform's internal address for the environment ([the settings table](/cloud/concepts/the-settings-a-deployed-copy-receives/#settings-and-environment-variables-a-deployed-copy-receives)).
- A file the application needs again goes in an area. What the code writes to the running copy's own disk is lost whenever the copy is replaced or stops, as at a deploy or after an idle stop ([Running copy](/cloud/concepts/glossary/#running-copy)).

## Steps

### 1. Declare the service and the areas

Add `{"kind": "object_storage"}` to the manifest's `services` array. The `object_storage` kind alone creates no storage area. Set up each area before using it. Choose a route below based on which part of your project sets it up. The storage routes and `declare_storage_area` work for a declared area with or without the entry. The entry's `areas` list holds one to fifty areas. Each has a `name` and `account_keyed`, and no name appears twice.

```json
{"kind": "object_storage", "areas": [{"name": "photos", "account_keyed": true}]}
```

Choose how to set up each area:

- The manifest's `areas`, for an area the application knows when it is built.
- The client's `mintArea`, for an area the running application creates, such as one per notebook.
- The `declare_storage_area` action, for a script or a tool.

One route is enough for an area. A manifest submission sets up each area it lists and reports `created` or `unchanged`. Areas keep only the current file at each name.

Two routes may declare one area, such as the manifest's `areas` and a `mintArea` at each start. Under the application's platform credential or a token for that application, a `mintArea` that omits `application` still declares the area for that application. The platform returns `unchanged` when `account_keyed`, `version_keeping`, and the application match the existing area. It refuses a declaration that changes any of the three ([step 5: Declare or remove an area outside the manifest](#5-declare-or-remove-an-area-outside-the-manifest)).

An area the list drops keeps its declarations and its files, because no submission ends an area. [Step 5 (Declare or remove an area outside the manifest)](#5-declare-or-remove-an-area-outside-the-manifest) covers declaring an area outside the manifest, and removing an area.

On every application, each area has two parts: development and production. A file written in development cannot be seen from production, and one name can mean a different file in each part. A run on your machine under the development platform credential writes to the development part. This holds on an application with one environment too, so test files never reach production. `delete_environment` erases every area's development files and leaves production's as they were.

### 2. Put, fetch, list, delete

Check who sent the request and which files they may use before your backend calls storage. A user's session cannot call the storage routes. Your backend uses the [platform credential](/cloud/concepts/glossary/#platform-credential). Group file names by user ID, and enforce that same rule in every route that reads or writes those files.

If no end user is signed in, your backend still passes a nonempty `identity` on each write, such as `anonymous` for a visitor or `report-job` for a background task. This is an attribution label your backend chooses, not a sign-in credential or an access check. Your backend decides which files the caller may reach ([File names, environments, and conditional writes](#file-names-environments-and-conditional-writes)).

The platform credential already belongs to one environment, so your backend sends no environment header. A script of your own may call the file routes with a [minted token](/cloud/concepts/glossary/#minted-token), for example to delete a test file. On each file call, send `x-turnzero-cloud-environment` with `development` or `production`. A read, a list, and a delete need it as a write does. Without it the call is refused 400 `environment_required` ([File names, environments, and conditional writes](#file-names-environments-and-conditional-writes)).

#### Call storage without end-user sign-in

This example runs in your deployed backend and uses Node.js's built-in `fetch`, without the Storage or Account package. It declares a shared `notes` area through `PUT /storage/v0/areas/notes`, the HTTP route `mintArea` calls, writes `hello.txt`, lists the area, then reads the file.

No visitor signs in, and the backend needs no browser session. It still uses its platform credential; a call with no credential returns 401 `authentication_required`. Keep that credential in the backend.

```js
// src/storage-no-sign-in.mjs: declare, write, list and read shared files
const origin = process.env.TURNZERO_CLOUD_GATEWAY_URL || process.env.TURNZERO_CLOUD_API;
const auth = { authorization: `Bearer ${process.env.TURNZERO_CLOUD_APP_TOKEN}` };

async function call(path, init = {}) {
  const response = await fetch(`${origin}/storage/v0/${path}`, {
    ...init,
    headers: { ...init.headers, ...auth },
  });
  if (!response.ok) {
    const { error, detail } = await response.json();
    throw Object.assign(new Error(`${error}: ${detail}`), { error });
  }
  return response;
}

// Every file name in the area, a page at a time; the last page has no cursor.
async function listNames(area) {
  const names = [];
  let cursor;
  do {
    const query = cursor ? `?${new URLSearchParams({ cursor })}` : '';
    const page = await (await call(`areas/${area}/files${query}`)).json();
    names.push(...page.files.map((file) => file.name));
    cursor = page.cursor;
  } while (cursor);
  return names;
}

// The file's text, or null where the area holds no file by that name.
async function readText(area, name) {
  try {
    return await (await call(`areas/${area}/files/${name}`)).text();
  } catch (failure) {
    if (failure.error === 'no_such_file') return null;
    throw failure;
  }
}

await call('areas/notes', {
  method: 'PUT',
  headers: { 'content-type': 'application/json' },
  body: JSON.stringify({ account_keyed: false, version_keeping: false }),
});
await call('areas/notes/files/hello.txt', {
  method: 'PUT',
  headers: { 'x-acting-identity': 'anonymous', 'content-type': 'text/plain' },
  body: 'hello',
});
console.log(await listNames('notes'));
console.log(await readText('notes', 'hello.txt'));
console.log(await readText('notes', 'missing.txt'));
```

The write records `anonymous` as its acting identity. That label grants no access. The credential already selects the environment, so these calls need no environment header. Each run writes `hello.txt`. If the `notes` area was empty when you started, the example prints `[ 'hello.txt' ]`, `hello` and `null`.

A list answers `{ files, cursor }`, each file with the fields [File names, environments, and conditional writes](#file-names-environments-and-conditional-writes) shows. `listNames` passes each `cursor` back unchanged until a page comes without one.

A read of a missing file is refused 404 `no_such_file`, with the body [Storage response bodies](#storage-response-bodies) shows. `readText` answers `null` for that `error` alone, since an undeclared area is refused 404 too, as `undeclared_area`.

For a run on your machine, the developer signs in to the CLI once, then the [`provision` command](/cloud/guides/run-your-application-on-your-machine/#1-write-the-environment-file) supplies the backend's credential. For a complete public web app, use [A public upload service with no sign-in](/cloud/guides/build-a-public-upload-gallery/).

#### A minimal upload service

These six files make a service that keeps each signed-in user's files private in one area. It uploads, lists, and downloads the user's own files, and gives a native app a transfer grant for an upload. A test runs them. Put them in your application's folder. Then take the Storage and Account packages as [Add an entry to the library folder](/cloud/guides/use-the-library/#3-add-an-entry-to-the-library-folder) shows. The take command copies them into `lib/storage/` and `lib/account/` and runs `npm install`.

The take command requires `--entry`, for example `turnzero library take --origin https://dev.turnzero.ai --entry storage`. Call `read_library` with `entry: "storage"` and use the command form for your operating system from its `download` response, then take `account` the same way.

For offline tests, use Storage's `createStorageDouble` as [Use the other doubles](/cloud/guides/test-your-application-locally/#6-use-the-other-doubles) describes.

##### Signed-in service files

The platform's storage needs no `egress` entry; [the list is for outside hosts](/cloud/guides/author-the-manifest/#writing-the-egress-list). `manifest.json` declares sign-in and storage and records the two packages:

```json
{
  "manifest_version": 1,
  "services": [{ "kind": "accounts" }, { "kind": "object_storage" }],
  "health": "/health",
  "region": "usa",
  "egress": [],
  "audience": { "kind": "public" },
  "packages": [
    { "name": "account", "version": "0.24.0" },
    { "name": "storage", "version": "0.23.3" }
  ]
}
```

`package.json` installs the two packages from their copies under `lib/` and starts `src/main.mjs`:

```json
{
  "name": "files-service",
  "private": true,
  "type": "module",
  "scripts": {
    "start": "node src/main.mjs"
  },
  "dependencies": {
    "@turnzero/account": "file:lib/account",
    "@turnzero/storage": "file:lib/storage"
  }
}
```

`src/storage.mjs` builds the Storage client. The client makes its calls through the `transport` function, which sends each call to `TURNZERO_CLOUD_GATEWAY_URL`, or to `TURNZERO_CLOUD_API` where that is not set. It adds the credential from `TURNZERO_CLOUD_APP_TOKEN`. A deploy sets these settings, which [A deployed app's settings](/cloud/concepts/the-settings-a-deployed-copy-receives/) lists. The [`provision` command](/cloud/concepts/turnzero-command/#running-on-your-machine) writes them for a run on your machine, so the same files run in both places.

```js
// src/storage.mjs
import { StorageWireClient } from '@turnzero/storage';

export const AREA = 'uploads';

// Each call goes to the platform with the application's credential.
export function transport(path, init = {}) {
  const origin = process.env.TURNZERO_CLOUD_GATEWAY_URL || process.env.TURNZERO_CLOUD_API;
  return fetch(`${origin}${path}`, {
    ...init,
    headers: { ...init.headers, authorization: `Bearer ${process.env.TURNZERO_CLOUD_APP_TOKEN}` },
  });
}

export const storage = new StorageWireClient(transport);
```

`src/users.mjs` tells which user sent a request. It is the check from [Tell which user sent a request](/cloud/guides/add-sign-in-to-your-app/#3-tell-which-user-sent-a-request), which explains it:

```js
// src/users.mjs
import { makeVerifyClient } from '@turnzero/account';

// A deployed copy receives all three settings. A local run has no
// TURNZERO_CLOUD_REALM_KEYS, so the client is built without keys there and
// verifies through the platform's route.
const keys = process.env.TURNZERO_CLOUD_REALM_KEYS;
const accounts = makeVerifyClient({
  baseUrl: process.env.TURNZERO_CLOUD_API,
  credential: process.env.TURNZERO_CLOUD_APP_TOKEN,
  ...(keys ? { realmKeys: keys } : {}),
});

// The session token: the cookie's value from a browser, or the bearer from a native app.
function sessionOf(request) {
  const auth = request.headers.authorization ?? '';
  if (auth.startsWith('Bearer ')) return auth.slice('Bearer '.length);
  for (const part of (request.headers.cookie ?? '').split(';')) {
    // Spaces and tabs come off a pair and nothing else, so a name is read as it stands.
    let from = 0;
    let to = part.length;
    while (from < to && (part.charCodeAt(from) === 0x20 || part.charCodeAt(from) === 0x09)) from += 1;
    while (to > from && (part.charCodeAt(to - 1) === 0x20 || part.charCodeAt(to - 1) === 0x09)) to -= 1;
    const pair = part.slice(from, to);
    const at = pair.indexOf('=');
    if (at > 0 && pair.slice(0, at) === '__Host-turnzero_cloud_realm') return pair.slice(at + 1);
  }
  return null;
}

export async function userIdOf(request) {
  const verdict = await accounts.verifySession(sessionOf(request), {
    sessionHeader: request.headers['x-turnzero-cloud-session'] ?? null,
  });
  return 'user' in verdict ? verdict.user.id : null;
}
```

##### Signed-in request handler

`src/server.mjs` starts listening on `PORT` straight away. Then it declares the area with `mintArea`, naming the application from `TURNZERO_CLOUD_APPLICATION`. Until the declaration succeeds, every route returns 503, the health path included. Use the same application as any earlier `declare_storage_area` call for this area. The two settings must equal those in that call. Match `accountKeyed` to `account_keyed` and `versionKeeping` to `version_keeping`. Otherwise every start fails: the platform refuses with `differing_redeclaration`, which the client throws as `declarations_differ`.

Every route except `GET /health` answers 401 when no user is signed in. The other routes are `PUT /files/<name>` to upload, `GET /files` to list, `GET /files/<name>` to download, and `POST /grants/<name>`. The last one is the grant of [step 3 (Hand a browser or a native app a transfer grant)](#3-hand-a-browser-or-a-native-app-a-transfer-grant), for a web page or a native app. Each route reads and writes under `<user id>/<name>`, and lists only names with that prefix, so no user reaches another user's files. A write also records the user's id as the acting identity, which says who made it.

The upload route answers the file's address from `APP_PUBLIC_HOST`, the public hostname the platform injects. A request's `Host` names the platform's internal address for the environment, so an address built from it does not resolve outside the platform.

The download route sends each file as an attachment, with `x-content-type-options: nosniff`. A browser then saves an uploaded page or image instead of running it on your application's hostname. An `<img>` element still shows such an image, because `attachment` governs only what a browser does when it opens the file's address itself. Each response also ends when the request's abort signal fires, as the deploy's rules require.

```js
// src/server.mjs
import { createServer } from 'node:http';
import { AREA, storage, transport } from './storage.mjs';
import { userIdOf } from './users.mjs';

// A request's abort signal. The deployed runtime attaches its own signal to each
// request, and it aborts at the request's window. A local run has none of its own,
// and Node's request.signal can abort at a normal request end on some Node 24
// releases, so a local run's signal aborts when the response closes unfinished.
function abortSignalOf(request, response) {
  const own = Object.hasOwn(request, 'signal') ? request.signal : undefined;
  if (own) return own;
  const controller = new AbortController();
  response.once('close', () => {
    if (!response.writableFinished) controller.abort();
  });
  return controller.signal;
}

// Each user's files are kept under the user's id.
const pathOf = (user, name) => `${user}/${name}`;
const encodePath = (path) => path.split('/').map(encodeURIComponent).join('/');

async function readBytes(request) {
  const chunks = [];
  for await (const chunk of request) chunks.push(chunk);
  return new Uint8Array(Buffer.concat(chunks));
}

// This service answers each listed file's name, size, version, and content type.
async function listFiles(user) {
  const files = [];
  let cursor = null;
  do {
    const page = await storage.list(AREA, { prefix: `${user}/`, cursor });
    for (const file of page.names) {
      const { size, version, contentType } = file;
      files.push({ name: file.name.slice(user.length + 1), size, version, contentType });
    }
    cursor = page.cursor;
  } while (cursor);
  return files;
}

// A transfer grant for one upload, minted under the application's credential.
async function uploadGrant(user, name) {
  const response = await transport('/storage/v0/grants', {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({ area: AREA, name: pathOf(user, name), direction: 'upload', identity: user }),
  });
  const body = await response.json();
  if (!response.ok) return { status: response.status, body: { error: body.error } };
  const address = `${process.env.TURNZERO_CLOUD_API}/storage/v0/areas/${AREA}/files/${encodePath(pathOf(user, name))}`;
  return { status: 201, body: { address, grant: body.grant, expires_at: body.expires_at } };
}

let ready = false;

async function handle(request, response) {
  // End the response when the request is aborted (abortSignalOf, above).
  const signal = abortSignalOf(request, response);
  if (signal.aborted) {
    response.destroy();
    return;
  }
  signal.addEventListener('abort', () => response.destroy(), { once: true });
  const send = (status, body) => {
    if (response.destroyed) return;
    response.writeHead(status, { 'content-type': 'application/json' });
    response.end(JSON.stringify(body));
  };
  if (!ready) return send(503, { error: 'starting' });
  // A target that does not parse as a URL names no route, so it ends like any unknown path below.
  let pathname = '';
  try {
    pathname = new URL(request.url, 'http://localhost').pathname;
  } catch {}
  if (request.method === 'GET' && pathname === '/health') return send(200, { ok: true });
  const user = await userIdOf(request);
  if (signal.aborted) return;
  if (!user) return send(401, { error: 'sign_in_required' });
  if (request.method === 'GET' && pathname === '/files') return send(200, { files: await listFiles(user) });
  if (request.method === 'POST' && pathname.startsWith('/grants/')) {
    const grant = await uploadGrant(user, decodeURIComponent(pathname.slice('/grants/'.length)));
    return send(grant.status, grant.body);
  }
  if (!pathname.startsWith('/files/')) return send(404, { error: 'not_found' });
  const name = decodeURIComponent(pathname.slice('/files/'.length));
  if (request.method === 'PUT') {
    const contentType = request.headers['content-type'] ?? 'application/octet-stream';
    const bytes = await readBytes(request);
    if (signal.aborted) return;
    const { version } = await storage.put(AREA, pathOf(user, name), bytes, { identity: user, contentType });
    // The address a browser reaches: the public hostname, never the request's Host.
    const url = `https://${process.env.APP_PUBLIC_HOST}/files/${encodePath(name)}`;
    return send(201, { name, version, url });
  }
  if (request.method === 'GET') {
    try {
      const { bytes, meta } = await storage.get(AREA, pathOf(user, name));
      // An attachment, never shown in place, so an uploaded page cannot run on this hostname.
      response.writeHead(200, {
        'content-type': meta.contentType,
        'content-disposition': 'attachment',
        'x-content-type-options': 'nosniff',
      });
      return response.end(bytes);
    } catch (error) {
      if (error.code === 'no_file') return send(404, { error: 'no_file' });
      throw error;
    }
  }
  send(405, { error: 'method_not_allowed' });
}

export async function startServer(port) {
  const server = createServer((request, response) => {
    handle(request, response).catch((error) => {
      const refused = error instanceof URIError || error.code === 'invalid_name';
      if (!refused) console.error(error);
      if (response.destroyed) return;
      if (!response.headersSent) response.writeHead(refused ? 400 : 500, { 'content-type': 'application/json' });
      response.end(JSON.stringify({ error: refused ? 'invalid_name' : 'internal' }));
    });
  });
  await new Promise((resolve) => server.listen(port, resolve));
  // Declare the area before any file route runs. Every start restates the same declarations.
  await storage.mintArea(AREA, { accountKeyed: false, versionKeeping: false, application: process.env.TURNZERO_CLOUD_APPLICATION });
  ready = true;
  return server;
}
```

##### Start the signed-in service

`src/main.mjs` starts the server on `PORT`:

```js
// src/main.mjs
import { startServer } from './server.mjs';

await startServer(Number(process.env.PORT ?? 8080));
```

A page on the application's hostname uploads with `fetch('/files/photo.png', { method: 'PUT', body: file })`, and the browser sends the user's sign-in cookie with it. On Turn Zero Cloud, a request body can hold up to 32 MiB ([Limits and metering](#4-limits-and-metering)). This sample reads the whole body before sending it to storage. Set a smaller limit in your upload route to bound memory use.

#### In a project the scaffold wrote

A project that `turnzero scaffold --origin https://dev.turnzero.ai` wrote has the same two files in a different form. Its `src/server.mjs` exports `createAppServer`, and its `src/main.mjs` starts that server. Add the file routes above as one more branch of that server's request handler, before its 404. Then declare the area in `src/main.mjs` once the server listens, as `startServer` does above. Until the declaration has answered, have every route answer 503, the health path too, as the `ready` flag does above. A deploy then counts the copy as ready only once its area is declared.

#### A public upload service with no sign-in

<div id="public-service-files"></div>
<div id="public-routes-and-limits"></div>
<div id="public-request-handler"></div>
<div id="storage-limits-and-file-safety"></div>
<div id="the-gallery-page"></div>
<div id="check-the-public-service"></div>

Use [Build a public upload gallery](/cloud/guides/build-a-public-upload-gallery/) for the complete service, gallery page and check script. It includes the Storage-package and fetch-only forms, with public access, limits and cleanup explained beside the files.

##### The starter without the library

Use [The starter without the library](/cloud/guides/build-a-public-upload-gallery/#the-starter-without-the-library) to write the gallery with `fetch` alone before signing in. Declaring storage and deploying still need a Cloud sign-in.

#### File names, environments, and conditional writes

The client calls the storage routes for you, at `/storage/v0/areas/{area}/files/{name}` on the platform's origin. [File routes](/cloud/backend-packages/storage/#file-routes) on the Storage package page lists every answer each route gives, with its status.

These are the platform's file routes, called with the credential and environment that [step 2 (Put, fetch, list, delete)](#2-put-fetch-list-delete) describes. They are separate from the sample application's own `/files` routes:

| Route | Successful response |
| --- | --- |
| `PUT /storage/v0/areas/{area}/files/{name}` | JSON with `name`, `area`, `size`, `content_type`, `created_at`, `last_written_at`, `actor`, and `version`, plus the `ETag` header. |
| `GET /storage/v0/areas/{area}/files/{name}` | The file's bytes. Add `?meta=1` to receive those same fields as JSON instead. |
| `DELETE /storage/v0/areas/{area}/files/{name}` | JSON with `deleted`, including when the file is already absent. |
| `GET /storage/v0/areas/{area}/files?prefix=&cursor=&limit=` | A JSON object with `files`, an array of those file objects, and an optional `cursor` for the next page. |

A list returns an object, not a bare array. Its file fields use the wire's snake_case names, including `content_type`. For example:

```json
{
  "files": [{
    "name": "report.txt",
    "area": "documents",
    "size": 123,
    "content_type": "text/plain",
    "created_at": "2026-01-01T00:00:00.000Z",
    "last_written_at": "2026-01-01T00:00:00.000Z",
    "actor": "user-123",
    "version": "example-version"
  }],
  "cursor": "<opaque cursor>"
}
```

Pass the returned `cursor` unchanged in the next request's `cursor` query parameter, keeping the same prefix and environment. Files are in name order. On the last page, `cursor` is absent; an empty listing is `{"files": []}`. The Storage client's `list` result names it `cursor` too and uses camelCase file fields, as [The client](/cloud/backend-packages/storage/#the-client) describes.

The file name is taken exactly from the path, slashes included. A name is refused 400 `invalid_request` when one of its segments, the parts a slash or a backslash separates, is `.` or `..`.

A write is also refused 400 `invalid_request` when the name holds a backslash, or when any segment ends with a dot, the last one included. This is because the storage service may keep such a name under another name. Separate segments with a forward slash, and end no segment with a dot. A file already stored under such a name can still be read, listed, and deleted.

Every call needs the account's credential, and reaches one environment's part of the area. The application's platform credential reaches its own environment. A header naming the other environment is refused 403 `environment_mismatch`. A session or a [minted token](/cloud/guides/mint-a-token/#1-mint-it) belongs to no environment. So a call with either names the environment in the header `x-turnzero-cloud-environment`, as `development` or `production`, and is refused 400 `environment_required` without it.

A file's name is also refused 400 `invalid_request` when it is too long for the store. The store holds a name of at most 1,024 characters, counted with the account, area, and environment the file is stored under. A write and an upload grant's request count UTF-16 code units, so an emoji counts as two. A read, a metadata read, a delete, and a download grant's request count code points, so a stored file stays reachable. The refusal's `detail` gives the room left for the name in that area and environment.

A file's name is refused the same way when it has too many folders. The store holds a name of at most 254 segments, a segment being a part between slashes, and the account, area, and environment take three of them. A write and an upload grant's request count every part. A read, a metadata read, a delete, and a download grant's request count the parts that are not empty and allow one more, so a stored file stays reachable. The refusal's `detail` gives the segments left for the name.

Set `X-Acting-Identity` to label who made the write. The application's credential and your own user check control access. The client sends the `identity` you pass. A write without it, and with no grant that sets one, is refused 400 `identity_required`. For a grant upload, omit the header or use the grant's identity. The client refuses such a write before sending it, with `no_identity` and a message that opens `unattributed write`. An upload from a visitor who is not signed in still passes one: any nonempty string of your own, such as `anonymous`.

To replace a specific version, send it in `If-Match`. A missing file returns 404 `no_such_file`. A different current version returns 412 `version_mismatch`. To create a file only if the name is free, send `If-None-Match: *`. An existing file returns 412 `version_mismatch`. Send one condition per write. If you send both, `If-None-Match: *` takes precedence.

[A gallery or feed, newest first](/cloud/backend-packages/storage/#a-gallery-or-feed-newest-first) shows how to keep each caption in a Database row, or how to name files so the list shows the newest first.

#### The client's methods

`StorageWireClient` is built over a transport that adds your credential, as [A minimal upload service](#a-minimal-upload-service) shows; [The client](/cloud/backend-packages/storage/#the-client) lists its methods, their results, and their refusals.

The delete method is `delete_(area: string, name: string, { identity }?: { identity?: string }): Promise<void>`. Pass a nonempty `identity` even though the type makes the options optional; without it, the client rejects with `no_identity` before sending a request.

For an already declared `uploads` area and the client above, `await storage.delete_('uploads', 'anonymous/photo.png', { identity: 'anonymous' });` deletes that file in the credential's environment. The promise resolves with no return value, including when the file is already absent. A service acting for a signed-in user passes that user's id and checks access before deleting.

### 3. Hand a browser or a native app a transfer grant

A transfer grant is a short-lived credential for one file. It lets a client other than your backend upload or download that file directly from storage, so the file's bytes do not pass through your backend. A web page can use one in the browser. The file routes accept a `PUT` or `GET` with a grant from a page on any origin. Send the grant as a bearer token. The request needs no cookie. A native app uses one the same way.

Keep grants out of logs, links, and markup. Anyone who has a download grant can use it until it expires.

For a private photo upload, see [Upload a photo from a phone app](#upload-a-photo-from-a-phone-app).

Your backend mints each grant after its own user check. Your backend's own routes, as in [A minimal upload service](#a-minimal-upload-service), are still how files are listed and deleted.

The sample's `POST /grants/<name>` route mints an upload grant after the same user check. It calls `POST /storage/v0/grants` under the application's platform credential or a token for that application. Name the environment as in step 2 (Put, fetch, list, delete); the grant then reaches only that environment's files. An account session or an account-scoped token cannot issue a grant on this route. They use `mint_upload_grant` instead ([An upload grant from your tool](#an-upload-grant-from-your-tool)). Send JSON with:

- `area` and `name`;
- `direction`: `upload` or `download`;
- `identity`: a nonempty acting identity, fixed for the grant;
- `max_bytes`, for an upload only: a positive integer up to the platform's upload-grant limit. Leave it out to use that limit. The upload-grant limit can be lower than the request limit.

The response returns `grant` once, with `id`, `area`, `name`, `direction`, `identity`, `max_bytes`, and `expires_at`. The page or the app sends the grant in the `authorization` header, as `Bearer <grant>`. With an upload grant, a `PUT` to the file's address uploads that one file; with a download grant, a `GET` downloads it. The grant is refused for other files, the other direction, and other routes.

In a page, the upload is two calls: the sample's grant route, then the `PUT` to the address it returns.

```js
async function upload(file) {
  const grantReply = await fetch(`/grants/${encodeURIComponent(file.name)}`, { method: 'POST' })
    .catch(() => null);
  const ticket = grantReply?.ok ? await grantReply.json().catch(() => null) : null;
  if (!ticket?.address || !ticket?.grant) throw new Error('Could not prepare the upload.');

  const reply = await fetch(ticket.address, {
    method: 'PUT',
    headers: { authorization: `Bearer ${ticket.grant}` },
    body: file,
  }).catch(() => null);
  if (!reply) throw new Error('Upload unconfirmed. Check the file before trying again.');
  if (!reply.ok) throw new Error(`Upload returned HTTP ${reply.status}. Check the file before trying again.`);
  const stored = await reply.json().catch(() => null);
  if (!stored?.version) throw new Error('Upload unconfirmed. Check the file before trying again.');
  return stored;
}
```

Show the error message if the upload fails. Show “Uploaded” only after the function returns the stored file's metadata.

If the reply is lost or the grant is spent, check the same file through your backend's `GET /files/<name>` route. Check that it holds the intended contents before trying again. Follow [Limits and metering](#4-limits-and-metering) and [Refusals](#refusals) for the size limit, expiry and failed grants.

An upload grant is refused for a `name` that a write refuses, as step 2 (Put, fetch, list, delete) describes. A download grant for a file already stored under such a name is issued as usual.

An upload grant allows one successful write. After a refused write, the grant normally stays usable until it expires. If the platform cannot restore the grant, it stays spent even though the write was refused. A download grant allows repeated reads until it expires. A conditional write's `If-Match` or `If-None-Match` still applies to an upload under a grant.

A grant lasts five minutes by default, and platform staff can change the default. Send the whole upload body before the grant expires. The server checks expiry after receiving the body and before writing the file. Request the grant just before sending the file, especially on a slow connection.

A grant also ends when its application or account is deleted. The storage routes then refuse it within the time [When an ending takes effect](/cloud/concepts/sign-in-sessions-and-tokens/#when-an-ending-takes-effect) gives. While the account is suspended, a grant is refused 403 `account_suspended` on its file route, and the backend cannot mint a new one. But suspension ends no grant: an unexpired grant works again once platform staff reinstate the account.

A platform credential and an application-scoped token each reach only their application's areas. Neither can issue a grant for another application's area.

#### Upload a photo from a phone app

Start with the [signed-in upload service](#a-minimal-upload-service) for photos private to each user. Its backend verifies the user's native bearer and keeps the file below that user's ID. The area's settings give no per-user access. Your backend must check the signed-in user on every file route. For a gallery where every visitor can see every file, choose the [public gallery guide](/cloud/guides/build-a-public-upload-gallery/).

Use your app's photo picker to select an image. If the person cancels or denies photo access, return to the current screen. Read the selected file as bytes using the app's file API. Pick a fresh name for each new photo and keep it until you confirm the result. Use the [native sign-in module](/cloud/guides/sign-in-from-a-native-app/#5-call-the-backend-with-the-bearer) to call your own backend. On a debug build, use your development hostname when development is on.

To send the bytes through your backend, use the signed-in client to call `PUT /files/<name>`. Have the route enforce your byte limit as it reads and return 413 for an oversized body. To send the bytes straight to storage, first call the sample's `POST /grants/<name>`. The function below uses only the returned grant for the storage request.

```js
export async function uploadPhoto(signedIn, uploadName, bytes, mediaType) {
  const route = '/grants/' + encodeURIComponent(uploadName);
  const prepared = await signedIn.call(route, { method: 'POST' });
  if (!prepared.ok) throw new Error('Could not prepare the photo upload.');
  const ticket = await prepared.json().catch(() => null);
  if (!ticket?.address || !ticket?.grant) throw new Error('Upload grant was unreadable.');

  const result = await fetch(ticket.address, {
    method: 'PUT',
    headers: {
      authorization: 'Bearer ' + ticket.grant,
      'content-type': mediaType,
      'if-none-match': '*',
    },
    body: bytes,
  }).catch(() => null);
  if (result?.status === 413) throw new Error('Choose a smaller photo.');
  if (!result?.ok) throw new Error('Check the stored photo before trying again.');

  const stored = await result.json().catch(() => null);
  if (!stored?.version) throw new Error('Check the stored photo before trying again.');
  return stored;
}
```

Add `max_bytes` to the request your backend makes to issue an upload grant. A photo over that limit returns 413 `request_too_large` and stores nothing. The sample's `If-None-Match: *` creates a file only at an unused name. An existing file returns 412 `version_mismatch`.

With either upload route, check the bytes before sharing the photo. Set the content type from the format your app confirms when it serves the file. Set a storage limit per user or regularly clear files your app no longer needs. A direct upload can land before the app records it. Decide how to find and remove files left by failed, abandoned or replaced uploads.

Try canceling the picker, choosing a photo over the limit, and losing the upload reply. Use a synthetic photo and two test users in development. Check that the first user can upload and read the intended bytes and that the second user cannot list or read the photo.

If a reply is lost, check `GET /files/<name>` through the signed-in backend before requesting another grant. Use the original `uploadName`. Storage returns the full name, including the user ID, and the backend adds that ID itself. Show the upload as complete after you confirm the intended file and its version.

### 4. Limits and metering

Turn Zero Cloud sets the request body limit at 32 MiB and the list page limit at 100 files. Platform staff can change either. An upload grant can have a lower byte limit than the request itself.

A list request takes `prefix`, `cursor`, and `limit`. The route rounds a fractional `limit` down, caps larger values at the page limit, and uses the page limit when `limit` is missing, unreadable, or less than one.

For the next page, keep the same area, environment and prefix. Pass the returned `cursor` exactly as given. It does not expire. You can change the `limit`. The cursor stays valid after a new deployment.

The cursor marks the next page's first file by name. If that file has been deleted, the page starts at the next name, without a refusal. A file added with a name before the cursor's name does not appear on later pages. To include those additions, list again from the first page. A listing does not freeze the files while you read its pages.

The cursor includes the next file's name. Give it only to people who may see the names in that listing. Check their access again on the next request.

The platform checks the cursor's format and a value the cursor carries. It calculates that value from the account, area, environment, and prefix. It also checks that the cursor's file name lies under the prefix and passes the rules for reading a stored file. So a file stored under a name a write now refuses still appears. The calculated value excludes the file name, so a change to that name only moves the cursor within the same listing.

A cursor from production cannot be used on development, or the reverse. A cursor for another account, area, environment, or prefix is refused 400 `invalid_cursor`, as is a repeated `cursor` parameter or another malformed cursor. List again from the first page.

For each file operation, the platform records its bytes, outcome, and time against the application. When the application passes its stored-data ceiling, puts are refused `usage_over_quota`, and reads, lists, and deletes keep working ([What an `over` state stops](/cloud/guides/plan-and-usage/#5-what-an-over-state-stops)). After freeing space, wait for a successful stored-data check to clear the refusal before uploading again. Deleting the account removes its areas and files, and keeps the record of usage.

### 5. Declare or remove an area outside the manifest

Outside the manifest, call `declare_storage_area` with:

- `name`: a letter or digit, then letters, digits, hyphens, or underscores, up to 64 characters. You cannot declare a new area with a name beginning `export-` or `deploy-`, or with `images-` followed by an application ID in UUID form. Those names are reserved and return `area_name_reserved`;
- `account_keyed`: `true` or `false`;
- `version_keeping`: `false`;
- `application`: the application the area belongs to. `list_applications` returns the identifier, and a call without it is refused 400 `application_required`.

You can also declare an area with `PUT /storage/v0/areas/{area}` and a JSON body containing the same members. On that route, a call under the application's platform credential or a token for that application can leave out `application`, and the area goes to that application. A call under a session or an [account-scoped token](/cloud/concepts/glossary/#account-scoped-token) must give it, or is refused the same way.

The Storage package's `mintArea` forwards `application` only when your code supplies it. The server examples above read that value from `TURNZERO_CLOUD_APPLICATION`.

A server that mints its area at each start needs no `declare_storage_area` call, so the declarations live in one place. For an area the manifest's `areas` lists, that place is the manifest, and the area needs neither the call nor a mint. Where the mint and the call both run, they must name the same declarations, or the server's start fails with `declarations_differ`.

The client spells the two declarations in JavaScript's style: `mintArea` takes `accountKeyed` and `versionKeeping`, and sends them as `account_keyed` and `version_keeping`. A tool's call or an HTTP request names the wire's spelling.

Declaring an area again with the same declarations changes nothing. Different declarations, including a different application, are refused.

`version_keeping: true` is refused: the platform keeps no earlier versions of a file. The platform records `account_keyed`, but it does not separate files by end user, so its value changes nothing about who can read a file. An area's declarations are fixed, so a different value needs a new area.

`list_storage_areas` returns the account's areas. It is a management action, not a storage route, and no storage route lists areas. The declaration route `PUT /storage/v0/areas/{area}` and `list_storage_areas` take no environment header.

The signed-in application page uses `list_storage_files` to list one page of an area's files and `read_storage_file` to read one file's fields, never its content. Scripts can call both management actions over HTTP with a bearer credential that reaches the area. Customer MCP connections do not list these actions.

Pass `application` and an `area` bound to it; `read_storage_file` also takes `name`. If you omit `environment`, both actions use the application's deploy target, where an upload with no environment writes. The file listing action and the storage listing route accept each other's cursors for the same area, environment and prefix.

To remove an area that contains no file in either environment, call `declare_storage_area` with its `name` and `remove: true`. It removes the area and frees the name, so a later declaration under that name creates a new area. Removing an area that still contains a file is refused `area_not_empty`, so delete its files in both environments first. Only the account can remove an area, under a session or an account-scoped token. An application-scoped token is refused by name.

Every area belongs to one application, and none belongs to two or to none. Deleting an application deletes its areas and every file in them.

### 6. The deploy area, and deploying from an area of your own

A deploy's zip goes to the application's deploy area, `deploy-<application id>`, which the platform creates and keeps. [Deploy from your computer](/cloud/getting-started/deploy-an-application/#3-build-and-upload-the-artifact) shows the `turnzero deploy --origin https://dev.turnzero.ai` command that uploads it. Only a deploy's short-lived upload grant reaches its files. The command alone receives it, from the call that prepares the upload. Your session, your tokens, and the application's platform credential are refused 403 `area_scope_refused` there.

A file in the deploy area older than a day is deleted at the next daily cleanup. The cleanup keeps a file saved by `deploy_files` while either environment serves or is deploying a version that lists it ([Deploy from your computer](/cloud/getting-started/deploy-an-application/#deploying-from-a-chat-whose-shell-cannot-reach-the-platform)). The area's bytes count toward your application's stored data, and an export leaves the area out.

You can send the deploy grant's upload again with the same zip, for example after a response was lost. After the first upload has landed, and until the grant expires, a repeat gets status 200 and nothing is written. The response gives the file's `name`, `area`, `size`, and `sha256`, with no `version` and no `ETag`. Different bytes are refused `transfer_grant_spent`. When the command prepares a new upload, its `deploy` call cancels the previous upload if its deploy has not started.

The prefix `deploy-` is reserved: a new area whose name begins with it is refused 400 `area_name_reserved`. An area you declared under the prefix before it was reserved keeps its files and your access.

The `artifact` form is the route that needs no turnzero command. A script of your own deploys from an area of its own. It uploads with one of the two `commands` that `mint_upload_grant` returns, which need no turnzero command, or with the `put` command, as [An upload grant from your AI assistant](#an-upload-grant-from-your-tool) describes. Or it uploads under a minted token, with the header naming the environment the deploy goes to and an acting identity, as [An upload under a minted token](#an-upload-under-a-minted-token) shows.

That script then calls `deploy` with `artifact`: the area, the file name, and the SHA-256 hash ([Deploy from your computer](/cloud/getting-started/deploy-an-application/)). Set `artifact.environment` to the environment holding the ZIP; if omitted, it defaults to the environment the deploy goes to.

#### An upload grant from your tool

To upload one file from a shell, your AI assistant calls the management action `mint_upload_grant` instead of keeping a token in the shell. It takes:

- `application`, and an `area` bound to that application;
- `name`, the file's name in the area;
- `environment`, optional: left out, it is the environment a deploy goes to, production on an application with one environment and development on one with two;
- `identity`, optional: the acting identity, `"deploy"` when you leave it out;
- `local_path`, optional: the file on your machine, as an absolute path or one relative to the folder the upload command runs in. Where you leave it out, the file is the one whose name is the last segment of `name`, in that folder.

On an application with one environment, leaving `environment` out puts the file beside your live application's own files. Name `development` for a test or seed file, so it stays with the data your local runs use.

The platform never reads the file at `local_path`: the upload command reads it on your machine. A `local_path` a shell would change in the upload command is refused 400 `invalid_request`, and nothing is minted. Such a path has a control character, a double quote, `$`, a backtick, `%`, `!`, `&`, `|`, `<`, `>`, `^`, a typographic double quote, a doubled backslash, or a trailing backslash. PowerShell passes a path that has no space to `turnzero.cmd` without its quotes, and `cmd` then reads `&`, `|`, `<`, `>`, and `^` as command syntax. So those five are refused on every operating system.

`mint_upload_grant` also refuses a `local_path` that is `~` alone or starts with `~/` or `~\`, before minting anything. It returns 400 `invalid_request`. Name your home folder in full: the upload command does not expand `~`. A name such as `~draft.txt` is admitted if it meets the other path rules.

The response gives the grant, its expiry, its byte limit, the file address and the following commands. The commands carry the grant. Keep the response and commands private while the grant can still write the file.

The four `command` and `command_npx` forms, including their Windows forms, are returned only for file names the turnzero command can upload. `commands.curl` and `commands.powershell` are always returned. If the four forms are absent, use one of those two commands.

- `command_npx` and `command_npx_windows`, the `put` command through npx for macOS/Linux and Windows, with no global installation needed;
- `command` and `command_windows`, the installed forms of the [turnzero command](/cloud/concepts/turnzero-command/), using `turnzero` and `turnzero.cmd`;
- `commands`, two upload commands that need no turnzero command: `commands.curl`, run in a shell such as bash with curl 7.76 or later, and `commands.powershell`, run in Windows PowerShell. Run `curl --version` to read its version on the first line.

Your AI assistant first runs `command_npx`, or `command_npx_windows` on Windows, once, exactly as returned, before `expires_at`. If npx cannot run here, use the installed form when `turnzero --version` responds.

For a deploy with no usable command, use `deploy_files` within its limits, then the [upload route](/cloud/getting-started/ways-to-deploy/#upload-a-zip-without-the-turnzero-command) past them. For an upload, use the returned curl or PowerShell command. Install the turnzero command only if the person wants to keep it.

The `put` command reads the grant from standard input, never from an argument. Each of the two `commands` sends only the grant, as the bearer token, because the grant already fixes the environment and the identity. All of them read the same file on your machine.

This is `command` for a call that names the area `artifacts` and the name `app.zip`, with `<grant>` where the call's own grant goes. A test checks that it matches the upload command the platform builds:

```text
echo <grant> | turnzero put --origin https://dev.turnzero.ai --area artifacts --name app.zip --path "app.zip"
```

If your AI assistant is connected to a platform other than https://turnzero.ai, the returned command includes `--origin` with that platform's address.

After its version line, the command prints one line that opens with `put:` and gives the file as the area stores it, as JSON: its `name`, `area`, `size`, `version`, `content_type`, and `last_written_at`. It ends with one of three statuses:

- 0: the file was written;
- 3: nothing was written, as on a refusal such as `transfer_grant_spent`: a write that lands spends the grant, so a second run after it is refused;
- 2: the outcome is unknown, so the file may have been written. Check the file before requesting a fresh grant.

The returned `commands.curl` uses `--fail-with-body` and sets no time limit of its own. The whole upload must arrive before the grant's `expires_at`, five minutes after minting by default. Request the grant just before uploading. Its outcomes differ from the `put` command's:

- Exit 0 with the stored file's JSON confirms the upload.
- Exit 22 means an HTTP status of 400 or above. Curl still prints the response body. For a platform refusal, read its `error` and `detail` and follow the remedy.
- Exit 28 means a timeout. It gives no confirmation: the file may have been written. Check the file before requesting a fresh grant.
- Another nonzero exit also gives no confirmation. Check the file before requesting a fresh grant.

If the answer is missing or comes from outside the platform, check the same area, environment and filename with an authorized read. If the intended file is already there, the upload is done. If it is still missing or unchanged, mint a new grant only if the upload is still needed.

For a new file, add `-H 'If-None-Match: *'` to `commands.curl`. In `commands.powershell`, add `'If-None-Match' = '*'` to the existing `-Headers` hashtable. If the file already exists, the write returns 412 `version_mismatch`. For a replacement, keep `If-Match` with the file's version.

For a deploy whose uploads repeatedly time out, use the [turnzero command](/cloud/getting-started/deploy-an-application/#upload-and-start-through-the-command) where it can run. Otherwise, follow [When to ask the person](/cloud/getting-started/ways-to-deploy/#when-to-ask-the-person), giving them the exact command you cannot complete.

The response has none of `command`, `command_windows`, `command_npx`, and `command_npx_windows` where the name contains a character that the `put` command cannot pass unchanged through every shell. A space is the common case. The `put` command can carry a name of up to 1,024 characters made of letters, digits, `.`, `_`, `-`, and `/`, starting with neither `-` nor `/`. The response's `detail` then says so, and your AI assistant runs `commands.curl` or `commands.powershell`, which read the same file.

The `put` command sends the file as it is, in one write, and follows no redirect. A write of a name that is already stored replaces that file.

In Windows PowerShell 5.1, `Invoke-WebRequest` needs `-UseBasicParsing`, and `commands.powershell` includes it.

The grant is an upload grant like any other: one file, spent by the one write that lands, and refused on every other route. A second write after that one landed is refused `transfer_grant_spent`, even with the same bytes. After a refused write, the grant normally stays usable until expiry. If the platform cannot restore it, it stays spent. The session, an account-scoped token, and a token for that application can call the action. The application's platform credential cannot, and the backend mints on `POST /storage/v0/grants` instead.

#### An upload under a minted token

The samples below show an upload without the turnzero command. They upload `app.zip` with a minted token into an area of your own named `artifacts`, for a script of your own that deploys with `artifact`. The token is in the environment variable `TURNZERO_CLOUD_MINTED_TOKEN`, and `deploy-tool` is the acting identity.

With curl 7.76 or later, from a shell. Here curl reads the `Authorization` header from standard input, so the token never appears in curl's arguments.

```bash
printf 'Authorization: Bearer %s' "$TURNZERO_CLOUD_MINTED_TOKEN" | curl --fail-with-body --upload-file app.zip \
  -H @- \
  -H "x-turnzero-cloud-environment: production" \
  -H "X-Acting-Identity: deploy-tool" \
  -H "Content-Type: application/zip" \
  "https://dev.turnzero.ai/storage/v0/areas/artifacts/files/app.zip"
```

With Node.js, saved as `upload.mjs` and run with `node upload.mjs`.

```js
import { readFile } from 'node:fs/promises';

const response = await fetch('https://dev.turnzero.ai/storage/v0/areas/artifacts/files/app.zip', {
  method: 'PUT',
  headers: {
    authorization: `Bearer ${process.env.TURNZERO_CLOUD_MINTED_TOKEN}`,
    'x-turnzero-cloud-environment': 'production',
    'x-acting-identity': 'deploy-tool',
    'content-type': 'application/zip',
  },
  body: await readFile('app.zip'),
});
console.log(response.status, await response.text());
if (!response.ok) process.exit(1);
```

## Expected result

The service's `PUT /files/<name>` returns 201 with the name, the version, and the file's address on `APP_PUBLIC_HOST`. `GET /files` lists the signed-in user's own files alone, each with its name, size, version, and content type, and a request without a session answers 401. `POST /grants/<name>` returns the grant once with its `expires_at` and the address the page or the app uploads to.

The public service's `POST /files` returns 201 with the name it chose, the version, and the file's address, with no session. Its `GET /files` lists every visitor's files a page at a time, each with an absolute `url` built from `APP_PUBLIC_HOST`, and returns the page's `cursor`. An upload outside its bounds answers 415, 413, or 429 and stores nothing.

When the manifest's `object_storage` entry lists areas, the submission returns each area in `storage_areas`, with its `outcome` and file address ([the receipt table](/cloud/guides/author-the-manifest/#expected-result)). `declare_storage_area` returns the `area` and an `outcome`, `created` for a new area or `unchanged` when the same declarations were repeated. Its `detail` gives the area's whole file address, `https://dev.turnzero.ai/storage/v0/areas/<area>/files/<name>`, and `list_storage_areas` then lists the area with its declarations and its application.

A `PUT` on a file route returns 200, with the file's version in the `ETag` header and its metadata as JSON; the package's `put` returns that version. `mint_upload_grant` instead returns the upload grant once, with the file's `address` and the upload commands. It does not upload the file. Run a returned command as given; a successful `put` prints the stored file's metadata on a line opening with `put:` and exits with status 0. A file written from development is listed from development and absent from production.

A file's version is opaque. The platform's is an HTTP entity tag that keeps its double quotes, so the JSON string holds them too. Send the quoted version back unchanged in `If-Match`. For a create-only write, send `If-None-Match: *`.

`declare_storage_area` with `remove: true` returns `outcome: removed` with the `area` as it was, or `outcome: unchanged` with `area: null` when no area has that name.

## Refusals

See the [refusals reference](/cloud/reference/refusals/) for other platform errors.

### Storage response bodies

Storage's own refusals return JSON with `error` and `detail`. For example, a request for a missing `photo.png` in a declared `uploads` area returns status 404 with a body like this:

```json
{
  "error": "no_such_file",
  "detail": "No file \"photo.png\" in \"uploads\"."
}
```

The platform's credential guard can refuse a request before it reaches storage. Those responses also include `contract_version`, for example a 401 `authentication_required`.

Handle either form by its `error` value. The `detail` text explains it for a person and can change; do not match that text in code. Storage's own refusals can add fields. For example, `version_mismatch` adds `current_version`, and some refusals add `credential_kind` or `scope`.

When using `StorageWireClient`, handle its own `code` instead, as [Failures](/cloud/backend-packages/storage/#failures) explains. A write or deletion can take effect before storage returns `storage_error`. Retry a read. After a failed write or deletion, read the file and its current version to check whether the change took effect. If a replacement is still needed, use a condition that protects the current version. If it keeps failing, report the refusal with its reference. [Deploy from your computer](/cloud/getting-started/deploy-an-application/#refusals) lists the deploy's refusals, including the artifact checks.

### Refusal causes and remedies

For grant and sign-in errors, see [Transfer grant and sign-in refusals](#transfer-grant-and-sign-in-refusals).

| Refusal | Status | Cause | Remedy |
| --- | --- | --- | --- |
| `invalid_request` | 400 | A member or header is malformed; `detail` names it. For example, an area `name` breaks step 5 (Declare or remove an area outside the manifest). A grant request may break step 3 (Hand a browser or a native app a transfer grant). A path containing a NUL character (U+0000) is refused too, as is a declaration or grant body containing one or an unpaired UTF-16 surrogate; `detail` then names the character. A write, or an upload grant, whose file name holds a backslash or a segment that ends with a dot is refused too. So is a file name past 1,024 characters with its account, area, and environment. A write or an upload grant counts UTF-16 code units, and a read, a metadata read, a delete, or a download grant code points. So is a file name past 254 segments with its account, area, and environment, a segment being a part between slashes. | Correct the named member, or remove the character `detail` names, and send the request again. For a file name, separate segments with a forward slash, and end no segment with a dot, and keep it within the room `detail` gives. |
| `differing_redeclaration` | 409 | The area was redeclared differently, such as for another application. For a listed area, `submit_manifest` names the refusal at its path in a `manifest_invalid` line. It returns 409 only if another declaration lands while it records the area. | Match the existing declaration or choose a new area name. For a manifest refusal, correct its storage entry and resubmit. The refusal lists declarations that took effect. You can undeclare and redeclare an empty area declared separately. |
| `environment_required` | 400 | A session or minted token called a file route, the file list, or the grant mint without `x-turnzero-cloud-environment`, or with a value that names neither environment. | Send the header with `development` or `production`. |
| `environment_mismatch` | 403 | A call under an application's platform credential named the other environment. | Drop the header, or name the credential's own environment. |
| `identity_required` | 400 | A `PUT` or `DELETE` had no `X-Acting-Identity` header and no grant sets one. | Send the acting identity on each write without a grant. |
| `area_name_reserved` | 400 | The name is reserved for a platform area. | Choose a name that does not begin with `export-` or `deploy-`. Do not use `images-` followed by an application ID in UUID form. |
| `grant_identity_fixed` | 400 | An upload grant already sets the acting identity, and the request sent a different one in `X-Acting-Identity`. | Omit the header or send the grant's identity. |
| `undeclared_area` | 404 | Your account has no area by that name, on a file route, the grant mint, or `mint_upload_grant`. | Declare it with `declare_storage_area` or `PUT /storage/v0/areas/{area}`. For a new area, choose another name if it begins `export-` or `deploy-`, or is `images-` followed by an application ID in UUID form. |
| `area_scope_refused` | 403 | The credential cannot reach the area, which belongs to another application. On `mint_upload_grant`, the area belongs to an application other than the one named. On an application's deploy area, every credential of yours is refused, and so is a grant from `mint_upload_grant` or the grant route. The platform's export area refuses uploads and upload-grant requests. | For uploads, choose an area other than the export area. Call under the application's platform credential, a token for that application, or an account-wide credential. For `mint_upload_grant`, name the area's own application. For the deploy area, call `deploy_command` with the application, and run the deploy command it returns once. |
| `application_other_account` | 403 | An area declaration named an application that another account holds, not the account the call is signed in as. The `detail` names the account the call acted as and nothing of the other one. | Compare `turnzero whoami --origin https://dev.turnzero.ai` with `read_account` over your AI assistant's connection, and declare the area from the one signed in to the account that holds the application. |
| `no_such_application` | 404 | The storage area declaration names an application the platform did not find for this account. | Check the app ID against `list_applications` for the signed-in account, then use the correct ID. |
| `no_such_file` | 404 | A `GET` named a file the area does not contain, or a put named a version for a missing file. Under an export's download grant, a stored file created after the export listed its files returns the same refusal. | For an unavailable export download, [request a new export and download it once completed](https://dev.turnzero.ai/turnzero/guides/export-or-delete-your-account/#download-the-export). Otherwise, check the name and environment, then look for the path in `detail` in the area's file listing. For a put, use `If-None-Match: *` to create only if the name is still absent. An unconditional put creates or replaces the file. Check its current version before replacing it. |
| `request_too_large` | 413 | The body is larger than the request limit or the grant's `max_bytes`. | Send a smaller request. The backend grant route accepts `max_bytes` up to the platform's upload-grant limit. That limit can be lower than the request limit. The management tool `mint_upload_grant` sets the grant's limit for you. |
| `usage_over_quota` | 429 | The area's application passed its stored-data ceiling at the last usage check. Reads, lists, and deletes still work. | If the owner approves freeing space, delete the selected files or database rows. Upload again after the next successful stored-data check clears the limit, or after an approved quota increase. The start of a new month does not clear it. |
| `account_paused` | 429 | The account is paused. File reads, lists, uploads and deletes under an app's credential, and file transfers under a grant the app minted, are paused too. | Retry after the pause clears. To manage files while paused, the owner can use an account session with the environment header. |
| `rate_capped` | 429 | One client address sent your application more requests in a minute than the serving router admits, or the backend's credential made more than 600 storage calls in a minute. | Wait the seconds `Retry-After` gives, then send the request again. |
| `storage_error` | 500 | A storage operation failed before it could send its response. | [Check what the request changed](#refusals) before retrying a write or deletion. Report a repeated failure with its reference. |

### Transfer grant and sign-in refusals

| Refusal | Status | Cause | Remedy |
| --- | --- | --- | --- |
| `grant_minter_not_admitted` | 403 | `POST /storage/v0/grants` was called under an account session or an account-scoped token. | Mint the grant under the application's platform credential or a token for the application. For an upload from your AI assistant, call `mint_upload_grant`. |
| `app_credential_not_admitted` | 403 | `mint_upload_grant` was called under the application's platform credential. | Call it from your session or a minted token. The backend mints on `POST /storage/v0/grants`. |
| `transfer_grant_not_admitted` | 403 | A transfer grant was used for another file, the other direction, or another route. | Use the grant only on `PUT` or `GET` for its one file, and an ordinary credential elsewhere. |
| `transfer_grant_spent` | 403 | A successful write spent the upload grant. Rarely, a refused write could not return the use, and nothing was written. Sending the same zip again under a deploy grant returns 200. | For a file transfer, check whether the write landed. Mint a grant only for a new write. For a deploy, check `read_status` for a started deploy or the same upload under `pending_upload`. Use its `retry` if present. Prepare a fresh upload only if the old one is gone and no deploy started. With only the command, ask the person monitoring it to check. |
| `transfer_grant_expired` | 403 | The grant expired, five minutes after minting by default. | For an ordinary transfer, get a fresh grant for the same area, file and direction. For an export, request the download again. For a deploy, check `read_status` for a started deploy or the same `pending_upload`. Use its `retry` if present. Prepare a fresh upload only if the old one cannot start and no deploy started. With only the command, ask the person monitoring it to check. |
| `account_suspended` | 403 | The account is suspended: the calling credential's account, or, under a transfer grant, the account whose application minted the grant. | Nothing on your side clears it. Once platform staff reinstate the account, an unexpired grant works again. |
| `authentication_required` | 401 | The call sent no credential, or one that matches no account. Or it sent a grant that was not accepted, and the `detail` opens "The grant this request presented was not accepted": the grant expired and was removed, or its value was changed. | Send the application's platform credential, a minted token, or the session's credential. For a grant that was not accepted, use a new grant. Where your application requested the grant, request another from `POST /storage/v0/grants`. Where `mint_upload_grant` returned it, call that action again and run the upload command it returns. |

## Related

- [Add sign-in to your app](/cloud/guides/add-sign-in-to-your-app/) turns on sign-in and explains the user check the service uses.
- [Storage](/cloud/backend-packages/storage/) describes the package's client, its test double, and the file routes.
- [Use the feature package library](/cloud/guides/use-the-library/) copies the packages into the project.
- [Deploy from your computer](/cloud/getting-started/deploy-an-application/) covers the deploy area and the deploy that reads an artifact.
- [Mint a token](/cloud/guides/mint-a-token/) mints the token a script uses on the storage routes.
- [Applications and environments](/cloud/concepts/applications-and-environments/) explains the two environments whose files each area keeps apart.
- [declare_storage_area](/cloud/reference/actions/declare-storage-area/), [list_storage_areas](/cloud/reference/actions/list-storage-areas/), and [mint_upload_grant](/cloud/reference/actions/mint-upload-grant/) in the generated reference give each action's arguments and result.
