DEV Community

Keria
Keria

Posted on

How to Upload Direct Images to Object Storage Using Browser JavaScript and Presigned URLs

Short answer: use a server-issued, short-lived presigned URL for each tenant-scoped object, then upload the image directly from browser JavaScript while the application server handles identity and completion.

A direct browser upload is the right shape for large delivery photos and scanned documents: the application authorizes a short-lived object-storage handoff, then the browser sends the bytes to storage. The important trade-off is tenant isolation. A fast upload that lets one depot write into another tenant's namespace is a security incident, not a performance win.

The implementation below keeps the application server in the control path for identity and policy, but out of the byte path. It uses a generic signing endpoint so the storage provider can change later. The browser receives one constrained upload target, sends one file, and then tells the application which object was completed.

Keep the URL disposable.

The decision: authorize a handoff, not a storage address

Treat the signed URL as a capability. Whoever holds it may be able to write a particular object until it expires, so the server must create it only after authenticating the user and resolving the user's tenant. Do not accept a client-supplied object key as an authority signal. A request saying tenantId=blue-fleet is still just input.

For a logistics portal, the policy input might be a depot, a shipment, and an upload purpose such as delivery-proof. The server should derive the object key from its own records, for example tenant-42/shipments/8841/proof/<random-id>.jpg. That key is an implementation detail returned to the browser, not a path the browser gets to choose freely.

The key is a policy result.

There is a useful boundary here. The application handles authentication, authorization, metadata, and audit events. Object storage handles the large body. A 5 MiB avatar and a 500 MiB warehouse video can use the same policy boundary while taking very different upload paths; do not make the UI's progress bar your security model.

How can you upload direct images to object storage using browser JavaScript?

Return only the fields the upload needs: an opaque object key, an upload URL, an expiry time, and any required headers. Keep the response small. The server should validate the file's declared size and media type before signing, then repeat validation after completion because client declarations are not proof of content.

Here is a browser-side TypeScript example. The signing endpoint is intentionally generic; its contract is the part your application owns. File is a browser object, and fetch streams the request body through the browser's network stack rather than through your application server.

type UploadGrant = {
  objectKey: string;
  uploadUrl: string;
  expiresAt: string;
  headers?: Record<string, string>;
};

type CompletedUpload = {
  objectKey: string;
  etag?: string;
};

export async function uploadDeliveryProof(file: File): Promise<CompletedUpload> {
  if (!file.type.startsWith("image/")) {
    throw new Error("Choose an image file");
  }

  const grantResponse = await fetch("/api/upload-grants", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    credentials: "include",
    body: JSON.stringify({
      purpose: "delivery-proof",
      size: file.size,
      contentType: file.type
    })
  });

  if (!grantResponse.ok) {
    throw new Error(`Could not authorize upload (${grantResponse.status})`);
  }

  const grant = (await grantResponse.json()) as UploadGrant;
  const uploadResponse = await fetch(grant.uploadUrl, {
    method: "PUT",
    headers: {
      "Content-Type": file.type,
      ...(grant.headers ?? {})
    },
    body: file
  });

  if (!uploadResponse.ok) {
    throw new Error(`Object upload failed (${uploadResponse.status})`);
  }

  const completeResponse = await fetch("/api/uploads/complete", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    credentials: "include",
    body: JSON.stringify({
      objectKey: grant.objectKey,
      etag: uploadResponse.headers.get("ETag") ?? undefined
    })
  });

  if (!completeResponse.ok) {
    throw new Error(`Could not finalize upload (${completeResponse.status})`);
  }

  return (await completeResponse.json()) as CompletedUpload;
}
Enter fullscreen mode Exit fullscreen mode

The PUT is deliberately separate from the two application requests. The browser sends the file to the signed target; the application receives a small completion message. A failed completion call does not prove that no object exists, so the server needs a reconciliation process rather than blindly asking the user to retry.

How do you keep tenants apart?

Use several independent checks. First, derive the tenant from the authenticated session or token. Second, derive the object prefix from a server-side tenant record. Third, make the completion endpoint look up the grant or pending upload by an unguessable identifier and verify that the caller still belongs to the same tenant. Finally, make reads follow the same authorization path; a private object is not private merely because its key is hard to guess.

The object key should carry enough structure for operations, but it should not encode sensitive shipment details. A random component prevents collisions. A server-side upload record can store the tenant, shipment, expected content type, maximum size, creator, expiry, and status. This record is also where an audit trail starts. It gives the completion handler something stronger to check than a string supplied by the browser: the handler can compare the authenticated tenant, the intended shipment, the original grant, and the storage result before attaching an image to a delivery record. If any of those relationships disagree, the object can remain quarantined for cleanup instead of becoming visible through a guessed or replayed path.

That record is the audit spine.

The common pitfall is checking tenant membership only when issuing the URL. Tenants can change, accounts can be disabled, and a URL can remain in a browser tab after the business decision changes. Short expiry limits exposure, while completion-time authorization and object cleanup limit the damage from stale capabilities. Expiry is a control, not a replacement for authorization.

CORS needs the same discipline. Permit only the application origins that actually upload, the methods required by the flow, and response headers that the browser must read. Do not use a permissive origin rule just because a signed URL is present; the URL and the browser policy solve different problems.

What fails after the happy path?

The upload can fail after the server has issued a grant, during the storage request, or after storage has accepted the object but before the completion request reaches the application. Each state should be observable. Log a request identifier, tenant identifier, object identifier, outcome, and reason. Never log the signed URL itself: query strings can contain credentials.

Retries need an idempotency plan. Reusing the same object key can overwrite an earlier object if the storage operation permits it. Generating a new key on every retry avoids that collision but leaves abandoned objects unless a lifecycle rule or reconciler removes them. For delivery evidence, I prefer a pending-upload record plus a unique object key, followed by a server-side verification job that checks size, media type, and ownership before marking the record complete.

Large files change the transport decision. A single request is easy to reason about for modest images. A resumable or multipart protocol is more appropriate when mobile connectivity and file size make restarts common, but its extra parts and completion state must still be tied to the same tenant-scoped upload record. The protocol can change; the authorization boundary should not.

Test the boundary with two tenants, expired grants, altered content types, an over-limit file, a replayed completion request, and a completion request made by a different user. Include a browser test for CORS and a storage test that confirms an object cannot be read through an unrelated tenant's authorized path. These tests cost less than discovering the prefix bug from a customer report.

The operational checklist is short when expressed as decisions: authenticate before signing, derive the key server-side, constrain size and type, keep the grant short-lived, restrict CORS, record pending state, make completion idempotent, verify the object asynchronously when the workflow needs it, and clean up abandoned uploads. The application server should know who may upload; storage should carry the bytes; neither layer should quietly assume the other one did its job.

Sources

Top comments (0)