Images, PDFs & upload safety

Separate public catalog media from private user PDFs, enforce server-side MIME and size checks, and serve fast images without leaking sensitive files.

Threat model: why user uploads need strict boundaries

Accepting files from real users introduces security and performance risks that plain form inputs never trigger. Once a live app accepts profile photos, product shots, tax invoices, or client PDFs, five predictable failure modes emerge if storage boundaries stay loose:

  • Leaked private documents. Saving invoices or resumes in a public path under a random URL means anyone who forwards, bookmarks, or logs that URL can download the file indefinitely without signing in.
  • Executable file injection. Accepting untrusted .svg or .html files and rendering them inline on your app domain lets attackers execute arbitrary JavaScript inside a logged-in admin's browser.
  • Filename collisions and overwrites. Storing uploads under raw client filenames (receipt.pdf) causes one user's upload to overwrite another customer's file or break URLs with unsafe characters.
  • Unbounded mobile camera uploads. Modern phones shoot 15–40 MB photos; rendering uncompressed originals inside product grids stalls mobile page loads and inflates storage consumption.
  • Orphaned storage files. Deleting a product or replacing an avatar in your database without deleting the underlying binary object leaves unused files accumulating silently.

ExaSpark keeps Preview and Live storage buckets strictly isolated, so testing upload guards and cleanup flows in Preview never risks exposing or altering live customer files.

Public catalog media vs private user documents

Every upload type in your app belongs in one of two explicit visibility tiers. Never mix public catalog images and private customer PDFs inside the same access pattern or folder prefix.

Architecture aspectPublic media (`public/...`)Private documents (`private/...`)
Typical filesProduct photos, hero banners, blog covers, venue galleriesTax invoices, payment receipts, signed waivers, resumes, client briefs
Read authorizationOpen to all visitors; write access restricted to AdminsStrictly authenticated — server checks owner_id === session.user.id or role === 'admin'
Delivery mechanismDirect cacheable CDN URLs for fast page loadsAuthenticated backend stream or short-lived signed download URL (60–300 seconds)
Cache headersLong-lived public cache (max-age=31536000, immutable)Cache-Control: private, no-store so shared browsers never cache sensitive PDFs
Database metadatastorage_key, alt_text, width, height, sort_orderstorage_key, owner_id, original_filename, mime_type, size_bytes

Why short-lived signed URLs protect private PDFs

When a logged-in customer clicks Download invoice PDF, your app backend first authenticates the session cookie and checks ownership against your Cloud database (invoice.user_id === session.user.id).

Only after that authorization check passes does your server either stream the file directly with safe download headers or mint a temporary signed URL valid for 60 to 300 seconds. Even if the customer pastes that link into an email thread later, the signature expires automatically.

Enforcing MIME type, magic-byte, and file size rules

Browser <input type="file" accept=".pdf,image/*"> attributes improve usability, but they provide zero security. Any visitor can bypass client-side filters using browser developer tools or direct HTTP requests.

Server-side MIME allowlists and magic bytes

Always re-validate uploaded files on the server before saving them to storage. Never trust the filename extension or browser Content-Type header alone.

Inspect the file's leading magic bytes (%PDF- for PDFs, FF D8 FF for JPEG, 89 50 4E 47 for PNG, RIFF....WEBP for WebP) so a renamed .html payload cannot pass as a .jpg.

Upload typeServer MIME allowlistMax sizeSafe delivery rule
Avatarimage/jpeg, image/png, image/webp2–5 MBResized WebP/JPEG; strip EXIF GPS data
Product photoimage/jpeg, image/png, image/webp5–10 MBPublic immutable URL; set aspect ratio and alt_text
PDF documentapplication/pdf10–20 MBPrivate signed download with Content-Disposition: attachment
CSV importtext/csv5–10 MBParse server-side; reject formula-injection cells
SVG / HTMLBlocked unconditionally0Reject image/svg+xml, text/html, .exe, and .js

Safe response headers for private downloads

When streaming user-uploaded documents through your backend, send defensive headers so browsers download files safely instead of executing embedded scripts:

http
HTTP/1.1 200 OK
Content-Type: application/pdf
Content-Disposition: attachment; filename="invoice-ord-1042.pdf"
X-Content-Type-Options: nosniff
Cache-Control: private, no-store, max-age=0

Keeping image-heavy pages fast on mobile

  • Prefer WebP or compressed JPEG. Converting phone uploads to WebP cuts payload size by 50–75% with zero visible quality loss on product cards.
  • Lock image dimensions. Set explicit width/height or CSS aspect-ratio on every card so layouts never jump while thumbnails load.
  • Eager-load heroes, lazy-load grids. Load above-the-fold hero shots with fetchpriority="high" and apply loading="lazy" to below-the-fold cards.
  • Strip EXIF metadata. Removing smartphone EXIF headers drops embedded home GPS coordinates automatically.

Implementing a safe upload and signed-download flow

  1. Validate in UI, then re-verify on the server

    Give instant browser feedback, then enforce MIME allowlists, magic bytes, and byte caps server-side.

  2. Generate collision-free scoped keys

    Store files under paths like public/products/<product_id>/<uuid>.webp or private/invoices/<user_id>/<uuid>.pdf, never raw filenames.

  3. Record ownership metadata in Cloud

    Save storage_key, owner_id, original_filename, mime_type, size_bytes, and visibility in a relational table.

  4. Gate private downloads server-side

    Verify session and ownership before minting a 60–300 second signed URL or streaming with Content-Disposition: attachment.

  5. Delete replaced objects cleanly

    Remove old storage binaries inside the same authorized server handler whenever an item is replaced or deleted.

json
{
  "id": "file_01JA2K9P4T",
  "visibility": "private",
  "owner_id": "usr_418",
  "record_type": "client_contract",
  "storage_key": "private/contracts/usr_418/9c2e4b11.pdf",
  "original_filename": "studio-retainer-signed.pdf",
  "mime_type": "application/pdf",
  "size_bytes": 418920
}
Starter prompt · App

Build two upload flows using managed storage and a `file_attachments` table: (1) Admin product gallery accepting up to 6 public JPEG/PNG/WebP images per product (max 5 MB each, saved under `public/products/<product_id>/<uuid>.<ext>`, rendered with `aspect-ratio`, `alt_text`, and `loading="lazy"`); (2) Client uploads accepting only verified `application/pdf` files up to 15 MB stored privately under `private/documents/<user_id>/<uuid>.pdf`. Reject SVGs and mismatched magic bytes server-side, serve private PDFs through an ownership-checked signed download route with `Content-Disposition: attachment` and `X-Content-Type-Options: nosniff`, and delete storage objects on removal.

Troubleshooting upload and media security issues

SymptomMost likely root causeReliable fix
Private PDF opens in incognitoSaved to public path or skipped session checkMove under private/... and verify owner_id or admin before signing
Phone upload hits `413` errorUncompressed 20 MB photo exceeded byte capResize client-side before upload and show max size clearly
Broken product photos on LiveHard-coded Preview media URLsRe-upload catalog images in Live admin or bundle static brand assets
Slow mobile catalog LCPRaw 4000px PNGs rendered in small cardsConvert to WebP, size appropriately, and lazy-load off-screen cards
SVG flags security reviewUntrusted SVG uploads allowed inlineRestrict user images strictly to image/jpeg, image/png, and image/webp
Storage grows after deletesDelete route removed DB row onlyDelete the storage object inside the same server delete handler

Next steps

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

From the blog