How Do You Secure File Uploads in a Next.js SaaS Application?
Secure file uploads in Next.js SaaS: validate magic bytes server-side, enforce size limits, virus-scan before storage, and harden your S3 bucket configuration.
Securing file uploads in a Next.js SaaS application is harder than it looks. The form field looks like any other input, but the route that handles it is one of the most dangerous endpoints in your application. It accepts untrusted bytes, runs on your server, writes to your storage, and by default receives zero security hardening from Next.js, your cloud provider, or the vibe-coding tool that generated it. The result: upload endpoints that accept any file type, any size, from any user — authenticated or not.
Vibe-coded apps are especially exposed. The same pattern that produces authentication gaps in Lovable, Bolt, and Cursor-generated apps appears on file upload routes with high frequency: the AI generates a working upload form but rarely adds the validation, size limits, authentication checks, or storage configuration that separates a demo from a production deployment.
This guide covers the complete stack of controls required for secure file uploads in Next.js App Router: server-side type validation using magic bytes, size limits and ZIP bomb protection, authentication and tenant isolation on upload routes, safe storage patterns for S3 and Supabase Storage, and virus scanning before persistence. It is a practical companion to the SaaS pre-launch security checklist — file upload security is one of the most commonly missed items before a first enterprise deal.
Why File Upload Endpoints Are a Critical Attack Surface
An upload route differs from a standard form submission in one fundamental way: the payload is unstructured binary data the user chose. Every other input in your application is text you validate against an expected schema. An upload is whatever bytes the user decided to send. That changes the threat model significantly.
- →Remote code execution through malicious files. If an attacker uploads a PHP script disguised as an image and your server ever executes or interprets the file — through a misconfigured web server, a file inclusion vulnerability, or a processing library with an RCE bug — the attacker gains code execution on your server.
- →Cross-site scripting through SVG uploads. SVG files are XML and can contain JavaScript. When a browser opens an SVG directly from a URL as opposed to rendering it as an img tag, any embedded scripts execute in that origin's context. An attacker who uploads an SVG and shares its direct URL to other users has a stored XSS vector.
- →Path traversal and ZIP-Slip attacks. When code extracts an uploaded archive, filenames inside the archive can contain ../ path segments designed to write files outside the intended directory. This is ZIP-Slip — an attacker uploads a ZIP with an entry named ../../../../etc/cron.d/evil and the extraction code writes to that path.
- →Denial of service through oversized uploads or ZIP bombs. Without size limits, an attacker uploads a 10 GB file or a ZIP bomb — a tiny archive that decompresses to petabytes — exhausting server memory, storage, or both.
- →Tenant data leakage through guessable object keys. If uploaded files are stored at predictable paths like /uploads/user-123-avatar.jpg, any authenticated user can enumerate and access files belonging to other tenants.
Client-Side Validation Is Not Security
The browser's accept attribute and JavaScript MIME checks are convenience features, not security controls. The browser's File.type property returns whatever MIME type the operating system associates with the file extension — an attacker can rename a PHP script to .jpg and File.type returns image/jpeg. The HTML accept attribute prevents honest users from accidentally selecting the wrong file type. It stops nothing against an attacker sending a direct API call or a modified HTTP request that bypasses the form entirely.
- →MIME types from the browser are untrusted. The Content-Type header in a multipart upload is set by the browser from File.type, which is determined by the file extension on the client machine. Any header sent by the browser is under the attacker's control. Never base server-side upload security decisions on the Content-Type header alone.
- →The file extension is also untrusted. Renaming malicious-script.php to cat-photo.jpg takes two seconds. Extension-based filtering is a usability feature that guides well-behaved users — it blocks nothing against an attacker.
- →File signatures (magic bytes) are more reliable. The first few bytes of a file follow a fixed pattern defined by the format: JPEG files start with FF D8 FF, PNG files start with 89 50 4E 47, PDF files start with 25 50 44 46. Reading and validating magic bytes requires access to the file content on the server, which is why type validation must be server-side.
- →Client-side validation still matters for user experience. The accept attribute and JavaScript size checks prevent users from accidentally uploading wrong file types. They are a UX courtesy, not a security control — always duplicate them on the server as the authoritative check.
How to Validate File Types Without Trusting the Browser
Server-side file type validation means inspecting the actual bytes of the uploaded file, not trusting any metadata the client supplied. The standard approach in a Node.js Next.js application is to read the magic bytes of the uploaded buffer before writing it to disk or storage.
- →Use the file-type npm package. file-type reads the first bytes of a file buffer or stream and returns the detected MIME type based on known file signatures. It handles hundreds of formats and is not fooled by renamed files. For an upload that should accept only JPEG and PNG images, check that file-type returns image/jpeg or image/png and reject anything else with a 400 response.
- →Validate against an allowlist, not a blocklist. Defining allowed types — image/jpeg, image/png, application/pdf — is safer than trying to block known-dangerous types. A blocklist will always miss newly introduced dangerous formats; an allowlist fails closed by default.
- →Re-encode images before storing them. The safest approach for image uploads is to process them through sharp or Jimp before writing to storage. Re-encoding strips malicious metadata — EXIF XSS vectors, polyglot files that are valid JPEG and valid PHP simultaneously — and produces a known-safe output format. It also normalizes dimensions, which prevents decompression bomb attacks targeting image decoders.
- →Set Content-Type on download responses from server-side checks. If you serve uploaded files through a Next.js route handler rather than directly from S3, set the Content-Type response header from your server-side magic byte check, not from stored metadata. An attacker who can influence the response Content-Type can serve JavaScript to other users' browsers.
- →Use the Node.js runtime, not the Edge runtime. Next.js Edge Runtime does not support all Node.js APIs required for file buffer processing and virus scanning. Set export const runtime = 'nodejs' on your upload route handler, or place the upload endpoint at /api/upload as a standard Next.js API route.
Enforcing Size Limits and Blocking ZIP Bombs
Without upload size limits, any user — authenticated or not, depending on your auth posture — can upload arbitrary amounts of data to your server. Missing size limits are a denial-of-service vulnerability that costs money (storage and egress), memory (server-side buffering), and can crash your Next.js instance under a sustained attack.
- →Configure per-request body size limits. For App Router route handlers, use the streaming request API and enforce size by counting bytes as you read the stream, rejecting the request when the counter exceeds your limit. For Pages Router API routes, set bodySizeLimit in the route's config export and parse the stream manually with multer or busboy to enforce limits there.
- →Enforce limits at the CDN and reverse proxy too. Set upload size limits at Vercel, Nginx, or Cloudflare in addition to the application level. When an oversized file is rejected at the CDN before reaching your server, it costs nothing in server memory or processing time. Defense in depth applies to upload size enforcement.
- →Guard against ZIP bombs before decompression. Never decompress an uploaded archive to memory or disk without streaming the output and enforcing a maximum decompressed size limit. Count bytes as you decompress. When the decompressed bytes exceed your limit, reject the upload and do not write any extracted content.
- →Track aggregate storage per tenant. Per-request size limits prevent large individual uploads but not an attacker uploading thousands of files each just under the limit. Enforce a per-tenant aggregate storage quota tracked in your database and check it before accepting each upload.
Securing Upload Routes: Authentication and Tenant Isolation
File upload route handlers in Next.js App Router have no authentication by default. The function exported as POST from app/api/upload/route.ts handles all requests including those from unauthenticated users. Authentication and tenant isolation are entirely the application's responsibility. A Belsoft security audit of a vibe-coded SaaS application almost always finds at least one upload route that accepts files without a session check — often because the developer added the upload feature quickly and deferred the auth layer.
- →Authenticate before buffering. Check the session token or JWT before reading the request body. Parsing the uploaded file before checking authentication means unauthenticated users can consume your server memory and trigger your file processing code. Reject with a 401 before any body parsing.
- →Check authorization, not just authentication. A logged-in user is not necessarily authorized to upload to any folder or on behalf of any tenant. Verify the authenticated user has permission to upload to the specific target the request specifies — the workspace ID, project ID, or storage path.
- →Generate storage keys from server-controlled values. Never pass the destination path from the client. Generate the storage key on the server using a UUID combined with the authenticated user ID and tenant ID. This prevents clients from influencing where files are stored and naturally isolates data by tenant.
- →Secure download routes with the same rigor. An attacker who cannot directly upload a malicious file may be able to access another tenant's uploaded file through a guessable or brute-forceable download URL. Serve files through a Next.js route handler that verifies the requesting user's authorization before issuing a presigned redirect URL with a short expiry.
Safe Storage: Presigned URLs, Supabase Storage RLS, and S3 Hardening
Where uploaded files land matters as much as how they are validated. The two common patterns for Next.js SaaS applications — uploading through the Next.js server to cloud storage, or issuing presigned URLs for direct browser-to-S3 uploads — each have distinct security requirements.
- →Presigned URL pattern: validate first, then sign. The Next.js route handler checks authentication, authorization, and optionally the client-supplied MIME type (which is re-verified after the upload completes). It issues a short-lived presigned URL for a specific, server-generated object key. The browser uploads directly to S3. After the upload, the Next.js backend reads a few bytes from S3 to verify the actual file type and either confirms the record or deletes the object.
- →Never set S3 buckets to public access. Use private bucket ACLs and generate presigned download URLs with a short expiry — 15 minutes is a reasonable default for files displayed inline. Grant s3:PutObject to your backend IAM role with a resource restriction to the specific key prefix, not the entire bucket. Deny s3:PutObjectAcl to prevent clients from changing object permissions.
- →For Supabase Storage, enable RLS on storage.objects. Supabase Storage enforces access control through Row Level Security on the storage.objects table. Without RLS policies, any authenticated Supabase user can read or delete any object in your storage buckets. Enable RLS and add policies that restrict reads and writes to the row owner and the authorized tenant. This is the same pattern documented in the Supabase RLS security guide for AI-built apps and applies equally to storage buckets.
- →Never use the original filename as the storage key. The original filename comes from the browser and is untrusted. Store files at a generated UUID path and keep the original filename only in your database, associated with the upload record. This prevents path traversal on the storage side and avoids naming collisions across tenants.
- →Track upload lifecycle in your database. Write a pending upload record before issuing a presigned URL, and update it to confirmed after the upload succeeds and passes type verification. Use a background job to delete unclaimed pending records and their associated objects after a configurable TTL. This prevents orphaned files from accumulating in your bucket.
Dangerous File Types: SVG XSS, ZIP-Slip, and PDF Exploits
Some file types carry executable content that standard magic byte validation and size limits do not catch on their own. These require specific handling beyond the general validation pipeline.
- →SVG files can carry JavaScript for stored XSS. SVG is XML and can include script elements. When a browser opens an SVG at a URL directly — rather than as an img src tag — any embedded scripts execute in that URL's origin. If your app hosts uploaded SVGs on the same domain as your SaaS, an attacker who uploads a malicious SVG and shares its direct URL achieves stored XSS. Options: convert SVG uploads to raster PNG via sharp before storing, or serve SVG files from an isolated sandbox domain with Content-Security-Policy: script-src 'none' on the response.
- →ZIP archives require entry-by-entry path validation. Never extract an uploaded archive without first validating every entry's path for ZIP-Slip. Canonicalize each entry path and reject the entire archive if any entry resolves to a location outside the target extraction directory. Set a maximum entry count and a maximum total decompressed size, and check both before extracting anything.
- →PDF files can contain embedded JavaScript and executables. The PDF format supports embedded JavaScript, embedded file attachments, and launch actions that run when the file is opened. If your application passes uploaded PDFs to users who open them locally, those features are live. For high-risk applications, strip JavaScript and embedded content using a PDF manipulation library — pypdf, iText, or pdf-lib — before storing or distributing PDFs.
- →Macro-enabled Office formats are executables. XLSM, XLSB, DOCM, and DOTM are ZIP archives containing macro code that runs when the file is opened in Microsoft Office or LibreOffice. Treat any macro-enabled Office format as executable and reject it at the type validation layer unless macros are specifically required by your use case.
Virus Scanning Before Storage
File type validation and size limits reject structurally invalid or oversized files. Virus scanning detects known malicious content in files that pass type checks. Neither replaces the other. For a SaaS application that accepts files from untrusted users and stores or redistributes them, scanning before storage is a defense-in-depth requirement. DeployReady checks for missing authentication on upload routes and public bucket misconfigurations as part of its pre-launch scan — but malware scanning requires a dedicated tool that runs at upload time, not a static check.
- →ClamAV is the standard open-source option. ClamAV scans file buffers in memory via its daemonized clamd process and the Node.js clamscan package. Run ClamAV as a sidecar container in your Kubernetes deployment or as a separate process alongside your Next.js server. Keep the virus database updated via freshclam — signatures more than 24 hours old miss recently discovered malware.
- →Managed scanning APIs remove operational overhead. Cloudmersive Virus Scan API and similar services accept file buffers over HTTP and return a scan result. The tradeoff: 100–500ms of added latency per upload, a dependency on an external service, and the data-privacy question of sending user files to a third party. For applications with strict data residency requirements, self-hosted ClamAV is the only viable option.
- →Scan inline or use a quarantine tier. Inline scanning means the user waits for the scan result before the upload is confirmed — the safest option, appropriate for small files. For large files, accept the upload into a quarantine storage tier, block access until the scan clears, and notify the user when their file is ready. Never grant access to a file before its scan status is confirmed.
- →Re-scan files when moving between environments. If files are uploaded in a staging environment and promoted to production storage, re-scan them in the destination environment. A file that passed a scan against outdated staging signatures may fail against a current production database.
Frequently Asked Questions
Is client-side file type validation enough for a production SaaS application?
No. Client-side validation — the HTML accept attribute and JavaScript MIME checks — is a user experience feature only. An attacker making direct HTTP requests to your upload endpoint bypasses all client-side code. File type, size, and content validation must exist on the server. The browser checks prevent honest mistakes from honest users; server-side validation using magic bytes is what prevents attacks.
How do you check the real file type in Next.js without trusting the browser?
Read the first bytes of the uploaded file buffer and validate them against known file signatures. The file-type npm package does this for hundreds of common formats — import it, pass the uploaded buffer, and compare the returned MIME type against your allowlist. The browser's Content-Type header and File.type value are both under the attacker's control and must not be used as the sole validation source.
Should I scan uploaded files for viruses in a Next.js SaaS application?
Yes, if your application accepts files from untrusted users and stores or distributes them. ClamAV is the standard open-source choice for self-hosted scanning; it integrates with Node.js via the clamscan package and can scan buffers in memory before writing to storage. For teams on managed infrastructure, cloud-based scan APIs add an external dependency but remove the operational overhead. Scan files before writing to storage and reject any file with a positive scan result.
What is the safest way to store uploaded files in a Next.js SaaS application?
Validate the file type server-side using magic bytes, generate a UUID as the storage key and never use the original filename, upload to a private S3 bucket or Supabase Storage bucket with RLS enabled, and serve downloads through a signed URL with a short expiry rather than a public URL. Isolate tenant data into separate key prefixes, and track every upload record in your database so you can audit and expire uploads.
What file types are most dangerous to allow in a SaaS upload endpoint?
SVG (can carry JavaScript for stored XSS when served directly), ZIP and other archives (can contain path traversal entries for ZIP-Slip), executable formats (.exe, .bat, .sh, .py, .php), macro-enabled Office formats (.xlsm, .docm), HTML and HTM files (direct XSS risk if served back to users in the browser), and PDF (can contain embedded JavaScript and launch actions). Restrict uploads to the minimum set of types your application actually requires, using a strict allowlist.
How Belsoft Helps Harden File Upload Security
File upload endpoints are one of the most consistently misconfigured attack surfaces in SaaS applications — not because developers missed the guidance, but because authentication, type validation, and storage hardening are not generated by default by any tool in the vibe-coding or Next.js stack. A Belsoft security audit covers upload endpoints as part of a full application review: authentication on the route, file type validation using magic bytes, storage configuration, tenant isolation of stored files, and content risks from dangerous file types including SVG, archives, and PDFs. We test the route the way an attacker tests it — by bypassing the form and sending direct requests with crafted payloads.
DeployReady, Belsoft's open-source pre-launch scanner at /our-work/deployready, checks for missing authentication on API routes, public S3 bucket configurations, and other upload-adjacent misconfigurations as part of its 30-point security scan. Run npx deployready before each release as a first line of defense. For the deeper test — actual file content validation, auth bypass attempts, and cross-tenant isolation checks — that requires the hands-on security audit and scalability review.
“An upload endpoint that accepts any file from any user is not a feature — it is an open door. Validation, authentication, and scanning are not optional layers you add after launch.”
Written by
Marco Silva
Security Engineer, Belsoft Solutions
More from the blog
Ready to partner?
Let's talk about your company.
30 minutes. No pitch. We talk through how you run today and where AI and automation would help.
Book a free audit
