> ## Documentation Index
> Fetch the complete documentation index at: https://docs.gatojs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Uploads

> Accept, store and serve organization files in GatoJS on local disk or S3-compatible storage with upload purposes and the FileUpload component.

When a feature accepts files from users (a delivery photo, an editor image, an attachment), the `uploads` module handles the whole path. It accepts the file at `POST /api/uploads`, checks it against an **upload purpose** (allowed types, size limit, visibility, optional image resizing), stores the object and an `Upload` row, and serves the file at `GET /api/uploads/<id>`. `STORAGE_PROVIDER` picks the storage: `local` (the default) is a directory on the server's disk, `s3` is any S3-compatible store.

Your feature renders `<FileUpload>` and stores only the file's `id` in its own entity. Modules declare purposes in `module.ts`; the kit ships one, `editor-image`.

A file belongs to an organization. The purpose's visibility decides who can download it: `public` means anyone with the URL, even signed out; `organization` means only a session whose active organization owns the file.

## What it doesn't do

* **No page or menu.** There's no list of organization files and no screen to delete them.
* **No cleanup of orphaned objects.** A file uploaded but never saved to an entity, a file whose entity was deleted without `deleteUploadCommand`, and every object after `gato remove` stay in storage. See [Orphaned objects](#orphaned-objects).
* **No migration between providers.** Changing `STORAGE_PROVIDER` doesn't copy existing files. They stay in the old storage and return 404.
* **No streaming.** The route reads the whole file into memory on upload and download. No `Range` requests and no presigned S3 URLs; files always pass through the app server.
* **No SVG, HTML or XML** in any purpose, and no signature-less text formats (`text/plain`, `text/csv`, `application/json`): the type is detected from the file bytes.
* **No foreign key to your entities.** The column holding the file `id` is a plain column; your command checks ownership.
* **No virus scanning**, and no processing of files other than images.

Skip the module if the project doesn't accept files or stores them outside the app, if files are large (video, archives) because the route holds each one in memory, or if production has neither a persistent directory for a single instance nor S3-compatible storage.

## Requirements

| | `uploads` |
| - | - |
| Required kit modules | None. With [`audit-logs`](https://docs.gatojs.com/modules/audit-logs) installed, file events are recorded. |
| Services | With `local`: none, files go to `./volumes/uploads` locally. With `s3`: an S3-compatible store with an existing bucket; locally MinIO from the Compose profile `s3`. Integration tests always run on S3 and need MinIO. |
| Production | With `local`: one app instance and a persistent directory such as a volume. With `s3`: a bucket. See [File storage](https://docs.gatojs.com/deployment/file-storage.md). |
| Environment variables | `STORAGE_PROVIDER` and `STORAGE_LOCAL_PATH`, optional outside production. `S3_ENDPOINT`, `S3_ACCESS_KEY_ID`, `S3_SECRET_ACCESS_KEY`, `S3_BUCKET` required only with `s3`; `S3_REGION` and `S3_FORCE_PATH_STYLE` optional. |
| npm dependencies | `@aws-sdk/client-s3`, `file-type`, `sharp`. |
| Database | `uploads` table and `UploadVisibility` enum, so a migration after adding the module. |

## Install and remove

> [tab] Existing project
>
> **1. Add the module**
>
> ```bash theme={null}
> npx gato add uploads
> ```
>
> This copies the module files, fills `wa:relations` (`uploads Upload[]` on `User` and `Organization`), `wa:modules` in `.env.example`, `wa:services` in `docker-compose.yml` and `wa:ci-integration` in your CI workflows, then runs `gato generate` and `npm install`.
>
> **2. Update .env**
>
> `gato add` doesn't change `.env`. Without new variables the dev server starts with `local` and `./volumes/uploads`. Copy the `STORAGE_*` variables from the `wa:modules` region of `.env.example` (and `S3_*` if you use `s3`) so production-mode runs work too.
>
> **3. Start MinIO (only for s3)**
>
> ```bash theme={null}
> docker compose --profile s3 up -d
> ```
>
> **4. Create the migration**
>
> ```bash theme={null}
> npx prisma migrate dev --name add-uploads
> ```
>
> Commit it. After `--no-install`, also run `npm run db:generate`.

> [tab] New project
>
> ```bash theme={null}
> npm create gato-app@latest acme-app -- --modules uploads
> ```
>
> `gato create` writes `STORAGE_PROVIDER=local`, `STORAGE_LOCAL_PATH=./volumes/uploads` and local MinIO `S3_*` values with the bucket `<slug>-uploads` to `.env`, adds the `minio` and `minio-init` services under the `s3` profile, and adds MinIO steps to CI. `docker compose up -d` starts only the database and mailpit; files go to `./volumes/uploads`, which is in `.gitignore`.

### Storage provider

The module's `env.ts` is part of the app-wide environment validation, so a bad storage configuration stops the whole server at startup, not at the first upload.

| Variable | Rule | Local value |
| - | - | - |
| `STORAGE_PROVIDER` | `local` or `s3`, trimmed and lowercased. Missing or empty means `local`. Anything else is an error. | `local` |
| `STORAGE_LOCAL_PATH` | Only with `local`: the storage directory. Empty means unset. A relative path resolves against the process working directory. In production outside Railway it's required and must be absolute. | `./volumes/uploads` |
| `RAILWAY_ENVIRONMENT_ID`, `RAILWAY_VOLUME_MOUNT_PATH` | Set by Railway. Read only with `local`, for production rules and as the default directory. | unset |

With `local`, the directory is the first of: `STORAGE_LOCAL_PATH`, `RAILWAY_VOLUME_MOUNT_PATH` (on Railway, attaching a volume is enough), then `./volumes/uploads`. With `local`, `S3_*` variables aren't validated, so the MinIO values from `.env.example` can stay in `.env`.

#### Production rules

With `NODE_ENV=production` and `local`, the schema checks four conditions and reports the first that matches. "On Railway" means `RAILWAY_ENVIRONMENT_ID` is set.

| Condition | Why it fails |
| - | - |
| On Railway without a volume | Files would live on the container disk and vanish on every deploy. |
| On Railway with a volume, but `STORAGE_LOCAL_PATH` outside it | Files would land next to the volume, not in it. |
| Outside Railway without `STORAGE_LOCAL_PATH` | The kit can't tell whether a directory survives restarts, so you must name it explicitly. |
| Outside Railway with a relative `STORAGE_LOCAL_PATH` | A relative path depends on the working directory. Under `node .next/standalone/server.js` it points inside `.next/standalone`, which the next build deletes. |

These rules check configuration, not the disk. A directory the process can't write to passes startup, and the first upload fails with 500 `storage_failed`. Outside production none of these rules apply.

Limits of `local`:

* **Single instance.** A second app instance can't see the files. Several instances need `s3`.
* **Persistent directory.** It must survive restarts and redeploys: a Railway volume, a Docker volume or a host directory.
* **Path safety.** Keys with a null byte, absolute keys and keys with `..` segments are rejected, and the resolved path must stay inside the storage directory. The check is lexical and doesn't resolve symlinks, so the directory should belong to the app alone.

See [File storage](https://docs.gatojs.com/deployment/file-storage.md) for choosing and hosting storage in production, and [Railway](https://docs.gatojs.com/deployment/railway.md) for volumes and buckets there.

### S3 variables

`S3_*` variables apply only with `STORAGE_PROVIDER=s3`. A missing required variable or bad value stops the server at startup.

| Variable | Rule with `s3` | Local value |
| - | - | - |
| `S3_ENDPOINT` | Required, URL | `http://localhost:9000` |
| `S3_REGION` | Optional, non-empty; default `auto` | `auto` |
| `S3_ACCESS_KEY_ID` | Required, non-empty | `minioadmin` |
| `S3_SECRET_ACCESS_KEY` | Required, non-empty | `minioadmin` |
| `S3_BUCKET` | Required, non-empty | `<slug>-uploads` |
| `S3_FORCE_PATH_STYLE` | Optional, `true` or `false`; missing means `false` | `true` |

* The S3 client is created once per process, so changing variables requires a restart.
* `S3_FORCE_PATH_STYLE=true` addresses objects as `endpoint/bucket/key`, which MinIO needs. Without it the client uses virtual-hosted style (`bucket.endpoint`).
* **The bucket must exist.** The app never creates it. Locally `minio-init` does, in CI a workflow step does, in production you create it in your provider's console.
* **Connection errors don't show at startup.** Validation only checks the format, so a wrong endpoint, credentials, region or missing bucket fails the first upload (500 `storage_failed`) or download (500).
* There is no rule against example values in production: `minioadmin` passes validation. Use your provider's credentials.

### MinIO locally

`docker/uploads.compose.yml` is added to the `wa:services` region of `docker-compose.yml` as two services with the Compose profile `s3`:

| Service | Image | Ports | Role |
| - | - | - | - |
| `minio` | `cgr.dev/chainguard/minio` pinned by digest | `${MINIO_PORT:-9000}` (S3 API), `${MINIO_CONSOLE_PORT:-9001}` (web console) | Storage; user and password `minioadmin`; data in `./volumes/minio`. |
| `minio-init` | `amazon/aws-cli` | none | Creates the `<slug>-uploads` bucket if missing, then exits. |

Profiled services don't start without the profile. To work on S3, set `STORAGE_PROVIDER=s3` in `.env` and run:

```bash theme={null}
docker compose --profile s3 up -d
```

If port 9000 is taken, change it in two places: `MINIO_PORT` in `.env` (read by Compose) and the port in `S3_ENDPOINT` (read by the app).

### CI

The manifest's `ciSteps` file is inserted into the `wa:ci-integration` region of `.github/workflows/ci.yml` and `mutation.yml`. Its "Start MinIO" and "Create MinIO bucket" steps run before integration tests. `src/test/integration/setup-env.ts` sets `STORAGE_PROVIDER=s3` for integration tests, so they run on S3 regardless of `.env`. E2E servers use `local` with a directory from `E2E_UPLOADS_DIR` (absolute path) or a temp directory, so `e2e.yml` doesn't start MinIO. See [CI](https://docs.gatojs.com/deployment/ci.md).

### Removing the module

`npx gato remove uploads` refuses when a project module lists `uploads` in `requires`. Otherwise it removes the module files, its variables from `.env.example`, the MinIO services, the CI steps, the schema relations and the three npm dependencies, and prints the migration command. What remains:

| What | After `gato remove uploads` |
| - | - |
| `uploads` table | Stays until you apply `npx prisma migrate dev --name remove-uploads`. Export the `key` column first if you want to clean storage. |
| Stored files | All stay: in `STORAGE_LOCAL_PATH` with `local`, in the bucket with `s3`. Neither the command nor the migration deletes them. |
| Local MinIO data and a running `minio` container | Stay; the container runs orphaned until `docker compose up -d --remove-orphans`. |
| `STORAGE_*` and `S3_*` in `.env` and production | Stay; remove them yourself. |
| File ID columns in your entities | Keep their values; `/api/uploads/<id>` returns 404. |
| Your code importing `<FileUpload>` or `deleteUploadCommand` | Stops building with `TS2307`. |
| `uploadPurposes` declarations | Stay and do nothing. |
| `upload.*` audit entries | Stay; shown as raw strings. |

## What the module adds

### Module definition

| Field | Value | Effect |
| - | - | - |
| `key` | `uploads` | Translation namespace. |
| `nav`, `routePrefixes` | `[]` | No page or menu item. |
| `roles` | not set | Routes and commands check access themselves. |
| `auditActions` | `upload.created`, `upload.deleted` | Labels for file events. |
| `uploadPurposes` | `editor-image`: `image/jpeg`, `image/png`, `image/webp`, `maxBytes: 5 * 1024 * 1024`, `visibility: "public"`, `resizeImage: { maxWidth: 1200 }` | The kit's purpose for editor images. |

### The `Upload` model

`prisma/schema/uploads.prisma`, table `uploads`, enum `UploadVisibility` (`PUBLIC`, `ORGANIZATION`):

| Field | Column and type | Meaning |
| - | - | - |
| `id` | `id`, `uuid` | File ID, part of `/api/uploads/<id>`. |
| `organizationId` | `organization_id`, text | Owning organization, from the session, never from the form. |
| `uploadedById` | `uploaded_by_id`, text, optional | Uploader; decides who may delete. |
| `purpose` | `purpose`, text | Purpose key at upload time. |
| `key` | `key`, text, unique | Storage key: `orgs/<organizationId>/<purpose>/<id>.<ext>`. A path under `STORAGE_LOCAL_PATH` with `local`, a bucket key with `s3`. |
| `fileName` | `file_name`, text | Client file name, unchanged (1–255 characters). |
| `mimeType` | `mime_type`, text | Type detected from bytes (`image/jpeg` after resizing). |
| `size` | `size`, `int` | Stored size in bytes (after resizing). |
| `visibility` | `visibility`, `UploadVisibility` | From the purpose at upload time. |
| `createdAt` | `created_at`, `timestamptz` | Upload time. |

Deleting an organization deletes its rows (`onDelete: Cascade`) but not its stored objects. Deleting a user keeps their files with `uploadedById` set to `null`. Visibility and limits are fixed at upload time: changing a purpose doesn't affect existing files.

### Upload: `POST /api/uploads`

A `multipart/form-data` request with `file`, `purpose` and an optional `serviceModeConfirmation` (JSON). Checks run in this order:

| Step | Error |
| - | - |
| 1. `Content-Length` is present and numeric | 411 `length_required` |
| 2. `Content-Length` ≤ the largest `maxBytes` of all purposes + 64 KiB | 413 `too_large` |
| 3. Session | 401 `unauthorized` |
| 4. Active organization | 403 `unauthorized` |
| 5. Body parses as `FormData` | 400 `invalid_input` |
| 6. Service mode confirmation | 403 with the confirmation error |
| 7. `file` is a file with a 1–255 character name, `purpose` is non-empty | 400 `invalid_input` |
| 8. Purpose exists in the registry | 400 `unknown_purpose` |
| 9. File isn't empty | 400 `empty` |
| 10. File size ≤ the purpose's `maxBytes` | 413 `too_large` |
| 11. Type detected from bytes is in `mimeTypes` and not forbidden | 415 `unsupported_type` |
| 12. Image resizing (purposes with `resizeImage`) | 400 `invalid_image` |
| 13. Object stored | 500 `storage_failed`, no row |
| 14. `Upload` row stored | 500 `storage_failed`, object rolled back |
| Success | 201 `{ id, url, fileName, mimeType, size }` with `url` = `/api/uploads/<id>` |

* **Order matters.** The step 2 limit is app-wide and checked before the session, so oversized requests are rejected without reading the body or touching the database. The purpose limit (step 10) applies after the file is in memory.
* **Type from content.** `file.type` and the extension are ignored; the stored extension follows the detected type.
* **Organization from the session.** An `organizationId` field in the form is ignored.
* **Images.** A purpose with `resizeImage` runs every `image/*` file through `sharp`: input limit 40,000,000 pixels, EXIF rotation, transparency flattened onto white, downscaled to `maxWidth` (never upscaled), saved as JPEG at quality 82 without EXIF metadata. Other file types in the same purpose pass unchanged.
* **Rollback.** If the row can't be written, the object is deleted again. If that also fails, the object stays orphaned and the log shows `upload rollback failed`.

### Download: `GET /api/uploads/<id>`

1. An `id` that isn't a UUID returns 404 without a database query.
2. A missing row returns 404.
3. An `ORGANIZATION` file returns 404 for no session, no active organization, a different active organization or removed membership, exactly like a missing file, so the response doesn't reveal that the file exists. A superadmin in service mode can read files of the organization they entered.
4. A `PUBLIC` file is served to anyone.
5. A missing object in storage returns 404; other storage errors return 500.

Response headers on 200:

| Header | Value |
| - | - |
| `Content-Type` | `mimeType` from the row |
| `Content-Disposition` | `inline; filename="<ASCII name>"; filename*=UTF-8''<percent-encoded name>` |
| `Cache-Control` | `public, max-age=31536000, immutable` for `PUBLIC`; `private, no-store` for `ORGANIZATION` |
| `X-Content-Type-Options` | `nosniff` |
| `Content-Security-Policy` | `sandbox; default-src 'none'` |

Browsers and proxies may cache a public file for a year, and the URL can't be invalidated other than by deleting the file. Organization files never enter caches. The sandbox CSP strips scripts, forms and external resources from the file, which may break the browser's built-in PDF viewer.

### Delete: `deleteUploadCommand`

`deleteUploadCommand(input, confirmation?)` (a server action) takes `{ id }`:

1. Gets the org context and checks service mode confirmation.
2. Looks up the file filtered by the active organization. An invalid ID, another organization's file and a missing file all return the same error.
3. Allows the uploader, organization owners and admins, and global admins and superadmins. Others get a permission error.
4. Deletes the object, then the row, then records `upload.deleted`. **A failed object delete doesn't stop the command**: it's logged as `upload deleteObject failed`, the row goes, and the object is orphaned.

### Orphaned objects

| Situation | What remains |
| - | - |
| A user uploaded a file in a form and never saved the form | Row and object without an entity. `<FileUpload>` uploads immediately on file selection. |
| Your entity was deleted without `deleteUploadCommand` | Row and object. |
| `deleteUploadCommand` couldn't delete the object | Object without a row. |
| Rollback after a failed row write failed | Object without a row. |
| An interrupted write with `local` (disk full, process killed) | Possibly partial file without a row. |
| Organization deleted | Objects under `orgs/<organizationId>/`; rows go by cascade. |
| `gato remove uploads` and the migration | Every object. |

The module has no cleanup job. To find orphans, compare storage keys with the `key` column; the `orgs/<organizationId>/<purpose>/` prefix narrows the comparison. See [Known limitations](https://docs.gatojs.com/known-limitations.md).

### Access by role

Any member of the active organization can upload, including `member`, and a superadmin in service mode after confirming. Deleting is limited to the uploader, owners and admins, and global admins. Reading: `public` files for anyone, `organization` files for any session whose active organization owns them, regardless of role.

### Audit events

| Action | Data | When |
| - | - | - |
| `upload.created` | `newData: { purpose, key, size }` | After the object and row are stored. |
| `upload.deleted` | `oldData: { purpose, key, size }` | After the row is deleted, even if the object wasn't. |

Events don't include the file name. Without `audit-logs` they're recorded nowhere.

## Upload purposes

```ts src/shared/lib/modules/define-module.ts theme={null}
export interface ModuleUploadPurpose {
  key: string;
  mimeTypes: readonly string[];
  maxBytes: number;
  visibility: "public" | "organization";
  resizeImage?: { maxWidth: number };
}
```

* **Fields.** `key` is unique across the registry and part of the storage key (use letters, digits and `-`). `mimeTypes` are types `file-type` detects from bytes. `maxBytes` is in bytes. `visibility` is stored on each row. `resizeImage` converts images to JPEG no wider than `maxWidth`.
* **Who reads.** `listUploadPurposes()` reads the server registry on every call: for the purpose lookup (step 8) and the route limit (step 2). `<FileUpload>` only passes the key.
* **When it applies.** A new `module.ts` needs `npx gato generate`; a new purpose in an existing array works after a rebuild.
* **Declaration errors.** A duplicate `key` (even across modules) or a forbidden type (`image/svg+xml`, `text/html`, `application/xhtml+xml`, `application/xml`, `text/xml`) throws `Duplicate upload purpose key: <key>` or `Upload purpose <key> declares forbidden type <type>` on every read. Typecheck and build pass, but every `POST /api/uploads` returns 500.
* **Text formats.** `text/plain`, `text/csv`, `application/json` have no signature, so a purpose listing them always returns 415.
* **Changing a purpose** affects new files only. A removed purpose rejects new uploads with `unknown_purpose`; existing files still download and delete.
* **The largest `maxBytes` sets the route limit** for every purpose.
* **Without `uploads`** the field type-checks and does nothing.

## The `<FileUpload>` component

```tsx src/features/uploads/components/file-upload.tsx theme={null}
interface FileUploadProps {
  purpose: string;
  accept?: string;
  onUploaded: (upload: UploadResponse) => void;
}
```

* **Props.** `purpose` is the purpose key. `accept` is a hint for the file picker only; the server still validates. `onUploaded` fires on 201 with `{ id, url, fileName, mimeType, size }`.
* **Behavior.** A client component. After a file is chosen it calls `requestConfirmation()` (a dialog in service mode; cancel aborts), posts `file`, `purpose` and any confirmation to `/api/uploads`, shows an `<img>` preview for images and calls `onUploaded`. On 413 it shows "File is too large", on 415 "Unsupported file type", on anything else "Could not upload the file".
* **Not supported.** No disabled state while uploading, no progress, no deletion of the previous file when a new one is chosen, no multiple files.

Because uploading is a `fetch`, not a server action, the component uses `useServiceModeAction().requestConfirmation()` instead of `run`. The route checks the confirmation like a command would. A superadmin in service mode therefore confirms twice: when choosing the file and when submitting the form. See [Superadmin and service mode](https://docs.gatojs.com/concepts/superadmin-and-service-mode.md).

## Use it from your code

The examples below come from a `deliveries` project module where a warehouse worker records a delivery with a photo that only the organization can see. Its `projectModules` entry lists `"requires": ["uploads"]`.

### Declare a purpose

```ts src/features/deliveries/module.ts theme={null}
export default defineModule({
  key: "deliveries",
  nav: [{ href: "/deliveries", labelKey: "nav", icon: "truck", order: 50 }],
  routePrefixes: ["/deliveries"],
  uploadPurposes: [
    {
      key: "delivery-photo",
      mimeTypes: ["image/jpeg", "image/png", "image/webp"],
      maxBytes: 8 * 1024 * 1024,
      visibility: "organization",
      resizeImage: { maxWidth: 1600 },
    },
  ],
});
```

A delivery photo is organization data, so the purpose uses `"organization"`. Use `"public"` only for content meant for everyone: a public URL works signed out and stays cached for a year. The 8 MiB limit also raises the route limit for the whole app. Run `npx gato generate` after adding `module.ts`, and keep the key in a constant (for example `DELIVERY_PHOTO_PURPOSE` in `contracts/`) shared by the form and the command.

### Add `<FileUpload>` to a form

```tsx src/features/deliveries/components/receive-delivery-form.tsx theme={null}
export function ReceiveDeliveryForm() {
  const serviceModeAction = useServiceModeAction();
  const [supplier, setSupplier] = useState("");
  const [photoUploadId, setPhotoUploadId] = useState<string | null>(null);
  const [uploadKey, setUploadKey] = useState(0);

  async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const result = await serviceModeAction.run(receiveDeliveryCommand, {
      supplier,
      photoUploadId,
    });
    if (result?.success) {
      setSupplier("");
      setPhotoUploadId(null);
      setUploadKey((key) => key + 1);
    }
  }

  return (
    <form onSubmit={handleSubmit}>
      {/* … */}
      <FileUpload
        key={uploadKey}
        purpose={DELIVERY_PHOTO_PURPOSE}
        accept="image/jpeg,image/png,image/webp"
        onUploaded={(upload) => setPhotoUploadId(upload.id)}
      />
      {serviceModeAction.dialog}
    </form>
  );
}
```

`<FileUpload>` uploads as soon as a file is chosen; the form keeps only the `id`. Changing `key` after saving remounts the component to clear the preview.

### Store the file ID in an entity

The `Delivery` model has `photoUploadId String? @map("photo_upload_id") @db.Uuid` with no relation to `Upload`. Your command must check that the ID points to a file of the active organization and the right purpose:

```ts src/features/deliveries/services/commands/delivery-commands.ts theme={null}
const { supplier, photoUploadId } = parsed.data;
if (photoUploadId) {
  const photo = await prisma.upload.findFirst({
    where: {
      id: photoUploadId,
      organizationId: context.organizationId,
      purpose: DELIVERY_PHOTO_PURPOSE,
    },
    select: { id: true },
  });
  if (!photo) {
    throw new DomainError("Delivery photo not found");
  }
}
const delivery = await prisma.delivery.create({
  data: { organizationId: context.organizationId, supplier, photoUploadId },
  select: { id: true },
});
```

Without the `organizationId` condition, organization B could attach organization A's file. B still couldn't download it, but the entity would point at someone else's file. The `purpose` condition prevents attaching a file uploaded with other visibility or limits.

### Show the file

The URL is always `/api/uploads/<id>`; store the ID, never the URL or storage key:

```tsx src/app/[locale]/(app)/deliveries/page.tsx theme={null}
{delivery.photoUploadId ? (
  // eslint-disable-next-line @next/next/no-img-element
  <img src={`/api/uploads/${delivery.photoUploadId}`} alt={delivery.supplier} />
) : null}
```

The browser sends the session cookie, so organization files work in `<img>` on app pages. A member of several organizations sees the photo only while the file's organization is active.

### Delete the file with its entity

```ts src/features/deliveries/services/commands/delivery-commands.ts theme={null}
await prisma.delivery.deleteMany({
  where: { id: delivery.id, organizationId: context.organizationId },
});
if (delivery.photoUploadId) {
  const removed = await deleteUploadCommand(
    { id: delivery.photoUploadId },
    confirmation,
  );
  if (!removed.success) {
    logger.warn("delivery photo left in storage", {
      uploadId: delivery.photoUploadId,
      error: removed.error,
    });
  }
}
```

Pass the service mode confirmation through, because `deleteUploadCommand` checks it again. `deleteUploadCommand` has its own rules: a `member` can't delete a photo someone else uploaded. This example deletes the entity first and only logs a failed file delete. To block entity deletion when the file can't be deleted, call `deleteUploadCommand` first and stop on error. If one file can be attached to several entities, add `@unique` to the column or check for other references before deleting.

### Code that works without the module

An `uploadPurposes` declaration builds without `uploads` and starts working after `gato add uploads`. `<FileUpload>`, `deleteUploadCommand` and `prisma.upload` don't: they need the module. A feature that handles files lists `uploads` in `requires`.

## Security

* **Organization from the session.** The form's `organizationId` is ignored; storage keys start with `orgs/<organizationId>/`.
* **Access by row, not path.** Organization files are served only to sessions with the file's organization active; everything else is a 404.
* **`public` means public.** The URL works signed out and may be cached for a year. Never use a public purpose for private data.
* **Your command checks entity file IDs** for organization and purpose.
* **Type from bytes; SVG, HTML and XML forbidden.** Responses carry `nosniff` and a sandbox CSP, so a file can't run script on your domain.
* **File names in headers** are sanitized and encoded.
* **Images go through `sharp`** with a pixel limit, and stored JPEGs have no EXIF (including phone GPS data).
* **Size limit before reading the body.** Oversized `Content-Length` and missing sessions are rejected first; no `Content-Length` returns 411.
* **Service mode** applies to uploads and deletes.
* **Orphaned objects** stay in storage.
* **Unsafe storage configuration stops startup** in production.
* **S3 secrets** have no rule against example values; set real ones in production.

## Testing

**Unit tests without MinIO.** The module's unit tests use no real storage: `local` is tested in a `mkdtemp` directory and `s3` with a mocked `S3Client`. To store a real file in your own unit test, mock `@/env` with `STORAGE_PROVIDER: "local"` and `STORAGE_LOCAL_PATH` pointing to a temp directory, then call the real `putObject` and `getObject`.

**Integration tests with MinIO.** `src/test/integration/setup-env.ts` sets `STORAGE_PROVIDER=s3` with the endpoint from `INTEGRATION_S3_ENDPOINT` (default `http://localhost:9000`), the bucket from `INTEGRATION_S3_BUCKET` (default `<slug>-uploads`), `minioadmin` credentials and path-style addressing. `.env` doesn't apply, so integration tests always need MinIO:

```bash theme={null}
docker compose --profile s3 up -d
npm run test:integration
```

For MinIO on another port:

```bash theme={null}
INTEGRATION_S3_ENDPOINT=http://localhost:9100 npm run test:integration
```

The bucket must exist; tests don't create it.

**Feature integration test.** Call `createUpload` with a real PNG generated by `sharp`, your commands and `readUploadForDownload` against a real database and MinIO. Mock only framework I/O and the session:

```ts src/features/deliveries/services/__tests__/delivery-photo.integration.test.ts theme={null}
async function uploadPhoto(width: number): Promise<{ id: string; key: string }> {
  const png = await sharp({
    create: { width, height: 100, channels: 3, background: "#336699" },
  })
    .png()
    .toBuffer();
  const formData = new FormData();
  formData.append(
    "file",
    new File([new Uint8Array(png)], "delivery.png", { type: "image/png" }),
  );
  formData.append("purpose", "delivery-photo");
  const result = await createUpload(formData);
  expect(result.status).toBe(201);
  const id = "id" in result.body ? result.body.id : "";
  const record = await prisma.upload.findUniqueOrThrow({ where: { id } });
  writtenKeys.push(record.key);
  return { id, key: record.key };
}

it("rejects a photo ID from another organization", async () => {
  await signInAs(world.alice, world.orgA);
  const photo = await uploadPhoto(800);
  await signInAs(world.bob, world.orgB);

  const result = await receiveDeliveryCommand({
    supplier: "Wholesale B",
    photoUploadId: photo.id,
  });

  expect(result).toEqual({ success: false, error: "Delivery photo not found" });
  await expect(prisma.delivery.count()).resolves.toBe(0);
});
```

Delete written objects in `afterAll` with `deleteObject`. Also cover resizing (a 3000 px PNG stored as a 1600 px JPEG under `orgs/<orgId>/delivery-photo/<id>.jpg`), download headers per session, and entity deletion removing the row and object. Without `audit-logs` you don't need to mock `trackAudit`. To unit test a component that renders `<FileUpload>`, stub `fetch` and wrap it in `NextIntlClientProvider` and `ServiceModeProvider`. See [Testing](https://docs.gatojs.com/guides/testing.md).

## Troubleshooting

Storage validation errors appear at server startup as an environment report followed by exit code 1. The kit currently prints these lines in Polish:

| Report line | Meaning | Fix |
| - | - | - |
| `- STORAGE_LOCAL_PATH: wymagana w produkcji przy STORAGE_PROVIDER=local: wskaż trwały katalog` | Required in production with `local`: point to a persistent directory. | Set an absolute `STORAGE_LOCAL_PATH`, or use `STORAGE_PROVIDER=s3`. |
| `- STORAGE_LOCAL_PATH: w produkcji poza Railway musi być ścieżką bezwzględną: wskaż trwały katalog` | Outside Railway in production, the path must be absolute (for example `./volumes/uploads` from `.env`). | Use an absolute path; in the Docker image, `/app/volumes/uploads`. `npm run dev` accepts relative paths. |
| `- STORAGE_PROVIDER: na Railway bez wolumenu pliki zginą przy redeployu: podepnij wolumen albo ustaw STORAGE_PROVIDER=s3` | On Railway without a volume, files would be lost on redeploy. | Attach a volume or switch to a bucket. |
| `- STORAGE_LOCAL_PATH: musi leżeć wewnątrz wolumenu Railway (<path>)` | The path must be inside the Railway volume. | Unset `STORAGE_LOCAL_PATH` to use the volume, or point inside it. |
| `- STORAGE_PROVIDER: dozwolone wartości: local, s3` | Only `local` and `s3` are allowed (not `minio`, `r2`). | MinIO, Cloudflare R2 and Railway buckets all use `s3`. |
| `- S3_ENDPOINT: …`, `- S3_BUCKET: …` and similar | A required `S3_*` variable is missing with `s3`. | Set the variable. |
| `- S3_FORCE_PATH_STYLE: Invalid option: expected one of "true"\|"false"` | Bad boolean. | Use `true` or `false`. |

Runtime problems:

| Symptom | Cause | Fix |
| - | - | - |
| "Could not upload the file"; the route returns 500 `storage_failed` | With `local`: the process can't write to the directory (for example a Docker volume mounted where the image doesn't prepare permissions). With `s3`: unreachable storage, wrong endpoint, credentials or region, missing bucket, wrong path style. | With `local`, mount the volume at `/app/volumes/uploads` or grant write access to UID 1001. With `s3`, check MinIO or your provider settings. The log line `upload putObject failed` reaches your OTLP collector when `OTEL_EXPORTER_OTLP_ENDPOINT` is set. |
| Files disappear after `npm run build` | `STORAGE_LOCAL_PATH` points inside `.next/standalone`, which the build deletes. | Use a persistent directory outside `.next`. |
| Older files return 404 after changing `STORAGE_PROVIDER` | Files stayed in the previous storage. | Switch back, or copy them: both providers use the same key layout. |
| Every upload returns 500; logs show `Duplicate upload purpose key` or `declares forbidden type` | A broken purpose declaration. | Fix the declaration. |
| 411 `length_required` | The client sends a body without `Content-Length` (chunked or streamed). | Send `FormData` built from a file; non-browser clients must set the header. |
| 413 for a file that looks smaller than the limit | `maxBytes` is in bytes (`5 * 1024 * 1024` = 5,242,880), or the file went to another purpose. | Check the size in bytes, `maxBytes` and `purpose`. |
| 415 for CSV, TXT or JSON | Text formats have no signature. | The module doesn't accept them. |
| 415 for an image with a correct extension | The contents are another type (SVG or HTML renamed to `.png`). | Upload a real image. |
| 400 `unknown_purpose` | The purpose isn't declared, or the feature's `module.ts` isn't in the registry. | Declare it; run `npx gato generate` for a new `module.ts`. |
| An organization file returns 404 to a signed-in user | Another organization is active, the user left, or the object is missing. | Switch organization. |
| A `.png` upload is stored as `image/jpeg` | Purposes with `resizeImage` store every image as JPEG; `fileName` keeps the client name. | Expected; use `mimeType`. |
| Permission error when deleting | A `member` deletes someone else's file. | The uploader, an owner or an admin can delete it. |
| Storage keeps growing | Orphaned objects. | Call `deleteUploadCommand` when deleting entities; reconcile storage against the `key` column. |
| Integration tests fail with a connection or S3 error | No MinIO on `localhost:9000`, or no `<slug>-uploads` bucket. | Run `docker compose --profile s3 up -d`, or set `INTEGRATION_S3_ENDPOINT` and `INTEGRATION_S3_BUCKET`. |
| `TS2307: Cannot find module '@/features/uploads/…'` | The module isn't installed. | `npx gato add uploads`, or remove the import. |
| `gato remove uploads` refuses, naming a module | A project module requires `uploads`. | Remove the file code and `requires` entry, or keep the module. |

## Reference

### Environment variables

| Variable | Required | Rule | Kit values |
| - | - | - | - |
| `STORAGE_PROVIDER` | No | `local` or `s3`; empty or missing means `local` | `.env`: `local`; integration tests: `s3`; e2e: `local` |
| `STORAGE_LOCAL_PATH` | In production with `local` outside Railway | Directory; absolute in production outside Railway; inside the volume on Railway | `./volumes/uploads` |
| `RAILWAY_ENVIRONMENT_ID`, `RAILWAY_VOLUME_MOUNT_PATH` | No; set by Railway | Production rules and default directory with `local` | unset |
| `S3_ENDPOINT` | With `s3` | URL | `http://localhost:9000` |
| `S3_REGION` | No | Non-empty, default `auto` | `auto` |
| `S3_ACCESS_KEY_ID` | With `s3` | Non-empty | `minioadmin` |
| `S3_SECRET_ACCESS_KEY` | With `s3` | Non-empty | `minioadmin` |
| `S3_BUCKET` | With `s3` | Non-empty | `<slug>-uploads` |
| `S3_FORCE_PATH_STYLE` | No | `true` or `false`, default `false` | `true` |
| `MINIO_PORT`, `MINIO_CONSOLE_PORT` | No | Read by Docker Compose only | `9000`, `9001` |
| `INTEGRATION_S3_ENDPOINT`, `INTEGRATION_S3_BUCKET` | No | Read by integration test setup only | unset |
| `E2E_UPLOADS_DIR` | No | Read by `e2e/env.ts`; must be absolute | unset (temp directory) |

See [Environment variables](https://docs.gatojs.com/configuration/environment-variables.md) for the full list.

### Routes

| Route | Access | Responses |
| - | - | - |
| `POST /api/uploads` | Session with an active organization; confirmation in service mode | 201 `{ id, url, fileName, mimeType, size }`; 400 `invalid_input`, `unknown_purpose`, `empty`, `invalid_image`; 401/403 `unauthorized`; 403 service mode; 411 `length_required`; 413 `too_large`; 415 `unsupported_type`; 500 `storage_failed`. |
| `GET /api/uploads/<id>` | `public`: anyone; `organization`: session with the file's organization active | 200 with the file and headers; 404 with no body. |

### Purposes and audit actions

| String | Kind | Details |
| - | - | - |
| `editor-image` | purpose (kit) | `image/jpeg`, `image/png`, `image/webp`; 5 MiB; `public`; resized to 1200 px JPEG |
| `upload.created` | audit action | "File uploaded" |
| `upload.deleted` | audit action | "File deleted" |

Forbidden in every purpose: `image/svg+xml`, `text/html`, `application/xhtml+xml`, `application/xml`, `text/xml`.

### Log messages

| Message | Meaning |
| - | - |
| `upload putObject failed` | Storing the object failed; response 500. |
| `upload record create failed` | Storing the row failed; the object is rolled back. |
| `upload rollback failed` | Rolling back the object failed; it's orphaned. |
| `upload deleteObject failed` | Deleting the object failed; the row is gone, the object is orphaned. |
| `Duplicate upload purpose key: <key>` | Two purposes share a key. |
| `Upload purpose <key> declares forbidden type <type>` | A purpose lists a forbidden type. |

### Files

| File | Export | Purpose |
| - | - | - |
| `components/file-upload.tsx` | `FileUpload` | File input, upload, error message, image preview. |
| `services/commands/create-upload.ts` | `createUpload` | Upload validation and storage for the route. |
| `services/commands/upload-commands.ts` | `deleteUploadCommand` | File deletion. |
| `services/read-upload.ts` | `readUploadForDownload` | Download access check and headers. |
| `services/upload-purposes.ts` | `listUploadPurposes`, `resolveUploadPurpose`, `maxUploadBytes`, `FORBIDDEN_MIME_TYPES` | Purposes from the registry. |
| `services/storage.ts` | `putObject`, `getObject`, `deleteObject` | Dispatches to the configured provider. |
| `services/storage-env.ts` | `resolveStorageEnv` | Provider choice and production rules. |
| `services/local-storage.ts` | `createLocalStorage` | `local` provider with path checks. |
| `services/s3-storage.ts` | `createS3Storage` | `s3` provider. |
| `env.ts` | `envSchema` | Storage variable validation. |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.