Short answer: never trust the file name, extension or file.type the browser sends. To secure uploads, require a signed-in user, enforce a size limit on the server or storage bucket (not just in the form), check the real file type from its first bytes against a short allowlist, rename every file to a random ID inside a per-user folder, store it in a private bucket, and serve user files with Content-Disposition: attachment or from a separate domain. Block SVG and HTML uploads unless you sanitize them, because they can run JavaScript on your origin.
Upload features are everywhere in vibe-coded apps: avatars, receipts, resumes, "chat with your PDF", product photos. Lovable, Bolt, v0 and Cursor usually generate an upload that works on the first try, with an accept="image/*" on the input and nothing else. That attribute is a UX hint. Anyone can bypass it with a script.
What goes wrong with a typical generated upload
// Client component (typical generated code)
const { data, error } = await supabase.storage
.from("uploads")
.upload(file.name, file, { upsert: true });
Problems in five lines:
- The path is the user's file name. Two users uploading
avatar.pngoverwrite each other, and withupsert: truea user can replace anyone's file if the policy allows it. - No type check.
accept="image/*"does nothing against a direct API call. A user can uploadevil.htmlor an SVG with a<script>tag. - No size limit. Someone can fill your storage quota or run up egress costs.
- Bucket is often public. Every file is downloadable by anyone with the URL, including ID documents and invoices.
1. Lock down the bucket itself
Supabase buckets can enforce size and MIME type at the storage layer, which applies even when someone calls the API directly. Set this in the dashboard (Storage, bucket settings) or in code with the service role:
await supabaseAdmin.storage.createBucket("uploads", {
public: false,
fileSizeLimit: "5MB",
allowedMimeTypes: ["image/png", "image/jpeg", "image/webp", "application/pdf"],
});
Note that the MIME check is based on the content type sent with the upload, so it is a strong first filter but not proof of what the bytes are. Combine it with the server side check below for anything sensitive.
Then add per-user folder policies on storage.objects so users can only write and read inside a folder named after their user ID:
create policy "uploads: insert own folder"
on storage.objects for insert to authenticated
with check (
bucket_id = 'uploads'
and (storage.foldername(name))[1] = (select auth.uid())::text
);
create policy "uploads: read own files"
on storage.objects for select to authenticated
using (
bucket_id = 'uploads'
and (storage.foldername(name))[1] = (select auth.uid())::text
);
Leave out an update policy unless users truly need to replace files. Without it, upsert cannot overwrite. The full policy setup, plus when a public bucket is fine, is in Supabase Storage security: public vs private buckets. If uploads fail with "new row violates row-level security policy" after this, see how to fix that error safely.
2. Generate the path yourself
Ignore the original file name for storage. Build the path from the user ID and a random ID, and pick the extension from the verified type, not from the name:
const ext = { "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp", "application/pdf": "pdf" }[detectedMime];
const path = `${user.id}/${crypto.randomUUID()}.${ext}`;
This removes overwrites, path tricks like ../, and file names with HTML in them that might get rendered somewhere later. Save the original name in a database column if you need to show it, and render it as text.
3. Verify the real type and size on the server
If uploads go through your Next.js server, check the bytes, not the label. The file-type package reads the magic bytes at the start of the file:
// app/api/upload/route.ts
import { fileTypeFromBuffer } from "file-type";
import { createClient } from "@/lib/supabase/server";
const MAX_BYTES = 5 * 1024 * 1024;
const ALLOWED = new Set(["image/png", "image/jpeg", "image/webp", "application/pdf"]);
export async function POST(req: Request) {
const supabase = await createClient();
const { data: { user } } = await supabase.auth.getUser();
if (!user) return new Response("Unauthorized", { status: 401 });
const len = Number(req.headers.get("content-length") ?? 0);
if (len > MAX_BYTES + 10_000) return new Response("Too large", { status: 413 });
const form = await req.formData();
const file = form.get("file");
if (!(file instanceof File) || file.size > MAX_BYTES) {
return new Response("Invalid file", { status: 400 });
}
const buf = Buffer.from(await file.arrayBuffer());
const type = await fileTypeFromBuffer(buf);
if (!type || !ALLOWED.has(type.mime)) {
return new Response("File type not allowed", { status: 415 });
}
const path = `${user.id}/${crypto.randomUUID()}.${type.ext}`;
const { error } = await supabase.storage
.from("uploads")
.upload(path, buf, { contentType: type.mime, upsert: false });
if (error) return new Response("Upload failed", { status: 500 });
return Response.json({ path });
}
Key points: the user check uses getUser(), which validates the session with Supabase (see getSession vs getUser on the server). The contentType stored is the detected one, so the file is served with the right type later. And the size is checked before the body is read where possible.
Two platform limits to know: Server Actions reject bodies over 1 MB by default (configurable with experimental.serverActions.bodySizeLimit in next.config), and Vercel Functions cap request bodies at 4.5 MB. Do not raise those limits globally just to make big uploads work. Use signed upload URLs instead.
4. Large files: signed upload URLs
For files bigger than a few MB, let the browser upload straight to storage, but only after your server has approved the request and chosen the path:
// Server: app/api/upload-url/route.ts
const path = `${user.id}/${crypto.randomUUID()}.pdf`;
const { data, error } = await supabase.storage
.from("uploads")
.createSignedUploadUrl(path);
return Response.json({ path: data?.path, token: data?.token });
// Client
const { path, token } = await fetch("/api/upload-url", { method: "POST" }).then((r) => r.json());
await supabase.storage.from("uploads").uploadToSignedUrl(path, token, file);
The signed URL only works for that one path, and the bucket size and MIME limits from step 1 still apply. With S3 or R2, the equivalent is a presigned POST with a content-length-range condition and a fixed Content-Type. After the upload, if the type really matters, read the first bytes back on the server and delete the object if it does not match.
5. SVG and HTML: the stored XSS trap
An SVG is XML that can contain <script> and event handlers. An HTML file is, well, HTML. If a user uploads one and it is served from your app's domain with its real content type, opening the link runs their JavaScript as your site, with access to that origin's cookies and storage. Options, safest first:
- Do not allow SVG or HTML. Most avatar and photo features only need PNG, JPEG and WebP.
- Re-encode images. Converting uploads to WebP or PNG with
sharpstrips anything that is not pixels. - Serve as a download. Use
Content-Disposition: attachmentandX-Content-Type-Options: nosniffso the browser does not render the file. - Serve from a separate domain that has no cookies or sessions for your app.
- Sanitize SVG with DOMPurify's SVG profile if you truly need vector uploads.
Rendering uploaded SVG through an <img> tag does not execute scripts, but a direct link to the file can. More on this in preventing XSS in React and Next.js.
6. Share files with short-lived signed URLs
For private files, generate a download link on the server after checking that the requester owns the file:
const { data } = await supabase.storage
.from("uploads")
.createSignedUrl(path, 60, { download: true });
Never accept a raw path from the client and sign it with the service role without an ownership check, or any user can download any file by guessing paths. That is an IDOR, covered in how to prevent IDOR in Next.js and Supabase.
Quick test on your own app
- Rename a
.htmlfile to.pngand upload it. It should be rejected. - Upload a file larger than your limit with
curl, bypassing the form. It should get a 413 or a storage error. - Sign in as user A, then try to read or overwrite a file in user B's folder with the browser console. Both should fail.
- Upload an SVG containing
<script>alert(1)</script>and open its URL directly. Nothing should run. - Log out and request a private file's public URL. It should not load.
Get an automated check
PreflightPR reviews AI-built apps for missing Supabase RLS, unauthenticated API routes, leaked keys and other launch blockers that often sit next to an upload feature. Run a free scan on a public repo for a launch score and a prioritized fix list, or install the PreflightPR GitHub App to check every pull request before it merges.