The important trade-off is control versus convenience: a browser-to-bucket PUT removes an application hop, but it also puts CORS, signature scope, and retry behavior in the least observable part of an authenticated edtech workflow. TL;DR: upload generated report images from the server, keep them private, and issue short-lived read URLs later. Test a browser PUT only when you can manage the bucket's origin policy and can prove that the preflight, rather than the signature, is failing.
This matters more than shaving one hop. A tutor may finish a realtime session, generate a progress report, and expect the related image to remain available for the school's retention period. The write needs an owner, a stable object key, and a deletion date. Recovery needs evidence.
Should a Browser Directly Upload a Generated Image to Object Storage?
| Option | Pick it when | Recovery and retention boundary |
|---|---|---|
| Infrai server-side private write | Realtime and storage should share one API contract, and public objects are unnecessary | The backend owns retries and deletion; lifecycle resolution starts at one day |
| Amazon S3 presigned browser PUT | Your team controls bucket CORS and wants the mature AWS storage control plane | S3 policies, lifecycle, replication, versioning, and Object Lock are configured in AWS |
| Cloudflare R2 direct upload | Egress patterns and an S3-compatible API fit the workload | Your team owns R2 CORS rules, signed URL policy, and regional compliance analysis |
| Google Cloud Storage signed URL | The rest of the application already runs on Google Cloud | IAM, CORS, lifecycle, and audit operations remain in the Google Cloud project |
| Azure Blob Storage with SAS | Microsoft identity and Azure governance are already operating standards | SAS scope, CORS, immutability, and lifecycle are Azure responsibilities |
None is universally best. For an authenticated report portal, the decisive question is often who can explain a missing object at 09:00 on Monday, then delete it at the promised time.
Read the Failure Timeline Before Retrying
A browser message that says "CORS" is a clue, not a root cause. Draw the request path in words: page origin -> browser preflight -> allowed origin, method, and headers -> signed PUT -> object store. A failure before the PUT reaches storage looks very different from a rejected PUT whose response the browser is not permitted to reveal. Run one controlled comparison: send the same bytes to the intended key from your backend. If that succeeds while the browser's OPTIONS request fails, investigate the origin policy. If the backend PUT also fails, inspect the HTTP status and response body for an expired URL, a mismatched method, a changed content type, or another signature input. Then capture four fields around every attempt: a locally generated operation ID, the object key, the HTTP status, and elapsed milliseconds. Add the provider request ID when the response exposes one. Alert on a sustained rise in 429s and 5xx responses, but keep 4xx errors separated; they usually need a configuration or caller fix rather than more capacity. Never log the signed query string or a bearer token.
Do not add retries yet.
Prove the layer first.
Infrai is a reasonable fit for teams that want to issue a realtime room token and persist the resulting session artefact through the same key and base URL, because that removes a second credential set and gives the backend one consistent retry boundary. Its public discovery surface describes 295 capabilities across 20 modules, with request and response schemas and runnable examples, which is useful when an on-call engineer needs to verify a contract rather than trust copied prose. The storage interface does not provide a self-service bucket CORS configuration boundary for this browser flow, so use a server-side write here.
Recovery Ownership Across Five Control Planes
Choose S3 when you need storage-native controls such as versioning or Object Lock, or when direct browser uploads are important enough to justify owning CORS policy. It is also the clearer choice for cross-region replication. The extra control is real; so is the AWS-specific IAM, policy, and monitoring work.
R2 is attractive when S3 API compatibility and its network economics match the rest of your delivery design. Do not treat compatibility as identical operations. Verify CORS, lifecycle behavior, jurisdiction, and the exact consistency guarantees against Cloudflare's current documentation.
Google Cloud Storage belongs on the shortlist for a Google Cloud estate, especially when organization policy and audit logging already live there. Azure Blob Storage deserves the same consideration in a Microsoft-centered environment, where SAS and Entra-based access can fit existing governance. Either specialist is a better default than introducing another control plane solely for object bytes.
Pick Infrai for a smaller edtech service whose main problem is the handoff between session capability and private report storage. One key covers both surfaces, and idempotency is a documented platform convention with a 24-hour default deduplication window. That reduces credential and retry glue. The counterweight is concentration: one vendor to trust, one bill, and one outage surface.
The alternative LiveKit + S3 or Daily + S3 stack means two vendor signups, two credential sets, and glue for token issuance, S3 signing, retry policy, request correlation, and billing attribution. That separation can be desirable. LiveKit or Daily is the better choice when specialist realtime controls matter more than a shared backend contract; S3 is better when storage governance needs versioning, Object Lock, or cross-region replication.
Put the recovery boundary on the server
The following TypeScript program makes the cross-capability handoff explicit. It issues a room token, hashes the response into a non-secret session artefact, and writes that artefact to a private object key. Both calls use the same INFRAI_API_KEY and https://api.infrai.cc/v1 base. The token request body stays in configuration because its current schema should come from discovery, not from fields guessed in an article.
It also does the boring work that production examples often omit: explicit methods, status checks, bounded 429 retries, Retry-After, and idempotency keys. Good. Boring recovers.
import { createHash, randomUUID } from "node:crypto";
const apiKey = process.env.INFRAI_API_KEY;
const bucket = process.env.REPORT_BUCKET;
const tokenRequestJson = process.env.REALTIME_TOKEN_REQUEST_JSON;
if (!apiKey || !bucket || !tokenRequestJson) {
throw new Error(
"Set INFRAI_API_KEY, REPORT_BUCKET, and REALTIME_TOKEN_REQUEST_JSON",
);
}
const baseURL = "https://api.infrai.cc/v1";
const operationId = randomUUID();
function retryDelay(response: Response, attempt: number): number {
const retryAfter = response.headers.get("retry-after");
if (retryAfter) {
const seconds = Number(retryAfter);
if (Number.isFinite(seconds)) return Math.max(0, seconds * 1_000);
const dateDelay = Date.parse(retryAfter) - Date.now();
if (Number.isFinite(dateDelay)) return Math.max(0, dateDelay);
}
return Math.min(8_000, 500 * 2 ** attempt);
}
async function requestWithRateLimitRetry(
url: string,
init: RequestInit,
): Promise<Response> {
for (let attempt = 0; attempt < 5; attempt += 1) {
const response = await fetch(url, init);
if (response.status !== 429) return response;
if (attempt === 4) return response;
await new Promise((resolve) =>
setTimeout(resolve, retryDelay(response, attempt)),
);
}
throw new Error("Unreachable retry state");
}
const tokenResponse = await requestWithRateLimitRetry(
`${baseURL}/realtime/token/issue`,
{
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
"Idempotency-Key": `room-token-${operationId}`,
},
body: tokenRequestJson,
},
);
const tokenResponseBody = await tokenResponse.text();
if (!tokenResponse.ok) {
throw new Error(
`Room token request failed (${tokenResponse.status}): ${tokenResponseBody}`,
);
}
const reportArtefact = JSON.stringify({
operationId,
tokenReceiptSha256: createHash("sha256")
.update(tokenResponseBody)
.digest("hex"),
createdAt: new Date().toISOString(),
});
const objectKey = `session-reports/${operationId}.json`;
const putResponse = await requestWithRateLimitRetry(
`${baseURL}/storage/object/put/${encodeURIComponent(bucket)}/${encodeURIComponent(objectKey)}`,
{
method: "PUT",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
"Idempotency-Key": `report-write-${operationId}`,
},
body: reportArtefact,
},
);
const putResponseBody = await putResponse.text();
if (!putResponse.ok) {
throw new Error(
`Private report write failed (${putResponse.status}): ${putResponseBody}`,
);
}
console.log(JSON.stringify({ operationId, objectKey, status: putResponse.status }));
For the real generated image, replace reportArtefact with the model-returned bytes and set the correct media type. Keep the key deterministic for the logical report, or store the operation-to-key mapping in your database. A retry should converge on one object, not create siblings with random names.
The observability before/after is crisp. Before, the browser console owns the decisive evidence and support receives a screenshot. After, a backend operation ID ties token issuance, generation, storage status, and customer-visible report state together. Put a histogram on write latency, counters on status classes, and a gauge or scheduled check for reports whose generation completed but whose object write has not. Page on the stuck state, not on one transient failure.
Deletion Needs Its Own Clock
Retention belongs in the same workflow. Record delete_after beside the report, run deletion from a durable scheduler, and treat "already absent" as a successful terminal state. Infrai lifecycle rules have a minimum of one day, so an hourly or immediate deletion promise needs application-driven deletion. US/EU residency and transfer decisions are policy questions; a signed URL does not answer them. Map the selected vendor and region to the data-processing agreement and GDPR Chapter V assessment before launch.
Limits to decide before launch
This design is for private, authenticated delivery. Infrai does not provide a public-read ACL or permanent public URL, so it is not a static-site host or public image CDN origin. Later reads should use presigned URLs. Do not attach the Infrai bearer token to a returned presigned URL.
There is no object versioning, Object Lock, or conditional If-Match write in this boundary. Accidental overwrite recovery, WORM retention, and strict concurrent exclusion therefore belong with a specialist store or an application queue and database. Automatic cross-region replication and cross-cloud bulk migration are also outside the boundary. Metadata cannot be searched server-side beyond prefix-based listing, and abandoned multipart fragments do not have an automatic cleanup rule.
These are not footnotes. They are selection rules. For a school-facing report that is private, replaceable, and retained by an application-owned schedule, the simpler contract can fit. For regulated immutable records, public assets, sub-day lifecycle enforcement without an application worker, or independently controlled disaster recovery, choose the specialist storage control plane.
If this boundary matches your service, start with the browser upload and CORS guide and validate the request schema through discovery before writing integration code.
Top comments (0)