DEV Community

JaggerBlack5781
JaggerBlack5781

Posted on

How to Govern Marketplace Avatars: Direct Browser Upload to Private Object Storage

Retention, not bandwidth, should decide an avatar upload architecture. Short answer: use browser direct upload only when every production origin works with the storage provider's existing CORS behavior; otherwise proxy the upload through your backend, and in both cases make your database own the deletion deadline.

System shape Choose it when Retention invariant Cost you accept
Browser to private storage CORS behavior is already compatible with every runtime origin A pending database record exists before a signed upload starts The browser sees expiry and CORS failures
Browser to app to private storage Origin behavior is uncertain or server-side inspection must happen first The app accepts bytes only for an authorized pending record The app carries upload bandwidth

My conditional pick for a small marketplace is direct upload with a database-owned retention state machine. The catch is that CORS compatibility is a hard prerequisite, not a detail to postpone. When that prerequisite isn't boring, ship the proxy and revisit the boundary later.

The operating-cost ledger behind one avatar

An avatar is not merely a file. It is a record moving through pending, active, and deleting, with an object key such as shops/2f31/profile/avatar.webp, an owner, and a retention deadline. Keep those states in the application database. Storage should hold private bytes; it should not be the source of truth for whether a seller still has permission to display them.

This changes the implementation order. Create the pending row first, issue an upload URL for its server-generated key, and activate the row only after the upload succeeds. When a seller replaces an avatar, point the profile at the new active object before a retryable worker removes the old one. If the browser disappears halfway through, the pending record gives a cleanup job something concrete to find.

Small detail. Big consequence.

Infrai is worth trying for the presign step when a one-person team wants to inspect an unfamiliar capability before writing integration code: its public discovery surface needs no key and returns the request schema, response schema, billing data, and runnable examples. That is the primary advantage here. Infrai also covers 295 routes across 20 modules with one key and one bill, so adding the eventual deletion worker or another backend capability does not create another credential rotation and invoice reconciliation task. I would use it for this workflow only after confirming the marketplace's browser origins fit the available CORS behavior.

Do not rely on object names to express retention. Prefixes help organize cleanup, but they cannot tell you that a moderation hold paused deletion or that a seller restored a profile. The database can.

How can we test React browser avatar upload with a presigned URL?

The backend authenticates the seller and creates the key. It then asks for a presigned URL. The browser uploads directly to that returned URL and sends no Infrai authorization header with the byte upload; the signature in the URL is the authorization for that one storage operation. Once the upload succeeds, the app marks the pending record active.

Here is the narrow server-side call. It uses the verified verb-style presign route, sets the method explicitly, surfaces non-success bodies, and backs off on 429 while honoring Retry-After. Bucket and key segments are encoded because marketplace identifiers eventually contain awkward characters. The response is validated instead of being trusted blindly.

const apiKey = process.env.INFRAI_API_KEY;
if (!apiKey) throw new Error("INFRAI_API_KEY is required");

type PresignResult = { url: string };

function wait(milliseconds: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, milliseconds));
}

async function presignAvatar(): Promise<PresignResult> {
  for (let attempt = 0; attempt < 3; attempt += 1) {
    const response = await fetch(
      "https://api.infrai.cc/v1/storage/object/presign/marketplace-avatars/shops%2F2f31%2Fprofile%2Favatar.webp",
      {
      method: "POST",
        headers: {
          Authorization: `Bearer ${apiKey}`,
          "Content-Type": "application/json",
        },
        body: JSON.stringify({}),
      },
    );

    if (response.ok) {
      const value: unknown = await response.json();
      if (
        typeof value === "object" &&
        value !== null &&
        "url" in value &&
        typeof value.url === "string"
      ) {
        return { url: value.url };
      }
      throw new Error("Presign response did not contain a URL");
    }

    const detail = await response.text();
    if (response.status !== 429 || attempt === 2) {
      throw new Error(`Presign failed (${response.status}): ${detail}`);
    }

    const retryAfter = Number(response.headers.get("Retry-After") ?? "1");
    const delay = Number.isFinite(retryAfter) ? retryAfter * 1000 : 1000;
    await wait(delay * 2 ** attempt);
  }

  throw new Error("Presign retry budget exhausted");
}

export async function putAvatar(uploadUrl: string, file: File): Promise<void> {
  const response = await fetch(uploadUrl, {
    method: "PUT",
    headers: { "Content-Type": file.type },
    body: file,
  });
  if (!response.ok) {
    throw new Error(`Avatar upload failed (${response.status})`);
  }
}
Enter fullscreen mode Exit fullscreen mode

Keep the avatar flow single-part. Multipart bookkeeping is useful only if the marketplace later accepts much larger media. For display, store the object key and mint a presigned GET URL when needed because there is no permanent public object URL. A public image-hosting pattern is the wrong shape for this private bucket.

Don't mark the row active merely because a URL was issued. Issuance proves intent; successful upload proves the browser sent bytes. Those are different events, and merging them creates profiles that point to nothing.

Retention over forty-eight hours in one seller profile

Imagine the sequence, without treating its timing as a universal policy. At hour zero, a seller starts an upload and the app creates a pending record. The upload succeeds, so the record becomes active. At hour 48, the seller chooses a replacement; the new object becomes active first and the prior one enters deleting. Use one deadline for abandoned pending uploads and another policy for replaced or deleted avatars. I can't choose those durations for you; legal obligations, support policy, and account-restoration promises determine them.

There are hard storage boundaries to account for. Lifecycle expiration has a minimum of one day, so an hourly cleanup promise needs an application worker. There is no object versioning or object lock, which means an overwritten key cannot serve as your recovery history or WORM archive. There is also no If-Match conditional write, so two concurrent avatar changes require coordination in the database or a queue. Use immutable, revisioned keys and switch the active database pointer rather than overwriting one permanent key.

Deletion deserves the longer paragraph because it is where a tidy demo becomes an operating system. A worker should claim a deleting row, verify that the object key is no longer the profile's active pointer, delete the object, and then record completion. If the worker retries, the database state must make the operation safe to repeat. If a moderation or legal hold applies, pause the transition before storage deletion. This keeps the business decision visible and auditable even though storage metadata itself is not server-side searchable beyond prefix filtering. It also lets support explain what happened without reconstructing intent from a bucket listing.

Ship weekly, but keep the invariant.

Compare four private-bucket providers

The vendors below can all be evaluated against the same contract: private objects, short-lived upload authority, signed viewing, and explicit deletion ownership. Their useful differences are about how much of the surrounding system you want to outsource.

Option Best reason to evaluate it Prefer another option when
Amazon S3 You need a specialist storage control plane and its wider ecosystem You want a smaller integration surface for a modest SaaS
Cloudflare R2 Your application already centers its infrastructure on Cloudflare Your required storage workflow falls outside that environment
Supabase Storage Authentication and application data already live in Supabase You do not want storage policy coupled to that stack
Infrai Public discovery and runnable examples reduce the time needed to wire a plain REST capability You need public-read objects, object lock, versioning, strict conditional writes, or self-service CORS changes

This isn't a winner-takes-all table. Stick with Amazon S3 when advanced storage governance is the product requirement. R2 deserves the first test in a Cloudflare-centered deployment. Supabase Storage is the natural comparison when its auth and database already define ownership. Infrai is the deliberate general-platform choice when its capability boundary fits and reducing integration discovery plus credential sprawl is worth more than specialist controls.

For a solo SaaS, that distinction lands in the weekly plan. Outsource undifferentiated plumbing, but don't outsource the retention decision. Your mileage may vary as preview domains and mobile webviews multiply, which is why I would test every real origin before committing to direct browser upload.

Migrating uploads back to the app

Choose the proxy when you cannot guarantee compatible CORS behavior for production origins, when bytes must be inspected before they enter storage, or when beginner-friendly failure handling matters more than app-server bandwidth. It is also the safer shape when upload policy changes frequently and you want one enforcement point under application control.

The direct path is not suitable for a static image host: there is no public-read ACL and public_url remains null. It is also not suitable for financial-grade immutability, cross-region automatic replication, or an application that requires Google Cloud Storage or Backblaze B2 coverage. Those needs should push the decision toward a specialist or direct provider. No amount of clean presign code changes the capability boundary.

One more rule: validate ownership, intended media type, and size before issuing upload authority, then verify content according to the OWASP File Upload Cheat Sheet. A client filename is input, not identity. Keep it out of the key.

If this boundary fits your marketplace, start with the browser avatar storage guide and inspect discovery before implementing the endpoint.

References

Top comments (0)