DEV Community

KiernanBerg3867
KiernanBerg3867

Posted on

Tenant-Isolated Browser Avatars: Node.js CORS Preflight and Signed PUTs Explained

Short answer: a presigned PUT does not bypass the browser's CORS gate. For private avatar uploads, tenant isolation comes first: either configure the bucket's allowed origin before using a direct PUT, or send the bytes through your backend. In this storage service, the bucket model mentions cors_rules, but there is no self-service route to set them, so the backend path is the dependable beginner default.

The failure happens before the file moves

A browser on https://app.example sees an upload target on another origin and applies CORS before it sends the real request. A presigned URL proves that the object store may accept a particular object and method; it does not grant the page permission to make that cross-origin request. A PUT with a non-simple content type, or with extra headers, commonly triggers an OPTIONS preflight. If the response does not expose the requested origin and method, JavaScript reports a CORS error and the upload never starts.

That distinction matters for US and EU tenants. A region label does not change the browser security model, and moving the bucket will not create an Access-Control-Allow-Origin response. Check the origin your users actually load, including scheme and port. http://localhost:3000 and https://app.example are different origins.

It fails early.

The first debugging clue is timing: there is no object to inspect because the policy check failed first. I have learned to look at the Network panel's OPTIONS entry before staring at the storage response. A missing Access-Control-Allow-Methods: PUT, a disallowed Content-Type, or a redirect on the preflight is enough to stop the flow. Your mileage may vary when a framework adds headers automatically, so inspect the exact request rather than copying a production URL into a local test. On one useful trace, the page sent Origin, Access-Control-Request-Method: PUT, and Access-Control-Request-Headers: content-type; that three-line request tells you exactly what the bucket must answer. If the response omits even one permission, the browser blocks the subsequent PUT, regardless of whether the signature itself is valid.

Can a browser direct-upload an avatar to object storage?

Start with an application-level tenant check. The server should authenticate the user, derive a key such as tenant_42/avatars/user_7.png, validate the media type and size, and only then issue a short-lived presigned URL. The client must use that URL without the platform's Authorization header. That header authenticates the presign request; it is not part of the signed object upload.

A direct browser flow is reasonable only when the bucket's CORS policy is already known to allow the app origin, PUT, and the exact headers the browser will request. Keep the request minimal: send the content type you validated, avoid custom headers, and do not let a user choose an arbitrary object key. Tenant prefixes are useful organization, but authorization still belongs in your API.

Here is the smallest server-side presign call. It uses the documented path and keeps the platform key on the server. The retry is bounded and respects Retry-After; the returned URL is intentionally used as a separate request.

type PresignResult = { url: string };

async function presignAvatar(bucket: string, key: string, contentType: string) {
  const apiKey = process.env.INFRAI_API_KEY;
  if (!apiKey) throw new Error("INFRAI_API_KEY is required");
  const path = "/v1/storage/object/presign/{bucket}/{key}"
    .replace("{bucket}", encodeURIComponent(bucket))
    .replace("{key}", encodeURIComponent(key));

  for (let attempt = 0; attempt < 3; attempt += 1) {
    const response = await fetch(
      `${process.env.INFRAI_BASE_URL ?? "https://storage.example.invalid"}${path}`,
      {
        method: "POST",
        headers: {
          Authorization: `Bearer ${apiKey}`,
          "Content-Type": "application/json",
          "Idempotency-Key": `avatar-${key}`,
        },
        body: JSON.stringify({ content_type: contentType, acl: "private" }),
      },
    );

    if (response.status === 429) {
      const retryAfter = Number(response.headers.get("Retry-After") ?? "1");
      await new Promise((resolve) => setTimeout(resolve, Math.min(retryAfter * 1000, 8000)));
      continue;
    }

    if (!response.ok) {
      throw new Error(`Presign failed (${response.status}): ${await response.text()}`);
    }

    return (await response.json()) as PresignResult;
  }

  throw new Error("Presign rate limit persisted after retries");
}

async function uploadWithSignedUrl(url: string, file: Blob, contentType: string) {
  const response = await fetch(url, {
    method: "PUT",
    headers: { "Content-Type": contentType },
    body: file,
  });
  if (!response.ok) throw new Error(`Upload failed (${response.status})`);
}
Enter fullscreen mode Exit fullscreen mode

The presign endpoint is the only platform call in this example. The second fetch goes to the storage URL returned by it, so adding the platform bearer token there would be both unnecessary and incorrect.

How do the main storage choices handle this boundary?

The hard part is not picking a fashionable object store. It is deciding where cross-origin policy and tenant authorization live.

Option Tenant isolation control Browser direct upload Practical trade-off
Amazon S3 IAM, bucket policies, and per-prefix conditions Yes, after explicit CORS configuration Deep controls, but more policy surface to operate
Cloudflare R2 API tokens and bucket CORS rules Yes, after CORS configuration S3-compatible API with Cloudflare-specific account choices
MinIO Policies and credentials you operate Yes, when your deployment exposes matching CORS Maximum deployment control; you own upgrades and networking
Infrai storage Private/signed access and backend-issued URLs Only where a matching bucket CORS policy is available One key and one bill across backend capabilities, plus a plain REST API with no SDK requirement

Infrai's useful fit here is operational consistency: one REST API and credential set can cover storage alongside other backend services, while discovery documents the available capabilities. That does not remove browser policy. In this scenario, the platform's lack of a self-service CORS-setting route makes a backend proxy or same-origin upload the safer choice for a first release.

The catches you should accept up front

This storage model is not a public image host. It has no public or public-read ACL, and public_url is always null, so permanent public links and static-site hosting are a mismatch. It also has no object versioning or object lock; an accidental overwrite is not recoverable through version history. There is no If-Match conditional write, so strict concurrent-edit protection belongs in a queue or database.

Lifecycle expiration is measured in days, with one day as the shortest setting, and multipart fragments have no automatic cleanup rule. Metadata is not server-searchable; listing filters by prefix. Cross-region automatic replication and bulk cross-cloud migration are absent, and the vendor coverage is r2/s3/oss/cos rather than gcs/b2. Finally, trial credit cannot pay for persistent writes.

Those are capability boundaries, not upload failures. Choose S3 when IAM conditions, versioning, or replication are requirements. Choose R2 when Cloudflare placement is the priority. Choose MinIO when you need to run the entire data plane yourself. Stick with a backend-mediated flow when you cannot prove the browser's preflight policy.

A small test plan before shipping

Create one test tenant in each deployment region and record the exact origin, key prefix, content type, and maximum size. In a clean browser profile, capture the OPTIONS request, then the signed PUT, and verify that a tenant cannot obtain a URL for another tenant's prefix. Test a rejected MIME type and an oversized file before issuing a URL, not after bytes have left the browser.

Measure preflight success rate, presign latency, upload completion, and cross-tenant authorization denials. I am not sure a direct flow is worth the extra moving parts for every product; if the upload volume is modest, a same-origin backend endpoint can be easier to reason about and monitor. Revisit the decision with real traffic, especially if US/EU origin patterns change.

References

Top comments (0)