---
title: Build a public upload gallery
description: Build a public image gallery with a complete storage-backed Node.js service, browser page and check script, using the Storage package or fetch alone.
slug: /guides/build-a-public-upload-gallery
order: 50
visibility: public
redirects_from: []
---

# Build a public upload gallery

Prompt:

> Let anyone upload images to a shared gallery, with no sign-in.

Build a gallery where any visitor can upload, list and download images. This page gives the complete server, browser page and check script, using the Storage package or the alternative that calls the file routes with `fetch`.

Every file in the gallery is public. For files belonging to individual users, use the [signed-in upload service](/cloud/guides/store-files/#a-minimal-upload-service) instead.

## What your AI tool does

- Writes the complete service and gallery files below, keeping the platform credential on the server.
- Declares storage, checks the application locally where a shell is available, and deploys it.
- Checks an upload, listing and download, and reports the environment and any untested behavior.

## What you need

- A gallery intended to let every visitor upload and read every file.
- Node.js 24 or later for local runs and the check script ([What your computer needs](/cloud/getting-started/prerequisites/)).
- A Turn Zero Cloud connection before declaring storage or deploying. Writing the fetch-only files needs no Cloud sign-in.

## Before your AI starts

**For the AI tool:** Read `skill:deploy` and `skill:add-service` through `read_context`, and keep their approval and verification rules.

- Before declaring storage or deploying, [connect and sign in](/cloud/getting-started/connect-your-tool/). Taking the Storage package through the CLI also needs a CLI credential ([Use the library](/cloud/guides/use-the-library/)).
- Keep `TURNZERO_CLOUD_APP_TOKEN` in the backend. The deployed backend receives its credential and storage origin through [its settings](/cloud/concepts/the-settings-a-deployed-copy-receives/). Visitors need no credential.
- For a run on your machine, follow [Write the environment file](/cloud/guides/run-your-application-on-your-machine/#1-write-the-environment-file). It supplies development storage settings, including `TURNZERO_CLOUD_APPLICATION`. Files stored by that local run stay in development, separate from production.
- Before a deployed write check, follow [Check the release](/cloud/getting-started/deploy-an-application/#check-the-release), including its permission rule for an application with real users.

## Steps

### 1. Write the service files

A service anyone may use, such as a shared gallery, needs no sign-in and no Account package. Its routes call storage with the application's platform credential. They check no user, so no visitor signs in. Every file in its area is shared: any visitor lists and downloads every file. For an upload only you may make, add sign-in and check your own user id, as [Let only you reach an admin route](/cloud/guides/add-sign-in-to-your-app/#6-let-only-you-reach-an-admin-route) shows.

This is a complete starter: the service, a gallery page, and a script that checks the deployed service. Every file is below, whole, and a test runs them all. For offline storage tests, use `createStorageDouble` after signing in to Cloud, or your own stand-in for `fetch` beforehand, as [Use the other doubles](/cloud/guides/test-your-application-locally/#6-use-the-other-doubles) describes. The files you write are:

```text
manifest.json
package.json
src/storage.mjs
src/main.mjs
src/server.mjs
client/index.html
client/app.js
client/styles.css
scripts/check.mjs
```

With the Storage package, use `turnzero library take --entry storage` as [Use the library](/cloud/guides/use-the-library/) shows. It copies the package to `lib/storage/` and runs `npm install`. Keep `package-lock.json`, the `lib/storage/` copy and the library folder `system/`: this starter deploys from the project root and ships all three. The image build installs from `lib/storage/`, not `system/` ([The two project layouts](/cloud/concepts/what-the-deploy-zip-holds/#the-two-project-layouts)).

To write the starter before signing in to Cloud, use [The starter without the library](#the-starter-without-the-library). Deploy either form as [Deploy from your computer](/cloud/getting-started/deploy-an-application/) describes. Then run `node scripts/check.mjs <hostname>` with the hostname the deploy returns.

#### Public service files

`manifest.json` declares storage and records the Storage package:

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

`package.json` installs the Storage package from its copy under `lib/` and starts `src/main.mjs`:

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

`src/storage.mjs` builds the Storage client, and `src/main.mjs` starts the server on `PORT`:

```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);
```

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

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

#### The starter without the library

Use this form to write the starter before signing in to Cloud. It calls the file routes with `fetch` and needs no `library take`. Declaring storage and deploying still require Cloud sign-in.

Replace `src/storage.mjs` with the file below. Remove `dependencies` from `package.json` and the `storage` row from the manifest's `packages`, leaving `packages: []`. Keep the other starter files unchanged.

This file implements only `mintArea`, `put`, `list` and `get`, the four calls this server uses. Deploy and run `scripts/check.mjs` as above.

```js
// src/storage.mjs: the file routes over fetch, with no library
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}` },
  });
}

// A refusal keeps the answer's status and the platform's error name.
async function refusal(response, code) {
  const body = await response.json().catch(() => ({}));
  const error = new Error(`${response.status}: ${body.detail ?? body.error ?? code}`);
  return Object.assign(error, { code, status: response.status, refusal: body.error });
}

// A segment that is . or .. would leave the area's route, so it is refused here.
function fileRoute(area, name) {
  if (name.split(/[\\/]/).some((part) => part === '.' || part === '..')) {
    throw Object.assign(new Error('A file name holds no . or .. segment.'), { code: 'invalid_name' });
  }
  return `/storage/v0/areas/${encodeURIComponent(area)}/files/${name.split('/').map(encodeURIComponent).join('/')}`;
}

export const storage = {
  async mintArea(area, { accountKeyed, versionKeeping, application }) {
    const body = { account_keyed: accountKeyed, version_keeping: versionKeeping, ...(application ? { application } : {}) };
    const response = await transport(`/storage/v0/areas/${encodeURIComponent(area)}`, {
      method: 'PUT',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify(body),
    });
    if (response.status !== 200 && response.status !== 201) throw await refusal(response, 'mint_failed');
  },
  async put(area, name, bytes, { identity, contentType }) {
    const response = await transport(fileRoute(area, name), {
      method: 'PUT',
      headers: { 'content-type': contentType, 'x-acting-identity': identity },
      body: bytes,
    });
    if (!response.ok) throw await refusal(response, 'put_failed');
    return { version: (await response.json()).version };
  },
  async list(area, { cursor, limit }) {
    const query = new URLSearchParams({ limit: String(limit) });
    if (cursor) query.set('cursor', cursor);
    const response = await transport(`/storage/v0/areas/${encodeURIComponent(area)}/files?${query}`);
    if (!response.ok) throw await refusal(response, 'list_failed');
    const { files, cursor: next } = await response.json();
    return { names: files.map((file) => ({ name: file.name, size: file.size, contentType: file.content_type })), cursor: next ?? null };
  },
  async get(area, name) {
    const response = await transport(fileRoute(area, name));
    if (!response.ok) throw await refusal(response, response.status === 404 ? 'no_file' : 'get_failed');
    const contentType = response.headers.get('content-type') ?? 'application/octet-stream';
    return { bytes: new Uint8Array(await response.arrayBuffer()), meta: { contentType } };
  },
};
```

#### Public routes and limits

`POST /files` uploads one image, and the service chooses its name, so no visitor replaces another's file. `GET /files` lists one page of up to 24 files, each with its name, size, content type and absolute `url`, followed by the page's `cursor`, and `GET /files?cursor=<cursor>` lists the page after it. `GET /files/<name>` downloads one file, as an attachment with `nosniff`, with the headers shown in the handler below. The service has no delete route, so no visitor removes a file.

Routes that anyone can call need their own limits. The upload route admits four image types and a body of 1 byte to 2 MiB. Each client address gets ten uploads and 120 reads a minute. The service answers 415 for another type, 413 for an empty or larger body, and 429 past a count. An upload over the application's stored-data quota gets 507 `over_quota`, without `Retry-After`.

The [serving router](/cloud/concepts/glossary/#serving-router), which receives every request to your hostnames, takes in the whole body first, and forwards it without `Content-Length` ([The request size limit](/cloud/concepts/egress-firewall-and-request-limits/#the-request-size-limit)). So the upload route counts the bytes as they arrive and keeps none past 2 MiB. That limit protects your server's memory, and the router's own 64 MiB limit caps what the router receives.

The client address is the first entry of `x-forwarded-for`, which the serving router sets. An IPv6 address counts as its first four groups, its /64 prefix, as the router's own count does. Each running copy keeps its counts in its own memory, so they start again when it restarts. Without the read limit, one address alone could use up the 600 storage calls a minute that every visitor shares.

Where storage refuses a cursor, the service answers 400 `invalid_cursor`, with a `detail` asking the visitor to list again from the first page. Where storage refuses a call for its rate, the service answers 503 `busy` with `Retry-After`. After a start or restart, it answers 503 `starting` until its area is declared. None of these answers writes a console error in this sample.

A 503 can still appear in the router's `answered_5xx` records and in `application.server_errors` from `read_status`. The record includes the method, path without its query, status, duration and serving version, but neither the response body nor `Retry-After`. It cannot distinguish `starting` from `busy`; read the response body's `error` to tell them apart. Time since a restart alone does not establish the cause. [Read logs and counters](/cloud/guides/read-logs-and-counters/) shows how to read the records and counts.

On the platform, the page's three files are served from `client/` ahead of these routes ([Serve a web client](/cloud/guides/serve-a-web-client/)). With `turnzero` 0.35.0 or later, `client/`, and a numeric port, the command serves them locally too. For an older command or starting Node.js directly, the server answers them itself.

#### Public request handler

```js
// src/server.mjs: a public service, with no sign-in
import { randomUUID } from 'node:crypto';
import { readFile } from 'node:fs/promises';
import { createServer } from 'node:http';
import { AREA, storage } from './storage.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;
}

// Per client address: ten uploads and 120 reads per minute; images up to 2 MiB.
const EXTENSIONS = new Map([['image/png', '.png'], ['image/jpeg', '.jpg'], ['image/gif', '.gif'], ['image/webp', '.webp']]);
const MAX_BYTES = 2 * 1024 * 1024;
const PER_MINUTE = { upload: 10, read: 120 };
// Leave room in the read limit for each listed image.
const PAGE_SIZE = 24;

// Serve client files locally.
const CLIENT_FILES = new Map([
  ['/', ['index.html', 'text/html; charset=utf-8']],
  ['/index.html', ['index.html', 'text/html; charset=utf-8']],
  ['/app.js', ['app.js', 'text/javascript; charset=utf-8']],
  ['/styles.css', ['styles.css', 'text/css; charset=utf-8']],
]);

// Use the first x-forwarded-for address; group IPv6 by /64, as the router does.
function sourceOf(request) {
  const address = String(request.headers['x-forwarded-for'] ?? '').split(',')[0].trim();
  if (!address.includes(':')) return address;
  const [head, tail = ''] = address.split('::');
  const left = head ? head.split(':') : [];
  const right = tail ? tail.split(':') : [];
  const groups = [...left, ...Array(8 - left.length - right.length).fill('0'), ...right];
  return groups.slice(0, 4).map((group) => parseInt(group, 16).toString(16)).join(':');
}

// Counts per address and kind, held in this process for one minute.
let minute = 0;
const counts = new Map();
function underLimit(request, kind) {
  const now = Math.floor(Date.now() / 60_000);
  if (now !== minute) {
    minute = now;
    counts.clear();
  }
  const key = `${kind} ${sourceOf(request)}`;
  const count = (counts.get(key) ?? 0) + 1;
  counts.set(key, count);
  return count <= PER_MINUTE[kind];
}

// Count bytes: the router omits Content-Length. Keep at most MAX_BYTES;
// return null for empty or oversized bodies.
async function readBounded(request) {
  const chunks = [];
  let size = 0;
  for await (const chunk of request) {
    size += chunk.length;
    if (size <= MAX_BYTES) chunks.push(chunk);
  }
  return size > 0 && size <= MAX_BYTES ? new Uint8Array(Buffer.concat(chunks)) : null;
}

let ready = false;

async function handle(request, response) {
  // End the response when the request is aborted (abortSignalOf, above).
  const signal = abortSignalOf(request, response);
  signal.addEventListener('abort', () => response.destroy(), { once: true });
  const send = (status, body, headers = {}) => {
    if (response.destroyed) return;
    response.writeHead(status, { 'content-type': 'application/json', ...headers });
    response.end(JSON.stringify(body));
  };
  if (!ready) return send(503, { error: 'starting' });
  // An invalid URL falls through to 404.
  let pathname = '';
  let searchParams = new URLSearchParams();
  try {
    ({ pathname, searchParams } = new URL(request.url, 'http://localhost'));
  } catch {}
  if (request.method === 'GET' && pathname === '/health') return send(200, { ok: true });
  if (request.method === 'GET' && CLIENT_FILES.has(pathname)) {
    const [file, type] = CLIENT_FILES.get(pathname);
    const body = await readFile(new URL(`../client/${file}`, import.meta.url));
    if (response.destroyed) return;
    response.writeHead(200, { 'content-type': type });
    return response.end(body);
  }
  try {
    if (request.method === 'POST' && pathname === '/files') {
      if (!underLimit(request, 'upload')) return send(429, { error: 'too_many_requests' });
      const contentType = request.headers['content-type'];
      const extension = EXTENSIONS.get(contentType);
      if (!extension) return send(415, { error: 'type_not_allowed' });
      // Reject a declared oversized local body before reading it.
      if (Number(request.headers['content-length']) > MAX_BYTES) return send(413, { error: 'size_not_allowed', max_bytes: MAX_BYTES });
      const bytes = await readBounded(request);
      if (!bytes) return send(413, { error: 'size_not_allowed', max_bytes: MAX_BYTES });
      // Generated names prevent visitors replacing files.
      const name = `${randomUUID()}${extension}`;
      const { version } = await storage.put(AREA, name, bytes, { identity: 'anonymous', contentType });
      return send(201, { name, version, url: `https://${process.env.APP_PUBLIC_HOST}/files/${encodeURIComponent(name)}` });
    }
    if (request.method !== 'GET' || !pathname.startsWith('/files')) return send(404, { error: 'not_found' });
    if (!underLimit(request, 'read')) return send(429, { error: 'too_many_requests' });
    if (pathname === '/files') {
      const cursor = searchParams.get('cursor');
      try {
        const page = await storage.list(AREA, { cursor, limit: PAGE_SIZE });
        const files = page.names.map(({ name, size, contentType }) => ({ name, size, contentType, url: `https://${process.env.APP_PUBLIC_HOST}/files/${encodeURIComponent(name)}` }));
        return send(200, { files, cursor: page.cursor });
      } catch (error) {
        // The visitor can restart a list with an invalid cursor.
        if (cursor && error.refusal === 'invalid_cursor') return send(400, { error: 'invalid_cursor', detail: 'List again from the first page.' });
        throw error;
      }
    }
    if (!pathname.startsWith('/files/')) return send(404, { error: 'not_found' });
    try {
      const { bytes, meta } = await storage.get(AREA, decodeURIComponent(pathname.slice('/files/'.length)));
      // Attachments cannot run here under a false type. Names are never reused,
      // so browsers can cache each file unchanged.
      response.writeHead(200, {
        'content-type': meta.contentType,
        'content-disposition': 'attachment',
        'x-content-type-options': 'nosniff',
        'cache-control': 'public, max-age=31536000, immutable',
      });
      return response.end(bytes);
    } catch (error) {
      if (error.code === 'no_file') return send(404, { error: 'no_file' });
      throw error;
    }
  } catch (error) {
    // A storage quota failure needs attention.
    if (error.refusal === 'usage_over_quota') return send(507, { error: 'over_quota' });
    // A storage rate refusal can be retried.
    if (error.status === 429) return send(503, { error: 'busy' }, { 'retry-after': '60' });
    throw error;
  }
}

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));
  // Restate the area on every start, before serving file routes.
  await storage.mintArea(AREA, { accountKeyed: false, versionKeeping: false, application: process.env.TURNZERO_CLOUD_APPLICATION });
  ready = true;
  return server;
}
```

#### Storage limits and file safety

A [transfer grant](/cloud/guides/store-files/#3-hand-a-browser-or-a-native-app-a-transfer-grant) sends the bytes directly to storage, past this service's type and rate checks. Your backend mints one only after its own checks.

The content type is whatever the visitor's request says. Storage records it and does not check the bytes against it. The attachment header and `nosniff` stop a file with a false type from running on your application's hostname.

The platform's own limits apply as well:

- The serving router admits 300 requests a minute from one client address without a session, on each of its replicas. It refuses the rest 429 `rate_capped` before they reach your application ([The per-address and per-user limits](/cloud/concepts/egress-firewall-and-request-limits/#the-per-address-and-per-user-limits)).
- Every visitor's upload, list, and download calls storage under the one platform credential, which may make 600 storage calls a minute ([The platform request limit](/cloud/concepts/egress-firewall-and-request-limits/#the-platform-request-limit)). Past that, the client throws `put_failed`, `list_failed`, or `get_failed`, its message starting `429:`, and the service answers 503. This platform limit is fixed; no setting raises it.
- A storage request body can be up to 32 MiB, and puts are refused `usage_over_quota` once the application passes its stored-data ceiling ([step 4: Limits and metering](/cloud/guides/store-files/#4-limits-and-metering)). The service limits neither the area's total size nor how long its files are kept: a total-size cap or a cleanup of old files is yours to add.

#### The gallery page

The page in `client/` is plain HTML, CSS, and script, with no build step. It uploads the image a visitor picks with `POST /files`, and shows it first in the gallery. It shows the gallery from `GET /files` a page at a time, and its More button follows `cursor`. Each image is an `<img>` of `/files/<name>`, which shows the image although the download is an attachment.

Each image fetched from the service counts as one read against an address's 120 a minute and one storage call against the shared 600. A listing answers 24 files to leave room for those reads. The download's `cache-control` header lets the browser reuse a cached image; a new or uncached request still counts.

The gallery lists files in name order, and the names are random, so it is not ordered by time. For a gallery newest first, see [A gallery or feed, newest first](/cloud/backend-packages/storage/#a-gallery-or-feed-newest-first).

`client/index.html` holds the upload form, the gallery, and the More button:

```html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Gallery</title>
  <link rel="stylesheet" href="/styles.css">
</head>
<body>
  <h1>Gallery</h1>
  <form id="upload">
    <input id="file" type="file" accept="image/png,image/jpeg,image/gif,image/webp" required>
    <button type="submit">Upload</button>
  </form>
  <p id="message"></p>
  <div id="gallery"></div>
  <button id="more" type="button" hidden>More</button>
  <script src="/app.js"></script>
</body>
</html>
```

`client/app.js` lists the gallery, follows `cursor`, and uploads:

```js
// client/app.js
const gallery = document.querySelector('#gallery');
const more = document.querySelector('#more');
const message = document.querySelector('#message');
const shown = new Set();
let pageCursor = null;

function imageOf(name) {
  shown.add(name);
  const image = document.createElement('img');
  image.src = `/files/${encodeURIComponent(name)}`;
  image.alt = name;
  return image;
}

// One page of the gallery, after the images already shown.
async function showPage(cursor) {
  const response = await fetch(cursor ? `/files?cursor=${encodeURIComponent(cursor)}` : '/files');
  if (!response.ok) {
    message.textContent = `The gallery could not be listed (${response.status}).`;
    return;
  }
  const page = await response.json();
  // A name already shown, such as the visitor's own upload, is not shown twice.
  gallery.append(...page.files.filter((file) => !shown.has(file.name)).map((file) => imageOf(file.name)));
  pageCursor = page.cursor;
  more.hidden = !pageCursor;
}

document.querySelector('#upload').addEventListener('submit', async (event) => {
  event.preventDefault();
  const file = document.querySelector('#file').files[0];
  message.textContent = 'Uploading.';
  const response = await fetch('/files', { method: 'POST', headers: { 'content-type': file.type }, body: file });
  if (!response.ok) {
    message.textContent = `The upload was refused (${response.status}).`;
    return;
  }
  const { name } = await response.json();
  gallery.prepend(imageOf(name));
  message.textContent = 'Uploaded.';
});

more.addEventListener('click', () => showPage(pageCursor));
showPage(null);
```

`client/styles.css` sets the images out in a grid:

```css
/* client/styles.css */
body {
  max-width: 48rem;
  margin: 0 auto;
  padding: 1rem;
}

#gallery {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(10rem, 1fr));
  gap: 0.5rem;
  margin: 1rem 0;
}

#gallery img {
  width: 100%;
  aspect-ratio: 1;
  object-fit: cover;
}
```

#### Check the public service

`scripts/check.mjs` checks the service end to end with Node's own `fetch`. It takes the deployed hostname, or an address such as `http://localhost:8080` for a run on your machine. It checks `/health`, uploads a one-pixel PNG, finds it in the list, downloads it, and compares the bytes. It prints one line for each step and exits 1 at the first failure. Each run leaves its one-pixel image in the area, since the service has no delete route.

The upload command prints the test file's name. Remove it with the platform's `DELETE /storage/v0/areas/{area}/files/{name}`, using `uploads` and that name for this sample. Use a minted token and `X-Acting-Identity`, with `x-turnzero-cloud-environment` set to the environment you checked, as [step 2 (Put, fetch, list, delete)](/cloud/guides/store-files/#2-put-fetch-list-delete) describes.

```js
// scripts/check.mjs: node scripts/check.mjs <hostname, or an address such as http://localhost:8080>
const target = process.argv[2];
if (!target) {
  console.log('usage: node scripts/check.mjs <hostname>');
  process.exit(2);
}
const base = target.includes('://') ? target.replace(/\/$/, '') : `https://${target}`;

// A PNG of one transparent pixel.
const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', 'base64');

function fail(step, detail) {
  console.log(`failed: ${step}: ${detail}`);
  process.exit(1);
}

async function call(step, path, init) {
  let response;
  try {
    response = await fetch(`${base}${path}`, init);
  } catch (error) {
    fail(step, error.cause?.message ?? error.message);
  }
  if (!response.ok) fail(step, `status ${response.status}`);
  return response;
}

await call('health', '/health');
console.log('ok: health');

const uploaded = await call('upload', '/files', { method: 'POST', headers: { 'content-type': 'image/png' }, body: PNG });
const { name } = await uploaded.json();
console.log(`ok: upload, named ${name}`);

let cursor = null;
let listed = false;
do {
  const page = await (await call('list', cursor ? `/files?cursor=${encodeURIComponent(cursor)}` : '/files')).json();
  listed = page.files.some((file) => file.name === name);
  cursor = page.cursor;
} while (!listed && cursor);
if (!listed) fail('list', `${name} is not in the list`);
console.log('ok: list');

const downloaded = Buffer.from(await (await call('download', `/files/${encodeURIComponent(name)}`)).arrayBuffer());
if (!downloaded.equals(PNG)) fail('download', 'the bytes differ from the upload');
console.log('ok: download, the bytes match');
```

### 2. Run locally and deploy

For offline storage tests, use the test double or a stand-in for `fetch` as step 1 describes. With provisioned local settings, run the server and check it before the first deploy. [Run your app on your computer](/cloud/guides/run-your-application-on-your-machine/) gives the setup and run commands.

Follow [Deploy from your computer](/cloud/getting-started/deploy-an-application/) to create the application, submit the complete manifest, check and deploy these files. With no usable shell, follow [Deploy from a chat](/cloud/getting-started/build-an-app-from-a-chat/), including its file limits and the library copies Cloud fills. Report local tests and local runs as unrun where your tools cannot perform them.

To test before serving production, follow [Test in development, then promote](/cloud/guides/turn-on-development-and-promote/). Turn development on before deploying. Each environment has its own part of the `uploads` area: development's files stay out of production.

### 3. Check the gallery

Run `node scripts/check.mjs <hostname>` with the hostname the deploy returns, in the environment you are checking. For a local run, pass its address, such as `http://localhost:8080`, instead. The script writes one test image; on production with real users, obtain the person's approval for that write in this run first.

Open the gallery and check that you can upload an image, see it once and follow **More** when another page exists. The check script verifies the routes, not browser behavior.

With development first, check development before an approved promote. After production reports `deployed`, check production within the permission rule above. Report the test file name the script prints and remove it using the cleanup instructions beside the script.

## Expected result

Visitors can upload images without signing in, list the shared gallery and download the same bytes. The server chooses file names and enforces the limits in [Public routes and limits](#public-routes-and-limits).

Report the deployed address, version, environment, script results and browser checks. Name any untested part and any test image left in storage.

## Refusals

These are the sample's common responses. [Store files: Refusals](/cloud/guides/store-files/#refusals) covers the platform's storage refusals.

| Response | Cause | Remedy |
| --- | --- | --- |
| 415 `type_not_allowed` | The upload names a type outside the four types the handler admits. | Send an image with an admitted content type. |
| 413 `size_not_allowed` | The upload is empty or exceeds 2 MiB. | Send a nonempty image within the limit. |
| 429 `too_many_requests` | The client address exceeds the handler's upload or read count. | Wait for the next minute. |
| 400 `invalid_cursor` | Storage refused the listing cursor. | List again from the first page. |
| 503 `starting` | The area has not been declared since the server started. | Read the response body and check startup; time since a restart alone does not establish this cause. |
| 503 `busy` | Storage refused a call for its rate. | Retry after `Retry-After`; the platform's shared limit still applies. |
| 507 `over_quota` | Stored data exceeds the application's ceiling. | Reduce stored data and follow [Limits and metering](/cloud/guides/store-files/#4-limits-and-metering). |

## Related

- [Store files](/cloud/guides/store-files/) covers storage declarations, private files, transfer grants, limits and cleanup.
- [Storage](/cloud/backend-packages/storage/) describes the client, its methods and file routes.
- [Test in development, then promote](/cloud/guides/turn-on-development-and-promote/) checks a version before it serves production.
