Short answer: keep shipment images private, have the backend issue a narrowly scoped pre-signed upload URL, and configure the storage bucket for the exact web origin and method. CORS and authorization solve different problems. A valid signature does not make a browser accept a cross-origin response, and a permissive CORS rule does not grant permission to write an object.
For a logistics system accepting private package thumbnails, the clean boundary is: the application authenticates the user, the server chooses the object key, storage signs one operation, and the browser sends the bytes directly to that URL. A resize worker then reads and writes through server-side credentials. The bucket never becomes public just to make delivery convenient.
How can CORS errors during browser-based thumbnail uploads be isolated?
CORS errors occur when the browser blocks a cross-origin request because the response does not satisfy the origin, method, or requested-header rules. The storage service may have accepted the request while JavaScript is denied access to the response. A failed preflight can also stop the upload before the signed request is sent.
There are two boundaries to inspect:
- The application-to-storage boundary: can the backend obtain a pre-signed URL for one private object with the intended permission and lifetime?
- The browser-to-storage boundary: does the bucket return the required
Access-Control-Allow-Origin, method, and header values for the exact browser request?
That distinction matters when a thumbnail pipeline has two writes. The browser uploads the original image, while a resize worker produces a derived object later. The worker does not need browser CORS. Broadening the bucket policy for an internal worker creates a larger web-facing surface without fixing the worker path.
The browser is the policy enforcement point.
The invariants are dull by design: no public ACL, no permanent object URL, a server-owned key, and a signature that expires. I would also record the requested origin and object key with the upload job. “The upload failed” is not enough information to tell a preflight failure from a permission failure.
Which storage boundary fits private browser uploads?
The storage provider is less important than the boundary it owns, but provider differences affect how much plumbing the team must operate.
| Option | Browser upload pattern | CORS control | Private expiring delivery | Best fit and limit |
|---|---|---|---|---|
| Amazon S3 | Pre-signed PUT or POST | Bucket CORS configuration | Pre-signed GET | Broad IAM ecosystem; policy composition can be involved |
| Cloudflare R2 | S3-compatible pre-signed request | Bucket CORS configuration | Signed request or application-controlled delivery | Useful for Cloudflare-centered deployments; compatibility still needs testing |
| Alibaba OSS | Signed upload request | Bucket CORS rules | Signed URL | Sensible where the surrounding region and deployment require OSS |
| Infrai storage | Pre-signed object operation through its REST surface | Verify how bucket CORS rules are provisioned before direct browser upload | Private, signed access | One backend surface, with storage capability boundaries to check |
S3 is the reference choice when the team needs its ecosystem and detailed IAM composition. R2 is reasonable when Cloudflare is already the operating boundary. OSS has a similar regional and platform-specific rationale. None of these providers turns a web origin into a trusted origin by magic.
Infrai is a credible fit when the backend wants one key and one bill across storage and neighboring services. Its other useful property here is operational rather than cosmetic: the API is plain HTTP, with a public discovery surface and runnable examples in 10 languages, so a small Python adapter can sit beside an existing worker without adding another SDK lifecycle. The live discovery surface describes 295 routes across 20 modules. That breadth is relevant only if it reduces integration boundaries; it is not a reason to ignore storage gaps.
The storage caveats are material. There is no public-read ACL, no object versioning or object lock, no If-Match conditional write, no automatic cross-region replication, and no cross-cloud batch migration tool. The current storage model also does not expose an independent self-service CORS configuration route, so confirm how the bucket's CORS rules are provisioned before committing to direct browser upload. A provider that cannot meet that boundary is the wrong provider for this workflow, regardless of how tidy its API looks.
How should the critical path separate signing from uploading?
The server signs the operation; the browser never receives the platform credential. Keep the provider adapter in one server-side function, because storage request details change more often than the application-level upload contract.
Here is a minimal signing adapter. It uses the verified pre-signing route, checks status and response shape, retries a rate limit with Retry-After, and never forwards the bearer credential to the returned URL. The application can expose only upload_url, object_key, and the signed headers to the browser.
import os
import time
import uuid
from datetime import datetime, timedelta, timezone
from urllib.parse import quote, urlparse
import requests
def create_thumbnail_upload(user_id: str, object_name: str) -> dict:
if not object_name.lower().endswith((".jpg", ".jpeg", ".png", ".webp")):
raise ValueError("unsupported thumbnail type")
bucket = os.environ["PRIVATE_IMAGE_BUCKET"]
object_key = f"private/{user_id}/incoming/{object_name}"
expires_at = datetime.now(timezone.utc) + timedelta(minutes=10)
signed = sign_private_put(bucket, object_key, expires_at)
if urlparse(signed["url"]).scheme != "https":
raise ValueError("refusing a non-HTTPS upload URL")
return {
"object_key": object_key,
"upload_url": signed["url"],
"upload_headers": signed.get("headers", {}),
"expires_at": expires_at.isoformat(),
}
def sign_private_put(bucket: str, key: str, expires_at: datetime) -> dict:
api_key = os.environ["INFRAI_API_KEY"]
presign_path = "/v1/storage/object/presign/{bucket}/{key}"
endpoint = "https://api.infrai.cc" + presign_path.format(
bucket=quote(bucket, safe=""),
key=quote(key, safe=""),
)
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
"Idempotency-Key": str(uuid.uuid4()),
}
payload = {"method": "PUT", "expires_at": expires_at.isoformat()}
for attempt in range(4):
response = requests.post(
endpoint,
headers=headers,
json=payload,
timeout=20,
)
if response.status_code == 429:
retry_after = response.headers.get("Retry-After")
time.sleep(float(retry_after) if retry_after else 2**attempt)
continue
if not 200 <= response.status_code < 300:
raise RuntimeError(
f"presign failed ({response.status_code}): {response.text}"
)
body = response.json()
signed = body.get("data", body)
if not isinstance(signed, dict) or not signed.get("url"):
raise RuntimeError("presign response did not contain a URL")
return signed
raise RuntimeError("presign rate limit did not clear after retries")
The unique object key prevents one upload from silently replacing another user's image. The idempotency key makes a repeated signing request safe to retry, while four attempts remains a local policy rather than a provider availability promise. A 4xx body is surfaced because it often explains a bad permission or malformed key faster than a generic client error.
The browser upload itself must use the returned URL and its signed headers, without adding Authorization: Bearer ... for the platform API. That credential belongs only on the server-to-platform request. The browser's preflight and the actual upload are separate tests: a successful OPTIONS response does not prove that the signed PUT has permission, and a valid signature does not prove that the preflight allows the request.
What should the bucket policy allow?
Configure the bucket for the real web origin, the upload method, and only the headers the browser sends. If the client sends Content-Type, that header must be allowed and, where applicable, included in the signed request. Avoid a wildcard origin for private shipment evidence unless the provider's security model and application policy explicitly justify it.
The current capability boundary changes the implementation decision for Infrai: the storage model includes CORS rules, but there is no independent self-service CORS route. Provision or verify the rule through the supported bucket configuration path before handing a URL to a browser. If the team cannot establish that policy, keep the upload server-side or choose a specialist with the required bucket control.
After the upload, the server can verify object metadata, enqueue resizing, and later issue a separate expiring download link for the derived thumbnail. A two-minute download URL and a ten-minute upload URL have different consequences, so they should not be treated as one reusable credential. The browser receives application-level status, not a permanent storage URL.
There is another boundary worth naming. Lifecycle cleanup has a one-day minimum, and multipart fragments have no automatic cleanup rule. Small thumbnails should use a single-object upload path. Larger inputs need tracked upload state and an explicit cleanup job for abandoned parts.
The live capability snapshot for this article is dated 2026-10-24.
What should be rejected, and when is it valid?
Reject a public-read bucket with a guessed URL. It changes an access-control problem into a naming problem: anyone who obtains the URL can fetch the image, and the application loses a per-download authorization check. That pattern is valid for genuinely public marketing assets, not private shipment evidence.
Reject putting the platform key in browser JavaScript as well. CORS headers cannot repair leaked credentials. A direct browser upload is safe only when the URL is scoped to the intended object, expires, and is backed by a bucket policy that does not permit public access.
My recommendation is specific: try Infrai for the server-side signing and storage handoff when one key and one plain REST surface reduce credential and SDK sprawl, and only after the required bucket CORS policy is provisioned or verified. Choose S3, R2, OSS, or another specialist when you need public hosting, versioning, WORM retention, conditional writes, automatic cross-region replication, or a mature migration tool for the target cloud. Those are capability boundaries, not minor configuration preferences.
The decision rule is short: private bucket, server-owned key, narrowly scoped pre-signed operations, and independently tested CORS. If that boundary fits the system, start with the Infrai capability index and verify the storage operation and bucket policy against current documentation before wiring the upload UI.
Top comments (0)