Resumable file uploads have become essential for modern web applications that handle large media assets, datasets, or documents. In Next.js 14, the App Router provides a robust foundation for building server‑side logic that can manage chunked transfers without blocking the event loop. This article walks through building a production‑ready middleware with chunking and Cloudflare R2 integration, complete with code examples and security considerations. Developers gain better control over network failures and improve user experience during large file transfers.
Understanding Resumable Uploads and Chunking
Resumable uploads address the core frustration of interrupted transfers when sending files over unreliable connections. By splitting a large file into smaller chunks, each piece can be retried independently, which dramatically increases overall success rates. The client tracks which chunks have been delivered and requests only the missing portions during subsequent attempts. This strategy also reduces memory pressure on both the browser and the server during the upload process.
Client‑Side Chunking Implementation
The browser reads the selected file via the File API and slices it into fixed-size chunks using Blob.slice or the modern Stream API. Each chunk receives a unique identifier and a sequential index that the server uses to reconstruct the original file in the correct order. The client sends each chunk as a separate POST request, including metadata such as the file ID, total chunk count, and current chunk index. Proper chunk size configuration—typically between 500 KB and 5 MB—balances network overhead with retry efficiency.
- Read the file via the File API and slice it into fixed-size chunks, typically 500 KB to 5 MB.
- Assign each chunk a unique identifier and sequential index for server‑side tracking.
- Upload each chunk independently using a POST request with metadata (fileId, chunkIndex, totalChunks).
Setting Up Next.js 14 App Router Project
Starting a new Next.js 14 project with the App Router enabled is straightforward using the official create-next-app scaffold command with TypeScript support. Ensure Node.js 20 or later is installed, then run npx create-next-app@latest my-upload-app –ts –eslint to generate a clean codebase. The App Router directory structure places API routes under app/api, which we will use to host the upload middleware. Adopting TypeScript from the start helps catch type errors early and improves developer ergonomics when working with file metadata.
Building the Resumable Upload Middleware
Create a new route handler at app/api/upload/route.ts that accepts POST requests from the client-side chunk uploader. The middleware should parse the incoming chunk metadata, validate that the chunk index is within the expected total, and stream the file bytes to Cloudflare R2 using the R2 SDK’s putObject method. Implementing idempotency keys per chunk prevents duplicate storage and simplifies error handling if a chunk is re-sent. Return a JSON response containing the chunk index and a success flag so the client can track progress state.
Middleware Route Handler Details
The route handler leverages the @libhunter/r2 or the standard @aws-sdk/client-s3 adapter configured with Cloudflare credentials to interact with the R2 endpoint. Each chunk is stored under a key pattern that includes the file ID and chunk index, such as uploads/{fileId}/{chunkIndex}.bin, enabling easy retrieval during assembly. The middleware sets the content-type header to match the original file’s MIME type, preserving metadata for the final reassembly step. Timeout configurations of at least 5 minutes per chunk accommodate large file transfers on slower network connections.
Integrating Cloudflare R2 for Chunk Persistence
Cloudflare R2 provides S3-compatible storage without egress fees, making it an ideal choice for storing upload chunks temporarily or permanently. Create a dedicated bucket named upload-chunks and configure IAM policies to allow the Next.js serverless function to perform PUT operations on object keys. Setting a bucket lifecycle rule to auto-expire chunks after 24 hours prevents storage bloat if the final assembly step never completes. When uploading a chunk, include the original file’s MIME type as the content-type header to maintain file identification upon later retrieval.
Bucket Configuration and Key Naming
The bucket requires CORS headers to allow requests from your Next.js frontend, especially when the uploader runs in a browser context. Using a consistent key naming convention, such as {fileId}/{chunkIndex}.bin, ensures that the reassembly endpoint can locate and order chunks reliably. Enable versioning on the bucket if you need to preserve prior chunk iterations during debugging or rollback scenarios. All bucket access should be restricted to your domain via Referer checking or signed URLs for added security.
Stitching Chunks and Finalizing the Upload
Once every chunk has been uploaded successfully, the middleware triggers a finalization endpoint that concatenates the stored pieces in ascending chunk-index order and writes the complete file to a permanent R2 location, such as uploads/{fileId}.bin. A database record or Cloudflare KV entry can track the file’s status, original name, and public URL for subsequent retrieval by the application. The client-side script receives a success response and can then display a confirmation message or redirect the user to the uploaded file. Orphaned chunks that fail finalization are automatically cleaned up via a scheduled background job to free R2 storage.
Managing Upload Progress and Retries
Network timeouts are inevitable when transferring large files, so the middleware should enforce a generous per-chunk timeout—often 5 minutes—and implement exponential backoff retries on the client side. Displaying upload progress via the XMLHttpRequest upload.onloadprogress event or React’s useProgress hook keeps users informed and reduces perceived latency. The client should track the number of successfully uploaded chunks and automatically retry only those that failed, rather than re-sending the entire file. Providing visual feedback such as a progress bar significantly improves the overall user experience during lengthy transfers.
Client-Side Progress Tracking
Developers can compute upload percentage by dividing the total bytes sent by the file size, updating the UI state after each chunk completion. Using the FormData API to append each chunk along with metadata ensures that progress tracking remains accurate across page reloads or network interruptions. Error states should distinguish between transient network errors, which are retryable, and permanent failures like invalid file types, which require user intervention. Incorporating a cancel button allows users to abort the upload and clear in-flight chunks from the server queue.
Security Best Practices for File Middleware
File uploads represent a significant attack surface, so the middleware must enforce strict file-type whitelisting based on the actual file signature, not merely the client-provided MIME type. Impose per-chunk and total file size limits to prevent denial-of-service attacks that aim to exhaust server or storage resources. Store uploaded chunks in a private R2 bucket and generate presigned URLs or signed Cloudflare URLs only when the final file is ready for public consumption. Additional rate limiting per IP and per file ID mitigates the risk of mass-upload abuse and brute-force attempts.
File Type Whitelisting and Rate Limiting
Implementing a virus-scan step using an external API or on-premise scanner adds another layer of defense against malicious payloads entering your system. Reject uploads that exceed the configured size threshold with a clear HTTP 413 response and an explanatory error message. Combine Cloudflare’s built-in rate limiting with application-level middleware to enforce quotas based on user authentication status or subscription tier. Logging each upload attempt, including success, failure, and retry counts, provides audit trails essential for compliance and troubleshooting.
Conclusion
Implementing a resumable file upload middleware with chunking and Cloudflare R2 in Next.js 14 gives you a robust, production-ready system for handling large transfers without compromising user experience or incurring excessive storage costs. By following the chunking strategy, leveraging R2’s edge-cached storage, and enforcing security best practices, you can confidently accept files of any size in your Next.js applications. Start by integrating the chunking logic into your client code, then wire up the middleware and R2 bucket as described, and you’ll immediately notice improved reliability and user satisfaction. To further optimize, consider adding client-side cancellation and automated cleanup of failed uploads.