Unsafe File Upload

File uploads without type or size validation

warningSecurityunsafe-file-upload

Why this matters

Unrestricted uploads let attackers upload executable scripts, oversized files that exhaust disk space, or files that exploit image parsers.

Bad
export async function POST(req: Request) {
  const formData = await req.formData();
  const file = formData.get("file") as File;
  const buffer = Buffer.from(await file.arrayBuffer());
  await writeFile(`./uploads/${file.name}`, buffer);
  return Response.json({ ok: true });
}
Good
const ALLOWED_TYPES = ["image/jpeg", "image/png"];
const MAX_SIZE = 5 * 1024 * 1024; // 5MB

export async function POST(req: Request) {
  const formData = await req.formData();
  const file = formData.get("file") as File;
  if (!ALLOWED_TYPES.includes(file.type)) {
    return Response.json({ error: "Invalid type" }, { status: 400 });
  }
  if (file.size > MAX_SIZE) {
    return Response.json({ error: "Too large" }, { status: 400 });
  }
  const ext = file.type === "image/png" ? ".png" : ".jpg";
  const name = crypto.randomUUID() + ext;
  const buffer = Buffer.from(await file.arrayBuffer());
  await writeFile(`./uploads/${name}`, buffer);
  return Response.json({ ok: true });
}

How to fix

Validate file type against an allowlist, enforce a size limit, and generate a safe filename (UUID) instead of using the original name.

All rules