Secure authentication and database setup for Supabase prompts

How to Add File Uploads to a Vibe-Coded App (Supabase Storage Step-by-Step)

File uploads in a vibe-coded app look trivial until RLS blocks your bucket, MIME checks live only in React, and public URLs leak every user’s resume. Supabase Storage is the default pairing for the 2026 vibe stack — S3-compatible buckets with Postgres policies — but AI codegen routinely skips signed URLs, size limits, and path naming that prevents overwrite attacks. This step-by-step guide walks from bucket creation to production-hardened uploads in a Next.js app. Updated November 2026.

File upload interface connected to Supabase Storage in a vibe-coded web application
Upload UI is the easy part — bucket policies and auth paths separate demos from products.

Set up auth and database first via prompts for Supabase auth and database setup, then return here for storage. Deploy with deploy to Vercel only after env vars for Supabase URL and anon key are scoped correctly.

Table of contents

  1. Upload architecture choices
  2. Step 1 — Create and lock down a bucket
  3. Step 2 — Storage RLS policies
  4. Step 3 — Client upload with signed URL or direct
  5. Step 4 — Server-side validation
  6. Step 5 — Display and delete files
  7. AI-generated bugs that break uploads
  8. Production checklist
  9. FAQ

Upload architecture choices

Supabase Storage supports:

  • Direct client upload — Browser uses supabase-js with user JWT; RLS on storage.objects enforces access
  • Signed upload URL — Server mints short-lived URL; client PUTs file without broad bucket credentials
  • Server proxy upload — API route receives multipart form; server uploads via service role (use sparingly — bandwidth on your compute)

For vibe-coded SaaS with logged-in users, direct client upload with strict RLS is the sweet spot. Signed URLs add complexity but help when you need extra server validation before bytes hit the bucket.

PatternProsCons
Direct + RLSSimple, scales bandwidthPolicy mistakes expose data
Signed URLServer gatekeeps mintingExtra round trip
Server proxyFull server validationCost, size limits on Vercel
Public bucketEasy CDN linksNever for private user files

Step 1 — Create and lock down a bucket

In Supabase Dashboard → Storage → New bucket:

  1. Name: avatars or user-files — one bucket per sensitivity class
  2. Public: off for private user content
  3. File size limit: set in bucket settings (e.g., 2MB avatars, 10MB documents)
  4. Allowed MIME types: restrict where possible (image/jpeg, image/png, application/pdf)

Prompt your agent: “Create private Supabase bucket user-files, max 10MB, allowed MIME image/png, image/jpeg, application/pdf. Generate SQL for storage policies — do not make bucket public.”

Step 2 — Storage RLS policies

Storage uses storage.objects policies. Path convention matters: store files as {userId}/{uuid}.{ext} so policies can match (storage.foldername(name))[1] = auth.uid()::text.

Minimum policies for private user uploads:

  • INSERT — authenticated users only; path prefix must equal their user id
  • SELECT — same user can read own objects (or expand for team features later)
  • DELETE — owner only
  • UPDATE — usually deny; upload new version instead

Test policies in SQL editor with set request.jwt.claim.sub = 'user-uuid'; patterns or via authenticated client in app. AI often generates “allow all authenticated” INSERT — fix before ship.

Supabase Storage row level security policies restricting file access by authenticated user ID
Wrong storage RLS is worse than no uploads — it looks working until another user guesses a path.

Step 3 — Client upload with signed URL or direct

Direct upload flow in Next.js client component:

  1. User selects file; client validates size/type before request
  2. Generate path: ${user.id}/${crypto.randomUUID()}.${ext}
  3. supabase.storage.from('user-files').upload(path, file, { upsert: false })
  4. On success, save path or public signed URL metadata in Postgres profile row
  5. Show progress and error states — AI skips these

For signed URL flow, server route validates session, creates createSignedUploadUrl (or upload token pattern per current supabase-js API), client uploads to returned URL. Prefer official Supabase docs version pinned in your project.

Never expose SERVICE_ROLE_KEY in client bundles. Anon key plus RLS is correct for direct uploads.

Step 4 — Server-side validation

Client checks are UX; server checks are security. Add API route or Edge Function when:

  • Files must be scanned or transformed (resize images)
  • Upload counts per day are limited
  • Metadata must be written atomically with upload record

Validation checklist:

  • Max bytes enforced server-side
  • MIME sniffing — do not trust file extension alone
  • Reject path traversal in filenames
  • Rate limit per user
  • Virus scan hook for compliance-sensitive apps

Image avatars: use server or Supabase image transformation to strip EXIF if privacy matters.

Step 5 — Display and delete files

Private files need signed download URLs with expiry:

supabase.storage.from('user-files').createSignedUrl(path, 3600)

Store stable object path in database; regenerate signed URL on page load. Do not store expired signed URLs in DB as permanent links.

Delete flow: remove object from storage and clear DB column in one user action; handle orphaned files with periodic cleanup job if uploads fail mid-transaction.

AI-generated bugs that break uploads

BugSymptomFix
Public bucket for “easier URLs”Anyone with link reads filePrivate bucket + signed URLs
Service role in browserGod-mode key in bundleAnon key + RLS only client-side
upsert: true on user pathsOverwrite attacksUUID filenames; upsert false
No auth on upload componentAnonymous uploads burn quotaRequire session before picker
Client-only size checkLarge file bypass via curlBucket max + server validation
Hardcoded bucket name driftWorks local, fails prodEnv var or single constants file

Run the security checklist on any upload feature before beta users.

Image optimization after upload

User-uploaded photos crash layout and PageSpeed when served as 4000px originals. Pipeline options for vibe-coded apps:

  • Client-side resize — canvas resize before upload for avatars; fast UX, not trustworthy alone
  • Supabase image transformation — render variant URLs with width/height params on storage paths
  • Server sharp pipeline — API route or Edge Function generates WebP thumbnail after upload event

Prompt pattern: “After avatar upload to user-files/{userId}/{uuid}.jpg, store path in profiles.avatar_path; display via Supabase transform URL width 128 for nav, 512 for profile page.” Test Lighthouse after — AI uploads without transforms routinely fail CWV on profile-heavy apps.

Multi-file and drag-drop uploads

Single file upload extends to multi-file with parallel uploads capped at 3 concurrent — unlimited parallel exhausts mobile bandwidth and Supabase rate limits. Track per-file progress in UI state array; fail one file without blocking others when possible.

Path pattern for batch: {userId}/batch-{batchId}/{uuid}.{ext} enables cleanup job if user abandons wizard mid-flow. Store batch metadata in Postgres when uploads belong to a form submission — not only storage paths in isolation.

Error handling users actually see

Map Supabase storage errors to human copy:

ErrorUser messageDeveloper action
413 / payload too largeFile over 10MB limitVerify bucket max matches UI copy
403 RLSPermission denied — re-loginFix policy path prefix
Invalid MIMEPDF and PNG onlyAlign allowlist client and bucket
DuplicateFile already uploadedUUID paths; avoid upsert

Log storage error codes server-side; never expose raw PostgREST messages to users — they leak schema hints.

Testing uploads before beta

  1. Two test accounts upload simultaneously — no cross-read
  2. Attempt upload while logged out — blocked
  3. Upload EXE renamed .png — rejected at bucket or MIME check
  4. Upload at exact size limit and limit+1 byte
  5. Delete user account — verify storage objects removed or scheduled

File uploads in vibe-coded apps fail reviews when testers skip the cross-user read test — the bug that ships most often. Add upload tests to your pre-launch checklist beside auth and billing — three amigos of vibe-coded production incidents.

Production checklist

  • Bucket private; policies tested with two user accounts cross-access
  • File limits in bucket settings match product docs
  • CORS configured if uploading from alternate domain
  • Monitoring on storage quota and error rates in Supabase dashboard
  • Backup strategy for critical user documents
  • GDPR delete: user delete removes storage objects

File uploads in vibe-coded apps ship in an afternoon when path conventions and RLS are planned first — not patched after a public bucket scare.

Compliance uploads: resumes, IDs, health forms

Higher-risk upload categories need retention policies and encryption at rest — Supabase Storage encrypts at rest by default, but your app logic must enforce who accesses what and when to delete. Add columns: uploaded_at, expires_at, document_type. Cron job deletes storage object and row when retention window closes.

Prompt for regulated-ish verticals: “Add document upload with 90-day retention; nightly edge function deletes expired storage paths and DB rows; audit log table append-only for access events.” AI rarely adds retention without explicit prompt — plan compliance in spec, not post-launch panic.

CDN and caching signed URLs

Signed URLs expire — do not cache them in CDN edge rules as static assets. Cache immutable public assets separately from private user content. For avatar public CDN pattern (discouraged for PII), use separate public bucket with user consent only — default remains private bucket plus short signed reads.

Next.js Image component with signed URLs requires careful refresh logic — regenerate signed URL when Image onError fires expired. Vibe-coded apps show broken avatar circles in production when signed URL TTL is shorter than page session length.

Mobile upload UX that ships

Mobile users upload from camera roll — accept image/* and capture="environment" on input when product needs photos. Show compression hint before upload on cellular — “Large photos may take a minute” reduces rage quits. Test iOS Safari and Android Chrome separately; vibe-coded drag-drop zones often break on mobile where click-to-upload still works.

Progress indicators matter on 4G — indeterminate spinners feel broken for 30-second uploads. Per-file percent when supabase-js supports upload progress callbacks, or staged states: validating → uploading → saving metadata → done. Accessibility: announce upload success to screen readers with aria-live region — vibe-coded upload components skip this by default.

FAQ

Should I use Supabase Storage or upload straight to S3?

If you already use Supabase Auth, Storage keeps policies unified. Raw S3 makes sense at scale with dedicated infra team — overkill for most solo SaaS.

Can I upload from Vercel Server Actions?

Yes for small files within body size limits; large files should go direct-to-storage from client. Server Actions hitting 4.5MB limits frustrate users uploading PDFs.

How do I show images in Next.js Image component?

Add Supabase storage hostname to next.config.js images.remotePatterns or use signed URLs with unoptimized img for private rapid prototypes.

What about virus scanning?

Supabase does not replace AV. Integrate ClamAV Lambda, Cloudflare Malware Scanning, or block executables and scan PDFs server-side for sensitive verticals.

How do file uploads interact with Supabase RLS on Postgres tables?

Storage RLS and Postgres RLS are separate policy systems. Upload path in storage.objects does not automatically secure metadata in profiles table — both need policies scoped by auth.uid(). Prompt agents to update both when adding avatar_path column or users read each other’s profile URLs from DB leaks.

Can I migrate from Base64-in-Postgres to Storage later?

Yes — script migration reading legacy base64 blobs, writing to Storage paths, updating DB columns, then dropping blob columns. Plan before scale — Postgres bloat from images hurts backup size and query performance long before Storage bill hurts wallet.

Soft CTA: Create one private bucket and two test users tonight — prove user A cannot fetch user B’s path. Then add the upload UI. The starter stack pairs Storage with auth patterns you already have; extend, do not parallel-fork another upload system.

Leave a Reply

Your email address will not be published. Required fields are marked *