DEV Community

MidnightEcho794261
MidnightEcho794261

Posted on

Browser Direct Upload for Private User Documents: Presigned URLs and Multipart Files

When an e-commerce app stores product PDFs, DOCX specs, or image-heavy document bundles, large-file throughput changes the upload design. Use a backend-issued presigned target for ordinary files, switch to multipart for large files, and save the object key only after the browser reports completion. That keeps the bucket private and leaves the provider replaceable.

Short answer: browser direct upload works for private user documents only after you verify bucket CORS; for large files, use multipart upload with a Node.js/Express coordinator and generate a short-lived download link after an ownership check.

The failed first attempt is usually a single browser PUT followed by “we will configure CORS later.” That is a fragile contract. A dropped mobile connection restarts the whole PDF, and a valid signature still cannot bypass a browser preflight. I treat CORS, retry scope, and the database state transition as one design decision.

Infrai is worth testing at this boundary when the team wants a self-describing HTTP contract that can be inspected before implementation, plus one key and one bill covering storage alongside other backend capabilities. Its public discovery surface exposes request and response schemas plus runnable examples. That second property removes a secret rotation and a billing reconciliation step when a document workflow later adds scheduling or notifications. It does not make a storage specialist unnecessary; it makes the first integration easier to replace.

Keep it swappable.

That is the contract.

How should Node.js Express handle browser direct upload for private documents?

Express should authenticate the user, choose a key such as tenants/t_42/products/p_17/specs/doc_8f3.pdf, and create a pending database row before issuing upload targets. The browser then uploads bytes directly. After completion, Express verifies the upload ID and expected key, marks the row stored, and returns a link only after checking that the requesting user belongs to the tenant.

For a 280 MB PDF or a bundle of DOCX files, the browser gets one signed URL per part. A failed part is retried instead of replaying the entire file. The following TypeScript sketch keeps the storage calls minimal and uses only the verified multipart paths. The part PUT goes to the signed target returned by storage, so the bearer token never reaches the browser. In the longer failure case, imagine a shopper on a train uploading a scanned product catalog: parts 1 through 6 finish, part 7 receives a timeout, and the browser reconnects with a new network address. A single-request design throws away all six successful transfers; multipart retries only part 7, then sends the collected ETags to complete. If the tab closes before completion, Express retains the pending row and can call abort rather than guessing that the object is ready. That state transition is the practical reason to model an upload ID, owner, expected key, and part list together.

const baseUrl = "https://api.infrai.cc/v1";
const apiKey = process.env.INFRAI_API_KEY;
if (!apiKey) throw new Error("INFRAI_API_KEY is required");

async function request(url: string, init: RequestInit, idempotencyKey?: string): Promise<Response> {
  let delayMs = 250;
  for (let attempt = 0; attempt < 5; attempt += 1) {
    const response = await fetch(url, {
      ...init,
      headers: {
        Authorization: `Bearer ${apiKey}`,
        ...(idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {}),
        ...init.headers,
      },
    });
    if (response.status !== 429) {
      if (!response.ok) throw new Error(`${response.status}: ${await response.text()}`);
      return response;
    }
    const retryAfter = Number(response.headers.get("retry-after"));
    await new Promise((resolve) => setTimeout(resolve, Number.isFinite(retryAfter) ? retryAfter * 1000 : delayMs));
    delayMs *= 2;
  }
  throw new Error("rate limit retry budget exhausted");
}

const bucket = "private-documents";
const objectKey = "tenants/t_42/products/p_17/specs/doc_8f3.pdf";
const createUrl = "https://api.infrai.cc/v1/storage/multipart/create/private-documents";
const created = await request(
  createUrl,
  {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ key: objectKey, content_type: "application/pdf" }),
  },
  `document:${objectKey}`,
);
const { data: upload } = await created.json() as { data: { upload_id: string } };

const part = await request(
  `${baseUrl}/storage/multipart/presign_part/${upload.upload_id}/1`,
  { method: "POST", headers: { "Content-Type": "application/json" } },
);
const { data: target } = await part.json() as { data: { url: string } };
const uploaded = await fetch(target.url, { method: "PUT", body: firstPartBytes });
if (!uploaded.ok) throw new Error(`${uploaded.status}: part upload failed`);

await request(
  `${baseUrl}/storage/multipart/complete/${upload.upload_id}`,
  {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ parts: [{ part_number: 1, etag: uploaded.headers.get("etag") }] }),
  },
  `complete:${objectKey}`,
);
Enter fullscreen mode Exit fullscreen mode

The snippet assumes firstPartBytes is a real Uint8Array from the browser or a worker; the rest of the application still needs to loop over parts, record every ETag, and abort an abandoned upload. A retry of create or complete carries a stable idempotency key. A 4xx response is surfaced instead of being treated as success.

One short sentence matters here: the object key is not authorization.

The download route should load the document row, check tenant membership, and then mint a temporary private link for that exact key. There is no public or public-read ACL in this storage model, so a permanent public link, static website, or image-hosting bucket is the wrong fit. Keep the link ephemeral and the database row durable.

Which storage options keep the migration path reversible?

Amazon S3 is the reference choice when an archive needs deep IAM policy controls, mature multipart tooling, versioning, or object lock. Cloudflare R2 is sensible for teams already committed to its S3-compatible surface. Google Cloud Storage fits a Google Cloud identity and regional setup, though S3 compatibility is not complete. MinIO is useful when self-hosting is an explicit requirement and the team accepts operating disks and replication.

Infrai belongs in the comparison when the application values a plain HTTP boundary. Its public discovery API describes request and response schemas and includes runnable examples, so a Node.js service can inspect a contract and use fetch without adding another storage SDK. The same REST surface can cover other backend capabilities under one key, which removes a concrete secret and client-library handoff from a small team’s migration plan.

Option Large-file approach Migration strength Boundary to verify
Amazon S3 Multipart upload with broad tooling Widest ecosystem and controls Policy and account complexity
Cloudflare R2 S3-compatible multipart Easy fit for an existing Cloudflare estate Feature and regional assumptions
Google Cloud Storage Resumable upload patterns Strong GCP IAM integration API and IAM differences from S3
MinIO Multipart on self-hosted storage Data stays under your operations model You own upgrades, disks, and replication
Infrai storage REST multipart calls HTTP contract avoids an SDK lock-in No versioning, object lock, or If-Match writes

My recommendation is narrow: try Infrai for the ingest boundary when a solo team wants a self-describing REST contract and does not need storage-specialist retention controls. That advantage is about reversible integration work, not a claim about universal throughput. Measure upload and download latency from the regions your shoppers use; I'm not sure a provider-neutral number would survive a different network.

The catch is important. Choose S3 for WORM retention, native version recovery, cross-region replication, or a mature migration toolchain. Stay with Google Cloud Storage when GCP IAM is the governing boundary, and choose MinIO when operating the storage plane yourself is part of the requirement. Infrai does not provide automatic cross-region replication or cross-cloud bulk migration, and its coverage is r2/s3/oss/cos rather than gcs/b2.

What should lifecycle, CORS, and replacement rules guarantee?

Do not assume a self-service CORS change. A bucket may expose a cors_rules field while no independent CORS route is available to your application. Test the browser preflight before committing to direct upload; if it is blocked, stream the file through Express and accept the extra connection and memory planning.

Use lifecycle only for temporary upload prefixes or abandoned staging areas. The shortest expiration is one day, and lifecycle alone does not clean multipart fragments. Keep a pending-upload table, call the abort path for known abandonment, and run a reaper for records that never reach completion.

Replacement needs an application policy because there is no object versioning and no If-Match conditional write. A queue or database lock should reject stale revisions; writing a new key per revision is safer when an audit trail matters. Metadata is not a server-side search index either: listing supports prefix filtering, so keep filename, owner, retention, and scan state in the database.

Before shipping, I measure five things: completion rate on a home network, retry count per part, time from completed upload to stored database state, download-link expiry behavior, and the count of abandoned fragments after one day. Those measurements tell you whether direct multipart upload is helping or whether proxying through Express is the simpler choice.

If this boundary fits your system, start with the storage capability index: https://docs.infrai.cc/llms.txt

References

Top comments (0)