Skip to main content
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.
  • 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

Install and remove

1

Add the module

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)

4

Create the migration

Commit it. After --no-install, also run npm run db:generate.

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. 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. 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 for choosing and hosting storage in production, and Railway 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.
  • 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: Profiled services don’t start without the profile. To work on S3, set STORAGE_PROVIDER=s3 in .env and run:
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.

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 the module adds

Module definition

The Upload model

prisma/schema/uploads.prisma, table uploads, enum UploadVisibility (PUBLIC, ORGANIZATION): 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:
  • 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: 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

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.

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

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

Upload purposes

src/shared/lib/modules/define-module.ts
  • 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

src/features/uploads/components/file-upload.tsx
  • 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.

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

src/features/deliveries/module.ts
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

src/features/deliveries/components/receive-delivery-form.tsx
<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:
src/features/deliveries/services/commands/delivery-commands.ts
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:
src/app/[locale]/(app)/deliveries/page.tsx
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

src/features/deliveries/services/commands/delivery-commands.ts
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:
For MinIO on another port:
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:
src/features/deliveries/services/__tests__/delivery-photo.integration.test.ts
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.

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: Runtime problems:

Reference

Environment variables

See Environment variables for the full list.

Routes

Purposes and audit actions

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

Log messages

Files