File storage & uploads

Accept user uploads and serve product media with managed project storage — backed by type checks, size limits, and role-scoped access rules.

Why files live in object storage, not your database

Every ExaSpark project comes with managed file storage built right alongside your relational database. Understanding how the two work together keeps your app fast, reliable, and cost-efficient as uploads grow.

Relational databases are engineered for structured rows, searches, and joins — not megabytes of binary image or PDF data. Storing raw files directly inside database columns bloats backups, slows queries across unrelated fields, and wastes memory every time a table loads.

Instead, your app uploads binary files (profile photos, product galleries, receipts, resumes, contracts) to managed object storage and saves only lightweight metadata (storage_key, file_name, mime_type, size_bytes, owner_id) in a database table.

text
[User Browser]
   |  1. Picks avatar.webp (420 KB) -> client checks type & size
   v
[App Backend]
   |  2. Verifies session, role, MIME type & byte limit
   |  3. Uploads binary to isolated project storage:
   |     avatars/<user_id>/<uuid>.webp
   v
[Cloud Database]
   |  4. Saves metadata row (storage_key, mime_type, size_bytes, visibility)
   |     and updates users.avatar_key

Public assets vs private scoped files

Not every uploaded file should be reachable by anyone with a link. Decide up front whether each upload category is public (openly viewable by visitors) or private (protected behind server-side session and role checks).

File categoryVisibilityExamplesHow access should work
Catalog & brand mediaPublicProduct photos, hero banners, blog cover images, venue galleriesServed directly via cacheable public URLs for fast page loads
User profile avatarsPublic or Member-onlyAccount headshots, team icons, public reviewer photosPublic on community sites; member-scoped on private internal portals
Financial & legal docsPrivate (owner + admin)Payment receipts, tax invoices, signed waivers, wholesale quotesServer verifies owner_id or admin role before streaming or signing URL
Personal submissionsPrivate (owner + staff)Job resumes, medical intake PDFs, client briefs, student assignmentsRestricted strictly to the uploader and authorized staff roles

How private access rules stay safe

Never protect sensitive PDFs or customer receipts merely by using a long random URL in a public bucket. Once a public URL is forwarded, indexed, logged in browser history, or pasted into chat, anyone on the internet can download the document indefinitely.

For private files, require your backend to verify the caller's session and permission rules first (matching file.owner_id === session.user.id or role === 'admin'). Only after that check passes should the server stream the file or return a short-lived signed download link. See Authentication & roles.

Preview and Live storage stay isolated

Just like databases and user accounts, Preview and Live use separate file storage buckets. Uploading test product shots or deleting sample invoices in Preview never touches or exposes real customer uploads in Live. Read Preview vs Live isolation for the full boundary breakdown.

Validating uploads before saving

Treat every user upload as untrusted input. Validate files in the browser for instant user feedback, and enforce the exact same rules on the server so bypassed forms cannot sneak oversized or malicious files into storage.

Allowed file types and safe rendering

Specify an explicit allowlist of MIME types and extensions for every upload field rather than accepting "any file."

  • Images (avatars & product galleries). Allow image/jpeg, image/png, and image/webp. Avoid allowing raw image/svg+xml from untrusted users — SVG files can embed executable JavaScript if served inline on your app's domain.
  • Documents (invoices, resumes, forms). Allow application/pdf (and .docx or .csv only when your workflow truly needs them). Always serve untrusted downloads with a safe Content-Disposition: attachment header when downloading.
  • Blocked types. Reject executable binaries, HTML files, and shell scripts unconditionally on the server.

Practical file size limits

Setting clear size caps prevents slow mobile uploads, accidental 80 MB camera uploads, and runaway storage bills.

Upload typeRecommended max sizeProcessing tip
Profile avatar2–5 MBResize or display inside a square object-cover frame; prefer WebP or JPEG
Product gallery photo5–10 MBGenerate clean hero aspect ratios and lazy-load thumbnails below the fold
PDF receipt, waiver, or resume10–20 MBShow file name, page/size badge, and a clear upload progress bar
CSV data import5–10 MBValidate required headers and preview row count before writing to tables

Filename hygiene and unique keys

Never save an upload directly under the raw filename a user sends (such as resume.pdf or ../../logo.png). Two users uploading receipt.pdf would overwrite each other, and special path characters can break URLs.

Always generate a deterministic, collision-free storage key scoped by resource — for example receipts/<order_id>/<uuid>.pdf — while keeping the user's original display label in a separate original_filename database column.

Linking uploads cleanly to database records

Choose between a single column or a dedicated attachments table depending on whether a record owns one file or many.

  • Single file (one-to-one). Add avatar_key on users or cover_image_key on posts when a record always has zero or one image.
  • Galleries & multi-file records (one-to-many). Create a child table such as product_images or ticket_attachments with sort_order, alt_text, and a foreign key pointing to the parent row.
json
{
  "id": "att_01J9X4K8M2",
  "record_type": "expense_claim",
  "record_id": "exp_4082",
  "owner_id": "usr_912",
  "storage_key": "private/expenses/exp_4082/7f3c9a21.pdf",
  "original_filename": "hotel-receipt-nov.pdf",
  "mime_type": "application/pdf",
  "size_bytes": 284910,
  "visibility": "private",
  "created_at": "2026-11-18T14:22:09Z"
}

Follow a clean four-step lifecycle so storage objects and database rows never drift out of sync.

  1. Validate type and size first

    Check extension, MIME type, and maximum byte size in the UI for instant feedback, then re-verify them on the server before accepting the upload.

  2. Upload with a unique scoped key

    Store the binary file under a non-colliding folder path (public/products/... or private/receipts/...) matching its visibility tier.

  3. Commit the database metadata row

    Save the returned storage key, MIME type, byte size, and owner ID in your table so queries stay fast and auditable.

  4. Clean up replaced or deleted files

    When a user swaps an avatar or an admin deletes a product, delete the old storage object (or mark it for cleanup) so unused files do not accumulate silently.

Starter prompt · App

Add two upload flows using managed file storage: (1) Admin product gallery uploads supporting up to 6 public JPEG/PNG/WebP images per product (max 5 MB each, drag-to-reorder via `sort_order`, with alt text); (2) Member receipt uploads on expense claims accepting only PDF or JPEG/PNG up to 10 MB stored privately so only the claim owner and Admins can download them through an authenticated server route. Clean up old files when an attachment is removed.

Avoiding broken media and leaked documents

Most file bugs surface right after publishing or once real customers start uploading photos from phones. Use this diagnostic table to catch and fix them quickly.

SymptomMost common root causeReliable fix
Broken image icon after PublishSeeded Preview image URLs were hard-coded into copy instead of uploaded to Live or bundled as static assetsBundle brand artwork inside the app or re-upload catalog media through your Live admin panel
Private PDF opens in an incognito browserFile was saved to a public path with no server-side session checkMove uploads to private storage and serve downloads only through an authenticated, ownership-checked endpoint
Two users overwrite each other's filesStorage key used the raw user filename (invoice.pdf) without a unique IDPrefix keys with <entity_id>/<uuid>.<ext> and store the original name as database metadata
Mobile gallery loads slowlyMulti-megabyte raw phone photos render at full resolution inside tiny cardsEnforce size limits, serve compressed WebP/JPEG variants, and enable image lazy loading
Orphaned files remain after deleteDeleting the database row did not remove the underlying object in storageDelete the storage object inside the same server delete handler right after verifying permissions

Next steps

Still have a question?Ask our team and other builders on Discord.

From the blog