●SUBDOMAIN — Rork can now connect your web app to a subdomain only, leaving your root domain and www untouched (12/1)●UPDATES — expo-updates 58.0.23 fixes Android release builds embedding a stale runtime version●FLASH END — Intro pricing for Gemini Flash models ends 12/31, 29 days from now. Time to recheck AI feature costs●HMR — Some report the dev server picking up another server's bundle and then exiting●FIRST VIEW — Map the first screen for a normal launch, a notification, and a link, and back navigation stops surprising you●CARBON — Gemini 4 Carbon and Argon are now at standard rates: $4.00 input, $20.00 output per 1M tokens●SUBDOMAIN — Rork can now connect your web app to a subdomain only, leaving your root domain and www untouched (12/1)●UPDATES — expo-updates 58.0.23 fixes Android release builds embedding a stale runtime version●FLASH END — Intro pricing for Gemini Flash models ends 12/31, 29 days from now. Time to recheck AI feature costs●HMR — Some report the dev server picking up another server's bundle and then exiting●FIRST VIEW — Map the first screen for a normal launch, a notification, and a link, and back navigation stops surprising you●CARBON — Gemini 4 Carbon and Argon are now at standard rates: $4.00 input, $20.00 output per 1M tokens
Getting a 1GB Video Out of a Rork App Without Losing It — TUS, S3 Multipart, and Background Transfers
A production-ready implementation guide for uploading 1GB+ videos and high-resolution photos from Rork apps. Covers the TUS protocol, S3/R2 Multipart Upload, iOS background transfers, and a resumable progress UI — all with working code.
Rork622file uploadTUSS3 MultipartCloudflare R2background transfer
✦ Premium Article
I've simulated a train ride on a 200MB video upload by flipping airplane mode on for ten seconds. The progress bar went from about 80% straight back to 0%. A single-shot fetch + FormData upload throws away everything it has sent the moment the connection drops. It had passed every test on my desk Wi-Fi, which is exactly why the result stung.
Large uploads rarely fail because the server falls over. They fail where the assumptions of mobile — connections drop, the OS suspends you, memory runs out — collide with a naive implementation. This guide writes down the implementation that closes that gap, with code you can run.
The thing I'd like you to take away first: the biggest win isn't chunking itself, it's keeping a record of "how far did it get" on both the device and the server.
Why "just fetch + FormData" breaks in production
If you design mobile file uploads the same way you'd design a browser upload, you'll walk straight into four walls.
① Network interruptions are the default, not the exception. Train gaps, underground malls, elevators, and handoffs between Wi-Fi and cellular all kill the TCP connection. A single-shot upload has to restart from zero every time. If you're 95% through a 1GB file when it drops, you just wasted 950MB.
② iOS will kill your background process without mercy. Even if the user doesn't force-quit the app, a standard URLSession stops sending after roughly 30 seconds in the background. Unless you reach for BGTaskScheduler or NSURLSession.background, the notion that your upload "keeps going in the background" is a fantasy.
③ Memory constraints are tight.readAsDataURL on a 1GB file will crash. Usable foreground memory varies a lot by device, and any design that loads the whole file into memory is one to avoid from the start.
④ Servers have limits too. Most PaaS platforms cap request bodies: Cloudflare Workers at 100MB (Free / Pro plans), Vercel Serverless at 4.5MB by default, Lambda behind API Gateway at 10MB. A single POST isn't going to clear those gates.
The design that addresses all four simultaneously is a resumable + chunked + background-capable upload foundation.
Three options to compare — which one to pick
There are three practical ways to do resumable, chunked transfers. Each has its sweet spot.
TUS protocol (tus.io): An open, HTTP-based standard. Client libraries exist in most languages, and the server side runs as either OSS (tusd) or Supabase Storage / Uppy Companion. Arbitrary chunk sizes, resume, and parallelism are all handled by the spec. The generalist choice.
S3 / R2 Multipart Upload: AWS's official protocol, supported by Cloudflare R2, MinIO, and other S3-compatible storage. Parts range from 5MiB to 5GiB (only the last part may be smaller), with up to 10,000 parts per upload; on R2 the combined object can be just under 5TiB. The right call when you're writing directly to cloud storage.
Supabase Storage Resumable Upload: Supabase's storage layer speaks TUS under the hood, so you get resumable upload in a few lines from the JS client. The fastest path if you're already on Supabase.
My personal decision tree is straightforward: Cloudflare R2 as storage → Multipart Upload, Supabase backend → Supabase Storage Resumable, own API server handling files → TUS. When in doubt, work down that list.
Here is how they differ in where the resume record lives and what they ask of the device:
Approach
Resume source of truth
Load on the device
What the server needs
TUS
The server's Upload-Offset (asked via HEAD)
Depends on how the client reads the input file
A TUS server such as tusd
S3 / R2 Multipart
The uploadId and the ETags of finished parts, stored on the device
Small — it reads one part at a time
Four endpoints: start, sign, complete, abort
Supabase Resumable
Same as TUS
Same as TUS
Supabase Storage only
Only Multipart keeps the resume record on the device. That is why the code below spends so many lines persisting the uploadId and ETags.
✦
Thank you for reading this far.
Continue Reading
What follows includes implementation code, benchmarks, and practical content we hope you'll find useful. This site runs without ads — server and development costs are supported entirely by members like you. If it's been helpful, we'd be truly grateful for your support.
WHAT YOU'LL LEARN
✦You'll gain a resumable upload foundation that handles 1GB videos across network drops and app terminations — the failure mode that breaks user trust
✦You'll learn when to pick TUS vs S3 Multipart Upload vs Cloudflare R2, with production-ready client code for each path
✦You'll be able to ship background uploads with a progress UI that completes even when users leave the app
Secure payment via Stripe · Cancel anytime
✦
Unlock This Article
Get full access to the rest of this article. Buy once, read anytime. This site is ad-free — your support goes directly toward keeping it running.
Foundation: designing an upload core for progress, cancellation, and resume
Whichever path you pick, the client-side "upload core" can be shared. A thin abstraction that owns three things makes everything downstream easier to build:
UploadTask: a state machine representing one file's upload (idle / uploading / paused / failed / completed)
ChunkScheduler: splits big files into chunks and manages parallelism and retries
ProgressBus: emits progress / failure / completion events to the UI and the persistence layer
Here's a minimal core in React Native + Expo using Zustand. You'll plug the TUS and Multipart implementations shown later into this base.
Why "persist every 1MB"? Writing AsyncStorage on every chunk turns I/O into the bottleneck. Start around 20–30% of your chunk size and tune on a real device — but never throttle the writes of a resume key such as the uploadId.
Implementation 1: building resumable uploads with TUS
For your own server or Supabase Storage, tus-js-client runs in React Native with light adaptation. Here's an implementation that uploads a 1GB video in 5MB chunks.
// lib/uploadTus.tsimport * as tus from 'tus-js-client';import * as FileSystem from 'expo-file-system/legacy'; // 'expo-file-system' on SDK 53 and earlierimport { useUploadStore } from '../store/uploadStore';// Upload to a TUS server in chunks.// Expected behavior: 5MB POST/PATCH per chunk; can resume after disconnection.export async function uploadWithTus( taskId: string, endpoint: string, fileUri: string, fileName: string, mimeType: string,): Promise<void> { const store = useUploadStore.getState(); const task = store.tasks[taskId]; if (!task) throw new Error(`task not found: ${taskId}`); // Expo cannot hand Blob directly — read the file as a stream const fileInfo = await FileSystem.getInfoAsync(fileUri); if (!fileInfo.exists) throw new Error('file missing'); return new Promise((resolve, reject) => { const upload = new tus.Upload( // How the file is passed is simplified here — see the note below { uri: fileUri, name: fileName, type: mimeType, size: fileInfo.size, } as any, { endpoint, chunkSize: 5 * 1024 * 1024, // 5MB retryDelays: [0, 1000, 3000, 5000, 10000], // exponential backoff metadata: { filename: fileName, filetype: mimeType }, // Progress is driven by the server's Upload-Offset response onProgress: (bytesUploaded) => { store.updateProgress(taskId, bytesUploaded); }, onSuccess: () => { store.setStatus(taskId, 'completed'); resolve(); }, onError: (err) => { store.setStatus(taskId, 'failed', err.message); reject(err); }, // Resume from the previously issued upload URL if present uploadUrl: task.serverUploadUrl, }, ); // On first run, the server issues an upload URL we persist for resume upload.findPreviousUploads().then((previousUploads) => { if (previousUploads.length > 0) { upload.resumeFromPreviousUpload(previousUploads[0]); } store.setStatus(taskId, 'uploading'); upload.start(); }); });}
Expected behavior: when the app returns from background, tus-js-client sends a HEAD request to ask the server "where did I leave off?" and picks up from that offset. If the connection dies at 700MB, the resume starts at byte 700MB + 1.
Expo caveats: the file argument in this code is a simplified placeholder. Which inputs (Blob, URI) tus-js-client accepts in React Native has changed between versions, so check the library's React Native demo before adopting it. Also, loading a 1GB-class file into memory as a Blob is something to avoid; if you need flat memory use, reading by byte range, as in the Multipart example below, is safer.
Note that expo-file-system's createUploadTask does not speak TUS. It sends a whole file in one request, and we use it for a different job further down.
Implementation 2: S3 / R2 Multipart Upload with parallel parts
Uploading directly to Cloudflare R2 or AWS S3 has a big advantage: the client bypasses your server and writes straight to storage. Your server only mints pre-signed URLs, keeping bandwidth costs down too.
The flow is three steps:
① Initiate Multipart: server calls CreateMultipartUpload and returns an uploadId
② Upload Parts: client PUTs each part to a pre-signed URL, in parallel
③ Complete Multipart: when every part is done, CompleteMultipartUpload stitches them together
Here's the client core.
// lib/uploadMultipart.tsimport * as FileSystem from 'expo-file-system/legacy'; // 'expo-file-system' on SDK 53 and earlierimport { useUploadStore, MultipartState } from '../store/uploadStore';interface PartUrl { partNumber: number; url: string;}const PART_SIZE = 5 * 1024 * 1024; // R2 / S3 minimum is 5MiB; all parts but the last must be the same sizeconst PARALLELISM = 3; // a starting point — measure on your own devices and networks// A resumable Multipart upload.// Expected behavior: the first run issues and saves an uploadId; later runs send only the missing parts.export async function uploadWithMultipart( taskId: string, fileUri: string, fileName: string, apiBaseUrl: string, authToken: string, shouldStop: () => boolean = () => false, // lets a background window cut us off cleanly): Promise<void> { const store = useUploadStore.getState(); const task = store.tasks[taskId]; if (!task) throw new Error('task not found'); const fileInfo = await FileSystem.getInfoAsync(fileUri); if (!fileInfo.exists) throw new Error('file missing'); const totalSize = fileInfo.size; const totalParts = Math.ceil(totalSize / PART_SIZE); const headers = { 'Content-Type': 'application/json', Authorization: `Bearer ${authToken}`, }; const partBytes = (n: number) => Math.min(n * PART_SIZE, totalSize) - (n - 1) * PART_SIZE; try { store.setStatus(taskId, 'uploading'); // Step 1: if an uploadId is already saved, do NOT call initiate again (that starts a different upload) let current: MultipartState | undefined = task.multipart; if (!current) { const initRes = await fetch(`${apiBaseUrl}/uploads/initiate`, { method: 'POST', headers, body: JSON.stringify({ fileName, size: totalSize }), }); if (!initRes.ok) throw new Error(`initiate failed: ${initRes.status}`); const init = (await initRes.json()) as { uploadId: string; key: string }; current = { uploadId: init.uploadId, key: init.key, parts: [] }; store.setMultipart(taskId, current); } const session: MultipartState = current; // Step 2: ask for fresh pre-signed URLs only for the parts still missing (old URLs may have expired) const done = new Set(session.parts.map((p) => p.PartNumber)); const pendingNumbers: number[] = []; for (let n = 1; n <= totalParts; n++) if (!done.has(n)) pendingNumbers.push(n); let uploadedBytes = session.parts.reduce((sum, p) => sum + partBytes(p.PartNumber), 0); store.updateProgress(taskId, uploadedBytes); if (pendingNumbers.length > 0) { const partUrlsRes = await fetch(`${apiBaseUrl}/uploads/part-urls`, { method: 'POST', headers, body: JSON.stringify({ uploadId: session.uploadId, key: session.key, partNumbers: pendingNumbers }), }); if (!partUrlsRes.ok) throw new Error(`part-urls failed: ${partUrlsRes.status}`); const { parts } = (await partUrlsRes.json()) as { parts: PartUrl[] }; async function uploadPart(part: PartUrl): Promise<void> { const start = (part.partNumber - 1) * PART_SIZE; const size = partBytes(part.partNumber); // Read only the byte range we need (never the whole file) const base64 = await FileSystem.readAsStringAsync(fileUri, { encoding: FileSystem.EncodingType.Base64, position: start, length: size, }); const res = await fetch(part.url, { method: 'PUT', body: decodeBase64ToUint8Array(base64) as any, }); if (!res.ok) throw new Error(`part ${part.partNumber} failed: ${res.status}`); const etag = res.headers.get('ETag')?.replace(/"/g, ''); if (!etag) throw new Error(`part ${part.partNumber}: ETag missing`); // Record after every part — if the app dies, nothing up to here is lost session.parts.push({ PartNumber: part.partNumber, ETag: etag }); store.setMultipart(taskId, { ...session, parts: [...session.parts] }); uploadedBytes += size; store.updateProgress(taskId, uploadedBytes); } const queue = [...parts]; const workers = Array.from({ length: PARALLELISM }, async () => { while (queue.length > 0 && !shouldStop()) { const next = queue.shift(); if (!next) return; await retryWithBackoff(() => uploadPart(next), 3); } }); await Promise.all(workers); } // If we were cut off, end as paused and continue next time if (session.parts.length < totalParts) { store.setStatus(taskId, 'paused'); return; } // Step 3: Complete const sorted = [...session.parts].sort((a, b) => a.PartNumber - b.PartNumber); const completeRes = await fetch(`${apiBaseUrl}/uploads/complete`, { method: 'POST', headers, body: JSON.stringify({ uploadId: session.uploadId, key: session.key, parts: sorted }), }); if (!completeRes.ok) throw new Error(`complete failed: ${completeRes.status}`); store.setStatus(taskId, 'completed'); } catch (e: any) { store.setStatus(taskId, 'failed', e.message); throw e; }}function decodeBase64ToUint8Array(base64: string): Uint8Array { const binString = atob(base64); const bytes = new Uint8Array(binString.length); for (let i = 0; i < binString.length; i++) bytes[i] = binString.charCodeAt(i); return bytes;}async function retryWithBackoff<T>(fn: () => Promise<T>, max: number): Promise<T> { let lastErr: any; for (let i = 0; i < max; i++) { try { return await fn(); } catch (e) { lastErr = e; await new Promise((r) => setTimeout(r, 500 * Math.pow(2, i))); } } throw lastErr;}
Expected behavior: a 1GB file splits into roughly 205 parts of 5MiB, uploaded three at a time. If the app dies midway, the resume reads the saved uploadId and the ETags of finished parts, then sends only what is missing. Once every part is in, CompleteMultipartUpload stitches them into a single object.
An earlier version of this article's code had no such record. If you call initiate again on every resume, you get a different uploadId, and the parts you already sent stay on the server as orphans. A Multipart upload is only resumable for as long as the device still holds the uploadId and the ETags.
Three-way parallelism is a starting point. More connections don't make the radio any wider, so on cellular you can hit a ceiling. Branch on the NetInfo connection type — raise it on Wi-Fi only, say — and always decide from measurements on your own devices and networks.
iOS background transfers — separate what keeps going from what picks things back up
Many of us want a transfer started in the foreground to keep going after the user goes home. What I find easiest to get wrong is mixing up what each mechanism is for.
Splitting into parts or resuming midway (it sends the whole file)
expo-background-task
Picks unfinished tasks back up in the short windows the OS grants
Sending a few more parts of a task that still has its uploadId
Long transfers themselves
The Multipart code in this article
Parallel transfer while the app is in front
Large uploads that must resume
Running on after the app is closed
The choice comes down to file size and whether "start over on failure" is acceptable. Up to a few hundred MB, handing one pre-signed PUT to a background session is smaller to build and keeps going when the app is closed. A BACKGROUND session works while the app is in the background and keeps retrying until it succeeds or is canceled (per the comment in Expo's type definitions). The price is that a broken transfer restarts from byte zero.
For files beyond 1GB, or on unstable networks, the Multipart resume record earns its keep — and picking that back up after the app goes to the background is the job of the BackgroundTask below.
One more update: expo-background-fetch, which an earlier version of this article used, was replaced and deprecated by expo-background-task in Expo SDK 53. It uses BGTaskScheduler on iOS and WorkManager on Android.
// lib/backgroundUpload.tsimport * as BackgroundTask from 'expo-background-task';import * as TaskManager from 'expo-task-manager';import { useUploadStore } from '../store/uploadStore';import { uploadWithMultipart } from './uploadMultipart';const TASK_NAME = 'rork-resumable-upload';const TIME_BUDGET_MS = 20 * 1000; // the window is cut short; stop yourself with room to spare// Expected behavior: starts when the OS allows, and advances tasks that still hold an uploadId a few parts at a timeTaskManager.defineTask(TASK_NAME, async () => { try { await useUploadStore.getState().hydrateFromStorage(); const tasks = useUploadStore.getState().tasks; const pending = Object.values(tasks).filter( (t) => (t.status === 'paused' || t.status === 'failed') && t.multipart, ); const deadline = Date.now() + TIME_BUDGET_MS; const token = await getAuthToken(); // from expo-secure-store for (const task of pending) { if (Date.now() > deadline) break; try { await uploadWithMultipart( task.id, task.fileUri, task.fileName, process.env.EXPO_PUBLIC_API_URL!, token, () => Date.now() > deadline, ); } catch (e) { console.warn('bg upload failed', task.id, e); } } return BackgroundTask.BackgroundTaskResult.Success; } catch (e) { return BackgroundTask.BackgroundTaskResult.Failed; }});export async function registerBackgroundUpload(): Promise<void> { await BackgroundTask.registerTaskAsync(TASK_NAME, { minimumInterval: 15, // minutes; a hint — the OS decides the real interval });}async function getAuthToken(): Promise<string> { // omitted: read the JWT from expo-secure-store return '';}
What iOS does not promise: a BackgroundTask runs when iOS decides it's a good time, based on usage patterns, battery state, and network conditions. You cannot order it to "keep sending now," and if the user force-quits the app it may not start at all. That is why this task is designed as a short continuation you can stop yourself with shouldStop, not as the thing that carries a long transfer.
If you need truly uninterrupted transfer, you need a native module that drives URLSessionConfiguration.background directly. Expo's createUploadTask covers the one-file-one-request case described above; beyond that you'll look at something like react-native-background-upload or your own native code. If you adopt a third-party module, check its maintenance status and its support for your Expo SDK first.
UX: progress display, cancellation, and error recovery
Solid transfer plumbing isn't enough — if the user can't see what's happening, they churn anyway. Here's a progress UI wired to the Zustand store.
Startup resume confirmation: any task still in uploading when the app was killed should demote to paused on launch and ask before resuming. Auto-resuming over cellular can burn through a user's data allowance on a large transfer.
Cleanup on cancel: skip AbortMultipartUpload and the incomplete parts stay in storage. R2 aborts them automatically after 7 days by default, but until then they count toward what you store. On cancel, always call the server's abort endpoint.
Wi-Fi-only mode: expose a setting so users can restrict uploads to Wi-Fi. Check NetInfo.fetch() for connection type and keep tasks in paused while on cellular.
Four spots where it's easy to stumble once you're following the implementation.
① Memory: Base64 chunks pile up
FileSystem.readAsStringAsync returns a string about 4/3 the size of the binary. For a 5MiB part, string plus bytes comes to a dozen-odd MB per part, roughly 35MB for three in flight. Because you never read the whole file, memory stays flat even at 1GB — but raise parallelism and part size together and that number grows honestly. Drop your references once a part is sent, and keep the number of parts you queue in Promise.all small.
② Parallelism: more isn't always faster
As noted above, raising parallelism on a weak signal doesn't guarantee a shorter total time. Switch it by NetInfo connection type (Wi-Fi or cellular) and decide by measuring.
③ Low Power Mode: fewer chances to run in the background
iOS offers Low Power Mode when the battery drops to 20%, and it reduces background activity. It doesn't kill your app, but it certainly reduces how often BackgroundTask is called. Check lowPowerMode via getPowerStateAsync in expo-battery and tell the user on screen that "the rest will be sent when you plug in."
④ Android: declaring a foreground service type
From Android 14, a foreground service must declare its type. For data transfer, that means the dataSync type and the FOREGROUND_SERVICE_DATA_SYNC permission. To keep sending after the app closes, use the dataSync type in react-native-background-actions, or call WorkManager natively. With Expo EAS, add FOREGROUND_SERVICE_DATA_SYNC to the Android permissions in app.json.
None of these show up while your test files are small. Settling them in the first implementation is far cheaper than fixing them later.
Server-side essentials — the four endpoints you need
The client code above leans on four server endpoints. Here is a minimal Cloudflare Workers implementation using Hono and the R2 binding. Add it to your existing API and connect an R2_BUCKET binding in wrangler.toml.
// api/uploads.ts (Cloudflare Workers + Hono)import { Hono } from 'hono';import { AwsClient } from 'aws4fetch';type Env = { R2_BUCKET: R2Bucket; R2_ACCOUNT_ID: string; R2_ACCESS_KEY_ID: string; R2_SECRET_ACCESS_KEY: string; R2_BUCKET_NAME: string;};const MAX_SIZE = 5 * 1024 * 1024 * 1024; // the cap your app allows (a value you choose, not R2's limit)const MAX_PARTS = 10000; // R2 / S3 limit on partsconst app = new Hono<{ Bindings: Env }>();// 1. Start a multipart upload: return an uploadId and an object keyapp.post('/uploads/initiate', async (c) => { const { fileName, size } = await c.req.json<{ fileName: string; size: number }>(); if (!Number.isFinite(size) || size <= 0 || size > MAX_SIZE) { return c.json({ error: 'invalid size' }, 400); } // Don't use the raw file name in the key; keep only safe characters const safeName = String(fileName).replace(/[^\w.\-]+/g, '_').slice(0, 120); const key = `u/${crypto.randomUUID()}/${safeName}`; const multipart = await c.env.R2_BUCKET.createMultipartUpload(key); // In production, store size, key and user ID in a DB here and check them in complete return c.json({ uploadId: multipart.uploadId, key });});// 2. Issue pre-signed URLs for the missing parts (valid for 1 hour)app.post('/uploads/part-urls', async (c) => { const { uploadId, key, partNumbers } = await c.req.json<{ uploadId: string; key: string; partNumbers: number[]; }>(); if ( !Array.isArray(partNumbers) || partNumbers.length === 0 || partNumbers.length > MAX_PARTS || partNumbers.some((n) => !Number.isInteger(n) || n < 1 || n > MAX_PARTS) ) { return c.json({ error: 'invalid parts' }, 400); } const aws = new AwsClient({ accessKeyId: c.env.R2_ACCESS_KEY_ID, secretAccessKey: c.env.R2_SECRET_ACCESS_KEY, service: 's3', region: 'auto', }); const endpoint = `https://${c.env.R2_ACCOUNT_ID}.r2.cloudflarestorage.com`; const parts = await Promise.all( partNumbers.map(async (n) => { const url = new URL(`${endpoint}/${c.env.R2_BUCKET_NAME}/${key}`); url.searchParams.set('partNumber', String(n)); url.searchParams.set('uploadId', uploadId); url.searchParams.set('X-Amz-Expires', '3600'); // the expiry lives on the URL const signed = await aws.sign(url.toString(), { method: 'PUT', aws: { signQuery: true }, }); return { partNumber: n, url: signed.url }; }), ); return c.json({ parts });});// 3. Stitch the parts together once all are uploadedapp.post('/uploads/complete', async (c) => { const { uploadId, key, parts } = await c.req.json<{ uploadId: string; key: string; parts: { PartNumber: number; ETag: string }[]; }>(); const multipart = c.env.R2_BUCKET.resumeMultipartUpload(key, uploadId); const object = await multipart.complete( parts.map((p) => ({ partNumber: p.PartNumber, etag: p.ETag })), ); return c.json({ ok: true, key: object.key, size: object.size });});// 4. The client's cancel path: abort an unfinished multipart uploadapp.post('/uploads/abort', async (c) => { const { uploadId, key } = await c.req.json<{ uploadId: string; key: string }>(); const multipart = c.env.R2_BUCKET.resumeMultipartUpload(key, uploadId); await multipart.abort(); return c.json({ ok: true });});export default app;
Why R2's native binding plus aws4fetch? R2's Workers binding supports createMultipartUpload / resumeMultipartUpload directly but doesn't expose pre-signed URL generation. For the client to PUT parts without going through your Worker, it needs pre-signed URLs, so only that step uses aws4fetch to apply SigV4 against the S3-compatible REST endpoint. Start, complete, and abort are faster and simpler through the binding.
R2 Multipart has a rule that every part except the last must be the same size. That's one more reason the client pins PART_SIZE. If an app update changes the part size, store the part size in the multipart record so in-flight uploads don't break.
Add auth. Wrap these routes with middleware that validates a Bearer token (a JWT, a Supabase session, whatever you use). Left unauthenticated, anyone can start a Multipart upload and spend your storage budget. In complete and abort, also check that the uploadId and key were issued to that user by initiate.
Testing the upload flow before shipping
Uploads are the category of feature where "it worked on office Wi-Fi" proves nothing. Here are the tests worth running before release, with what you should expect.
① Network Link Conditioner (iOS) / Chrome DevTools throttling: simulate "Very Bad Network" (1% loss, 500ms RTT). Your upload should still complete for any file size. Taking a long time is fine; ending in failure is a fail.
② Airplane mode flip: start a 200MB upload. At 30% progress, toggle airplane mode on for 10 seconds, then off. It should resume automatically and continue from the saved parts, not from zero.
③ Force-quit recovery: start a 500MB upload and push it to 50%. Force-quit from the app switcher. On relaunch the task should appear as paused, and tapping it should skip finished parts and continue. If initiate is called again here, your uploadId isn't being saved.
④ Background behavior: expectations differ by mechanism. A PUT on a BACKGROUND session should finish even after you go home. A Multipart upload driven by BackgroundTask advances only as far as the windows the OS grants — "done after 20 minutes" is not guaranteed — so check that UploadProgressList shows the correct progress when you return to the foreground and that you can continue from there.
⑤ Cancellation leaks: cancel 10 files at scattered progress points. Your storage should show zero unfinished multipart uploads. If any remain, abort isn't being called.
⑥ Large-file stress: upload the largest file your app will realistically handle (say, 2GB of 4K video) on iOS and Android, over Wi-Fi and 4G/5G. Record completion time, failure count, and peak memory; those become the starting values for what you monitor in production.
Automating ① to ⑤ in CI with Maestro or Detox is the ideal end state, but until then a manual pass each release still gives you a net for regressions.
Production readiness checklist
Here's what to verify before shipping resumable uploads. The list is long, so work through it one item at a time in the release sprint.
Server: no unfinished uploadId is left lying around. R2 aborts them after 7 days by default; if you want sooner, set a lifecycle rule or run a cron that calls abort
Server: part numbers are validated to 1–10,000 (anything outside is rejected)
Server: the size of the finished object matches the size declared in initiate
Client: pre-signed URLs are re-requested on every resume (a URL past its one-hour expiry won't work)
Client: hydrateFromStorage runs on cold start to restore unfinished tasks
Client: the uploadId and finished-part ETags are persisted after every part
Client: cancel calls abort on the server
UX: the copy tells users accurately whether it is safe to close the app, matched to the mechanism you use
UX: failure messages prescribe an action ("we'll resume once you're on Wi-Fi") rather than "please try again"
Observability: Sentry / Firebase Crashlytics dashboards track completion rate, duration, and failure-reason distribution
Observability: the server tracks per-uploadId progress and auto-aborts uploads idle for an hour or more
On the binary-size side, Slimming Down Rork App Binaries is worth pairing with this work — upload dependencies tend to bloat, and you'll want to keep both in check. If you're on R2, Rork × Cloudflare R2 File Storage Implementation has a minimal server snippet for the pre-signed URLs this guide assumes.
Whether an upload can resume depends on who holds the record. With TUS it's the server; with Multipart it's the device.
Your next step: check whether your app actually saves the uploadId. If it doesn't, one force-quit test (③) will tell you in a minute.
Share
Thank You for Reading
Rork Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.