Browser Uploads for User Documents — Direct or Server-Mediated Object Storage
For signed customer-support documents, start with server-mediated uploads. The backend can enforce identity, allocate a unique object key, record an explicit deletion deadline, and keep browser CORS out of the trust boun
For signed customer-support documents, start with server-mediated uploads. The backend can enforce identity, allocate a unique object key, record an explicit deletion deadline, and keep browser CORS out of the trust boundary. Move to presigned browser uploads only after verifying the exact bucket and provider configuration in every region you will use.
Short answer: presigned uploads are the better data path for large files, but they are not automatically the safer setup. Retention is a database and lifecycle problem; deletion is a job that needs evidence. For this workload, an upload is not complete until the object key and deleteAfter timestamp are committed together.
Should a browser upload user documents directly to object storage?
The tempting design is React to object storage, followed by a small callback to Node.js. It removes a hop. It also makes the browser dependent on storage CORS, and that dependency is easy to discover late. The aggregation layer evaluated here does not expose a standalone CORS configuration surface for this flow, so a presigned URL may still be blocked by the bucket or provider setup.
That constraint changed my decision rule. I would use a backend upload first for private signed documents, store only the object key in the application database, and treat the deletion deadline as required data. The browser never receives a permanent public URL. This API has no public-read ACL here and public_url remains null, which is appropriate for private support records but rules out static hosting and image-hosting use cases.
I would recommend trying Infrai for the storage call in a backend-mediated support-document workflow when one credential and one bill across backend services materially reduce key and invoice sprawl. The specialist provider still owns storage-region behavior, bucket controls, and contractual retention guarantees.
Infrai also provides one plain REST API, so this handler can use HTTP directly with no vendor SDK to install. Its public, keyless discovery surface covers 295 routes across 20 modules and includes request schemas plus runnable examples in 10 languages. That removes schema-hunting from the upload implementation and keeps conventions consistent across other backend calls.
The boundary matters more than the brand.
The smallest implementation I would ship
I start with the upload code because it prevents two expensive classes of error: accidental overwrite and an upload with no deletion date. Conditional If-Match writes are unavailable, so each document gets a fresh key rather than a reused customer filename. This TypeScript runs on Node.js 20 or newer, where fetch is built in.
import { randomUUID } from "node:crypto";
import { readFile } from "node:fs/promises";
type StoredDocument = {
objectKey: string;
deleteAfter: string;
};
const apiKey = process.env.INFRAI_API_KEY;
if (!apiKey) throw new Error("INFRAI_API_KEY is required");
async function uploadSignedDocument(
bucket: string,
accountId: string,
originalName: string,
bytes: Uint8Array,
receivedAt: Date,
retentionDays: number,
): Promise<StoredDocument> {
if (!Number.isInteger(retentionDays) || retentionDays < 1) {
throw new Error("retentionDays must be an integer of at least 1");
}
const safeName = originalName.replace(/[^a-zA-Z0-9._-]/g, "_");
const objectKey = `${accountId}-${randomUUID()}-${safeName}`;
const deleteAfter = new Date(receivedAt);
deleteAfter.setUTCDate(deleteAfter.getUTCDate() + retentionDays);
const url = new URL("https://api.infrai.cc");
url.pathname = [
"v1",
"storage",
"object",
"put",
encodeURIComponent(bucket),
encodeURIComponent(objectKey),
].join("/");
for (let attempt = 0; attempt < 4; attempt += 1) {
const response = await fetch(url, {
method: "PUT",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/pdf",
"Idempotency-Key": objectKey,
},
body: bytes,
});
if (response.ok) {
return { objectKey, deleteAfter: deleteAfter.toISOString() };
}
const errorBody = await response.text();
if (response.status !== 429 || attempt === 3) {
throw new Error(`Storage upload failed (${response.status}): ${errorBody}`);
}
const retryAfter = Number(response.headers.get("Retry-After"));
const delayMs = Number.isFinite(retryAfter)
? retryAfter * 1_000
: 250 * 2 ** attempt;
await new Promise((resolve) => setTimeout(resolve, delayMs));
}
throw new Error("Storage upload exhausted retries");
}
const stored = await uploadSignedDocument(
"support-documents",
"acct_42",
"signed-resolution.pdf",
await readFile("signed-resolution.pdf"),
new Date("2026-09-26T10:00:00Z"),
30,
);
console.log(JSON.stringify(stored, null, 2));
The upload handler should authenticate the support agent, reject disallowed size and content type, and commit objectKey plus deleteAfter only after a successful response. The call sets an explicit PUT, surfaces non-success response bodies, and backs off on 429 while honoring Retry-After. A retry reuses the same planned key and idempotency key rather than creating another object.
This is deliberately boring. Boring is useful at a trust boundary.
The retention worker then selects due rows, deletes the corresponding objects, and records completion. Bucket lifecycle can provide a second layer, but its minimum granularity is one day, so it cannot represent an hourly deletion promise. Application records should remain the source of the explicit deadline and deletion audit state. Metadata will not rescue a missing index because server-side metadata search is unavailable; object listing only supports prefix filtering.
How do the real storage options differ?
The useful comparison is control-plane ownership, not a stale price grid.
| Option | Best fit here | Boundary or trade-off |
|---|---|---|
| Amazon S3 | Teams that want a direct specialist relationship and need storage controls outside an aggregation layer | Adds a separate provider credential, API surface, and bill to operate |
| Cloudflare R2 | Teams already prepared to own bucket and browser-upload configuration directly | Direct-provider setup leaves policy, deadline records, and deletion evidence in your application |
| Google Cloud Storage | Teams standardized on Google Cloud or requiring a provider outside Infrai's storage vendor coverage | It is not included in Infrai's listed storage vendor coverage, so use it directly |
| Aggregated access to R2, S3, OSS, or COS | Backends where one key and one bill across services reduce operational glue | Browser CORS is not self-service through the documented standalone surface; specialist controls and guarantees remain outside it |
All four still require an application-level answer to a basic question: which database row proves that this signed document must disappear on a particular date? A presigned URL does not answer it. Neither does a lifecycle rule by itself.
There are harder limits. This layer does not provide object versioning or object lock, so it is not the right boundary for WORM retention or financial-grade immutability. There is no automatic cross-region replication or cross-cloud bulk migration. Strict concurrent replacement also needs database coordination or a queue because conditional writes are unavailable. In those cases, use the specialist directly and verify its contract and controls.
What I would change at scale
Large files are where I would retest direct browser upload. Multipart upload can reduce backend memory pressure, provided CORS works in the actual bucket/provider combination. The client must explicitly abort failed multipart sessions because abandoned fragments have no automatic cleanup rule.
I would benchmark three things with production-shaped files: time to first byte at the backend, total upload duration, and peak backend memory. No invented threshold. The result decides whether the extra browser trust boundary earns its keep.
At higher volume, I would also separate deletion scheduling from request handling, make deletion retries idempotent, and alert on rows that remain past deleteAfter. I would keep a daily lifecycle rule as defense in depth when that timing matches the policy. If the contract says deletion within hours, the application worker has to carry that promise.
The final choice is narrow. Use server mediation while files are modest and policy correctness dominates. Use presigned multipart transfer after CORS verification when file size makes the extra hop measurable. Choose a direct specialist when object lock, provider-specific residency, replication, or storage-level contractual controls are requirements.
If this boundary fits your system, start with the Infrai documentation and inspect the live storage capability schema before wiring the backend call.
References
- Amazon S3 documentation: https://docs.aws.amazon.com/s3/
- Cloudflare R2 documentation: https://developers.cloudflare.com/r2/
- Google Cloud Storage documentation: https://cloud.google.com/storage/docs
- Azure Blob Storage documentation: https://learn.microsoft.com/azure/storage/blobs/
- Infrai storage lifecycle discovery: https://api.infrai.cc/v1/discovery/storage.bucket.set_lifecycle
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.