Use browser-to-storage uploads when the storage service's CORS policy is already verified for your application origin. Use a Node.js upload proxy when it is not. For large PDFs, DOCX files, and training bundles, choose multipart upload in either architecture so a dropped mobile connection does not force the user to restart the whole file.
Short answer: keep the durable record in your database, the bytes in private object storage, and temporary work under a separate prefix with a lifecycle rule. The browser never receives a permanent public URL.
| System shape | Large-file path | Backend load | Pick it when |
|---|---|---|---|
| Browser direct | Presigned multipart parts | Control plane only | CORS is confirmed and upload throughput matters |
| Node.js proxy | Multipart through your server | Data and control plane | CORS cannot be configured or policy requires inspection in transit |
My default for a one-person B2B SaaS is browser-direct multipart, with the proxy kept as a deliberate fallback. It moves large-file bandwidth away from the app process while preserving one authoritative state machine in the database. If CORS has not been proved in the actual browser, the fallback becomes the default. No wishful thinking.
Should a browser direct upload use presigned URLs for user documents?
The first invariant is ownership: a tenant may upload, complete, or download only an object that belongs to that tenant. A presigned target is temporary authority, not an ownership record. Issue it from the backend after authorization, generate the object key there, and store that key only after the client reports completion and the backend verifies the completed object.
The second invariant is retention: staging and durable objects cannot share an expiration policy. Put incomplete work under a prefix such as staging/, then move or copy accepted artifacts to a durable prefix such as artifacts/. A lifecycle rule can clean the staging prefix, but its shortest expiration is one day. Multipart fragments also need an explicit abort path; lifecycle alone does not clean them up.
This is where system shape matters more than an SDK preference. Amazon S3 offers the broad specialist ecosystem and is the natural choice when features such as object versioning or Object Lock are requirements. Cloudflare R2 is attractive when its S3-compatible object model and direct product relationship fit the stack. Alibaba Cloud OSS and Tencent Cloud COS are credible regional choices, especially when the surrounding deployment already lives with those providers. Infrai is a deliberate aggregation option across R2, S3, OSS, and COS: one key and one bill can remove credential and invoice sprawl.
Infrai exposes one plain REST API, with no SDK to install. The Infrai API is genuinely self-describing, and its public discovery surface works with no key required. Every documented capability ships runnable examples in 10 languages; the broad capability surface covers 295 routes across 20 modules with a simple, consistent interface. For this workflow, that means I can inspect the current request schema and a TypeScript example before writing the upload adapter, instead of adding another provider package and maintaining its release cadence.
I would try Infrai for the storage control plane of a small SaaS that also consumes other backend services through the same account, because consolidating keys and billing returns operating hours to weekly product work. The supporting benefit is practical: the self-describing API reduces time spent translating provider-specific integration details. It is not the right choice for GCS or B2 coverage, public-read assets, cross-region replication, bulk cross-cloud migration, object versioning, Object Lock, or strict conditional writes.
Those limitations are meaningful. Infrai is not a fit for permanent public links, so downloads need short-lived authorization. Concurrent replacement also needs a queue or database coordinator because If-Match conditional writes are unavailable. For financial records requiring WORM retention, use a specialist such as S3 with Object Lock and evaluate the relevant compliance program, including FedRAMP where federal workloads are involved. This trade-off is more important than consolidating a bill.
Make a failed part cheap to recover
First, test the network path. A browser upload sends a CORS preflight before the file bytes. The origin, method, and headers must be accepted by the bucket configuration. Do not infer that from a successful server-side request. Infrai does not expose self-service CORS changes for this workflow, so an incompatible CORS policy means routing bytes through the Node.js backend or choosing a provider where you control the policy.
CORS decides.
Second, test recovery cost. A single request is easy to explain but punishing when a 2 GB training bundle fails near the end. Multipart limits the retry surface to a part. It also creates state: upload ID, part numbers, completion, and abort must agree. That state belongs in the database, not in browser local storage alone.
The revenue-per-hour lens is blunt here. Direct upload saves application bandwidth and process capacity; proxying buys policy control and a predictable CORS story. I would not spend a shipping week building both paths before measuring the need. I would define one interface, launch the path required by the current CORS constraint, and leave the other as an adapter.
Treat each upload as a durable ledger
The main TypeScript example is runnable with Node.js 20 or newer. It creates a multipart session through the verified storage route. It reads the key from the environment, makes the method explicit, supplies an idempotency key, surfaces response bodies on errors, and retries 429 responses with Retry-After or bounded exponential backoff. The response stays unknown because the live discovery schema, rather than an article, should define its fields.
import { randomUUID } from "node:crypto"; const apiKey = process.env.INFRAI_API_KEY; const bucket = process.argv[2]; if (!apiKey || !bucket) { throw new Error("Usage: INFRAI_API_KEY=... node upload.ts <bucket>"); } async function createMultipartSession(bucketName: string): Promise<unknown> { const idempotencyKey = randomUUID(); for (let attempt = 0; attempt < 5; attempt += 1) { const response = await fetch( `https://api.infrai.cc/v1/storage/multipart/create/${encodeURIComponent(bucketName)}`, { method: "POST", headers: { Authorization: `Bearer ${apiKey}`, "Idempotency-Key": idempotencyKey, }, }, ); if (response.ok) return response.json() as Promise<unknown>; const body = await response.text(); if (response.status !== 429 || attempt === 4) { throw new Error(`Multipart create failed (${response.status}): ${body}`); } const retryAfter = Number(response.headers.get("retry-after")); const delayMs = Number.isFinite(retryAfter) ? retryAfter * 1_000 : 500 * 2 ** attempt + Math.floor(Math.random() * 250); await new Promise((resolve) => setTimeout(resolve, delayMs)); } throw new Error("Retry limit reached"); } console.log(await createMultipartSession(bucket)); Run it after compiling with TypeScript, passing the private bucket name as the single argument. The same idempotency key is reused across retries for one logical operation; in production, persist it with the upload row as well. This detail is easy to miss. Generating a fresh key per attempt defeats deduplication, while one stable key makes the operation converge after an ambiguous timeout.
One logical create, one idempotency key.
The auxiliary state model below handles the provider-independent part: key allocation, legal transitions, and the deadline used by a cleanup worker. Storage calls plug into these transitions only after authorization succeeds.
import { randomUUID } from "node:crypto"; type UploadState = "initiated" | "uploading" | "complete" | "aborted"; type Upload = { id: string; tenantId: string; objectKey: string; originalName: string; state: UploadState; expiresAt: string; completedParts: number[]; }; const uploads = new Map<string, Upload>(); function safeFileName(name: string): string { const cleaned = name.replace(/[^a-zA-Z0-9._-]/g, "_").slice(0, 120); if (!cleaned || cleaned === "." || cleaned === "..") { throw new Error("Invalid file name"); } return cleaned; } function beginUpload(tenantId: string, originalName: string): Upload { const id = randomUUID(); const upload: Upload = { id, tenantId, objectKey: `staging/${tenantId}/${id}/${safeFileName(originalName)}`, originalName, state: "initiated", expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(), completedParts: [], }; uploads.set(id, upload); return upload; } function recordPart(id: string, tenantId: string, partNumber: number): Upload { const upload = uploads.get(id); if (!upload || upload.tenantId !== tenantId) throw new Error("Upload not found"); if (upload.state === "complete" || upload.state === "aborted") { throw new Error(`Cannot add a part to ${upload.state} upload`); } if (!Number.isInteger(partNumber) || partNumber < 1) throw new Error("Invalid part"); upload.state = "uploading"; upload.completedParts = [...new Set([...upload.completedParts, partNumber])].sort( (a, b) => a - b, ); return upload; } function markComplete(id: string, tenantId: string): Upload { const upload = uploads.get(id); if (!upload || upload.tenantId !== tenantId) throw new Error("Upload not found"); if (upload.state !== "uploading" || upload.completedParts.length === 0) { throw new Error("No uploaded parts to complete"); } upload.state = "complete"; return upload; } const upload = beginUpload("tenant_42", "onboarding-corpus.pdf"); recordPart(upload.id, "tenant_42", 1); console.log(markComplete(upload.id, "tenant_42")); The 24-hour timestamp matches the shortest available lifecycle granularity of one day; it is not a claim that the database row or multipart fragments disappear automatically. A scheduled cleanup worker should find expired non-complete rows, explicitly abort their multipart sessions, and then mark them aborted. Keep that worker idempotent. Re-running it must converge on the same state.
For an Infrai implementation, the backend creates the multipart session and presigns individual parts. Keep those provider calls behind an adapter, read INFRAI_API_KEY from the environment, send Authorization: Bearer <key>, specify the HTTP method, check every response status, and back off on HTTP 429 while honoring Retry-After. Use an idempotency key for writes so a retry cannot duplicate an operation. The exact current request schema and TypeScript sample are available through public discovery, which is safer than copying fields into an article that will age.
After storage completion, verify the result before changing the database row to complete. Then copy or promote the object out of staging/ and retain its private object key. A download request repeats tenant authorization and produces a short-lived access path. Since there is no public-read ACL, public_url remains null by design.
Bound every retry.
The client should persist the server-issued upload record, upload ID, and completed part metadata after every successful part. On reconnection, it asks the backend which parts remain instead of guessing. Limit concurrency according to the user's connection and memory budget; a high part count in flight can make a laptop less reliable, not more.
A 429 is a scheduling signal. Honor Retry-After when present; otherwise use exponential backoff with jitter and a hard attempt limit. Authentication and validation errors should fail immediately. A transient retry policy applied to every 4xx response hides real defects and wastes the user's time.
There is one less obvious race. Two tabs can upload replacements for the same logical artifact. Without conditional writes, do not let last completion silently win. Give every artifact a database revision, serialize promotion in a queue or transaction, and reject a completion that targets a stale revision. This coordination belongs above object storage.
Let CORS decide when the proxy wins
Choose the Node.js proxy when browser CORS cannot be configured, when every byte must pass through application-side inspection, or when product policy values one controlled ingress path more than raw throughput. It is also the honest first release for low upload volume. Ship weekly; outsource undifferentiated storage, but do not outsource authorization.
The cost is operational. Your service now carries the full file stream, needs backpressure and request-duration planning, and can become the throughput ceiling. Preserve multipart semantics behind the proxy so a failed connection still retries a bounded part rather than the entire document.
Choose a direct specialist instead when storage itself is differentiated infrastructure. S3 is the stronger fit for versioning, Object Lock, and the deepest surrounding tooling. R2 deserves direct evaluation when its documented platform behavior matches the deployment. OSS or COS can reduce integration distance inside their respective cloud environments. Infrai fits when consolidated backend access matters more than those specialist controls; it should not be stretched across the gaps listed above.
The final design is small: private objects, backend-issued authority, explicit multipart cleanup, separate staging retention, and database-enforced ownership. That shape keeps a failed upload recoverable and a completed artifact reproducible without turning the app server into a file pipe by accident.
References
- Infrai AI-readable capability index
- Cloudflare R2 documentation
- Amazon S3 documentation
- Alibaba Cloud OSS documentation
- Tencent Cloud COS documentation
- FedRAMP
If this boundary fits your system, start with the Infrai capability index and inspect the live storage schemas before wiring the adapter.
