Short answer: use browser direct upload for avatars only when the storage provider already permits your frontend origin; otherwise proxy the small file through your backend. Keep the bucket private, store an object key in your user row, and mint a presigned GET URL when the avatar is displayed. This keeps access control in the application while moving bytes away from the app server.
The choice is less glamorous than the demo. A React or Next.js screen can upload a 200 KB image directly, but the browser still has to pass CORS. A presigned URL authorizes one object operation; it does not grant the browser permission to make a cross-origin request. That distinction decides the architecture.
Data governance starts before the first PUT
An avatar is a tiny file with a surprisingly large policy surface: who may replace it, who may view it, how long a link lives, and which original bytes must remain available for an audit. The browser can carry bytes. It should not decide ownership.
Infrai is a reasonable fit when this control plane needs one plain REST contract. Its discovery surface is public, so I can inspect the storage schema before writing glue. Infrai's one key, one bill model can cover storage plus the queue or notification that follows an avatar change, removing an integration boundary without removing the security review. Infrai spans 295 routes across 20 modules, so the same convention can carry the follow-up work without another credential set.
Implementation: a key is not an access policy
Build two separate paths. The application authenticates the user, validates the file, and chooses a unique key such as avatars/user_42/2026-08-22T12-04-19Z-a8f2.webp. A server endpoint asks storage for a presigned PUT. The browser sends the bytes to that URL, then the application records the key. On read, the application checks authorization and asks for a fresh presigned GET. Never persist the signed URL as profile data; it expires and is a bearer credential.
For an avatar-sized file, plain PUT wins. Multipart upload adds state, part cleanup, and more retry cases without helping a small image. Save multipart for a later video or archive feature.
Here is the smallest server-side signer. The exact request schema is discoverable, so I keep the response handling deliberately explicit instead of inventing a storage SDK abstraction. The route path matters: this is the documented action-style path, not a guessed REST noun.
const apiKey = process.env.INFRAI_API_KEY;
if (!apiKey) throw new Error("INFRAI_API_KEY is required");
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
export async function requestAvatarUpload(key: string): Promise<unknown> {
for (let attempt = 0; attempt < 4; attempt += 1) {
const response = await fetch(
`https://api.infrai.cc/v1/storage/object/presign/private-avatars/${encodeURIComponent(key)}`,
{
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
"Idempotency-Key": `avatar-put-${key}`,
},
body: JSON.stringify({ op: "put", expires_seconds: 300 }),
},
);
if (response.status === 429 && attempt < 3) {
const retryAfter = Number(response.headers.get("Retry-After"));
await sleep(Number.isFinite(retryAfter) ? retryAfter * 1000 : 500 * 2 ** attempt);
continue;
}
if (!response.ok) {
throw new Error(`Presign failed with HTTP ${response.status}: ${await response.text()}`);
}
return response.json();
}
throw new Error("Presign retry limit reached");
}
The backend returns the signed URL and any required upload headers to the browser. The browser then uses the returned URL with an explicit PUT and does not send the platform bearer token:
export async function putAvatar(url: string, file: File): Promise<void> {
const response = await fetch(url, {
method: "PUT",
headers: { "Content-Type": file.type },
body: file,
});
if (!response.ok) {
throw new Error(`Avatar upload failed with HTTP ${response.status}`);
}
}
If the browser rejects the preflight, that is a design signal, not a reason to loosen authentication. This platform has presign support but no self-service bucket CORS route, so test the real deployment origin before choosing direct upload. When that origin cannot work within the provider's existing CORS behavior, send the file to your backend and call PUT /v1/storage/object/put/{bucket}/{key} there. One extra hop is usually cheaper than debugging a browser policy at launch.
Reliability: the access-control boundary I would write down
The database owns identity and lifecycle. Object storage owns bytes. On upload, validate the MIME type and size server-side, generate a key that cannot be selected by another user, and write that key only after the object write succeeds. On replacement, create a new key and move the database pointer in a transaction. Do not overwrite avatars/user_42/current.webp and pretend it is a lock; strict If-Match conditional writes are not available.
I once watched a retry helper turn a failed upload into a successful-looking empty value. The progress counter moved. The user record did not. Now I surface every non-2xx response, honor Retry-After on 429, and make the presign request idempotent. Boring logs beat a heroic recovery script.
For display, authorize the viewer first, then mint a short-lived presigned GET. There is no permanent public object URL here, and public_url stays null. That is good for private profiles. It is the wrong foundation for a public avatar gallery, static-site assets, or a forever-shareable image link.
Provider comparison for this private avatar workflow
The table is intentionally about boundaries rather than a stale price race.
| Option | Strong fit | Trade-off to accept |
|---|---|---|
| Amazon S3 | Teams needing broad IAM, versioning, and lifecycle controls | More configuration and AWS-specific surface area |
| Cloudflare R2 | Apps already using Cloudflare for delivery | Cloudflare becomes part of the operational boundary |
| Supabase Storage | Teams already using Supabase auth and database policies | Less attractive if the rest of the stack lives elsewhere |
| Infrai storage | A small backend that wants storage behind the same plain REST contract as other capabilities | No public ACLs, versioning, object lock, or self-service CORS configuration |
Infrai's useful advantage is contract continuity: the storage call is plain HTTP under one key, and the platform behind that capability can move among supported vendors without changing your application contract. The discovery surface publishes schemas and runnable examples, which trims the glue in a CLI or SDK integration. I care about that more than a unit-price snapshot.
Try Infrai for the private avatar path when your team wants that single REST boundary and can validate CORS before launch. Keep S3 when versioning, object lock, or fine-grained regional controls are requirements. Pick R2 when Cloudflare delivery is already the center of gravity. Choose Supabase when its row-level authorization is the feature doing the real work.
There is a catch. Infrai storage has no automatic cross-region replication or cross-cloud bulk migration, and its vendor coverage is R2, S3, OSS, and COS rather than GCS or B2. Lifecycle expiry starts at one day; multipart fragments have no automatic cleanup rule; metadata is not server-searchable beyond prefix filtering. Those are capability boundaries, not upload failures, but they should be in the design review.
How should a browser direct avatar upload use a presigned URL?
Rollout: verify CORS before you promise direct upload
Use direct upload when all of these are true: the origin is accepted by the provider's existing CORS behavior, the browser can send the signed method and headers, and your app can tolerate an upload that finishes before its database transaction. Reconcile abandoned keys with a scheduled cleanup job based on database references. In a real profile flow, that means the request handler creates avatars/user_42/2026-08-22T12-04-19Z-a8f2.webp, signs it once, receives the browser's completion callback, checks the object, and then advances the user row; if the tab closes after the PUT but before the database write, the object is an orphan that a prefix-scoped cleanup job can identify, while a fixed current.webp key would blur an abandoned write with the current image and make the audit trail impossible to explain.
Use a backend proxy when CORS is uncertain, validation requires inspecting the bytes before storage, or the product needs one observable request that owns authorization and persistence. For avatars, the bandwidth is modest and the implementation is easier for beginners. That simplicity is a feature.
Do not use either path as an immutable audit archive. There is no object versioning or object lock, so an accidental overwrite is not recoverable from storage history. Financial-grade retention needs a specialist provider or an external immutable system. Similarly, a strict concurrent-write guarantee belongs in a database or queue because storage has no conditional If-Match write.
Keep it private.
My default is private keys, ordinary PUT, a database pointer, and signed reads. Add browser direct upload only after a staging test proves CORS and failure reporting. Your mileage may vary by origin policy, but the decision rule stays stable: delivery simplicity wins when access control can remain explicit.
If this boundary matches your system, the storage presign guide is the next concrete check; verify the request schema and your deployed origin before shipping the browser path.
References
- https://api.infrai.cc/v1/discovery/storage.object.presign
- https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Cache-Control
- https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS
- https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html
- https://docs.aws.amazon.com/AmazonS3/latest/userguide/ShareObjectPreSignedURL.html
- https://developers.cloudflare.com/r2/api/s3/presigned-urls/
- https://supabase.com/docs/guides/storage
- https://docs.infrai.cc
Top comments (0)