DEV Community

EvanShepherd8274
EvanShepherd8274

Posted on

Node.js Logistics: User Documents Reach Object Storage via Direct Browser Upload (Presigned)

Short answer: send an opaque tenant snapshot from the browser to object storage with a narrowly scoped presigned request, then verify it before making it restorable. Put a Node.js relay in the byte path only when acceptance depends on inspecting or transforming those bytes before they land. The deciding issue is not upload convenience. It is where failure may leave data, and which component can recover it.

Choice Failure boundary Access-control burden Delivery burden
Presigned request Storage may hold an object before the app accepts it Authorize before signing; authorize again before restore CORS, expiry, verification, reconciliation
Node.js relay The app can reject while reading the stream Authorize and enforce limits in one server path Streaming, backpressure, timeouts, capacity

My default for logistics backups is the presigned path. Object storage handles the undifferentiated byte transfer; the application owns tenant policy and snapshot state. That is the better revenue-per-hour choice for a solo SaaS shipping weekly. A relay wins only when reading the body is part of the admission decision.

Should a browser upload user documents direct to object storage?

An HTTP success from storage means storage accepted the request. It does not mean the archive is valid, belongs in a restore menu, or is safe to use. Treating those meanings as one event creates the nastiest failure in this design: an object exists, but the application either forgets it or exposes it too early.

Model the workflow first. A server-created snapshot record starts as pending. After the object is present and its stored properties have been checked, it becomes verified. Only the application can promote it to restorable. A restore operation resolves a server-held object key from a tenant-owned record; it never trusts a browser-supplied key or a bucket listing.

This distinction changes retries. Suppose the browser finishes sending snapshot 7f2 and loses connectivity before it reports completion. Storage has the archive, the database still says pending, and the operator cannot tell from the browser which statement is true. Creating another snapshot immediately can duplicate a large archive; marking 7f2 as failed can strand a valid object; allowing restore on the strength of the upload response can expose an archive that has not passed validation. The recovery operation should instead be idempotent: lock or otherwise serialize work for 7f2, look up the server-held key, inspect the expected object, run the same validation, and converge on one state no matter how many times completion is requested. If the object is absent, leave a result that a retry can understand. If it is present but invalid, quarantine or remove it under a documented policy. If it is valid, promote the original record rather than minting another snapshot. This is more application work than a relay appears to need on day one, but it makes the post-upload gap observable and repairable.

I first favor direct upload for delivery simplicity. The state model is what keeps that preference honest.

Small state machines beat clever retries.

Reconciliation is part of the normal path, not an emergency tool. A scheduled worker can revisit old pending records, check for the corresponding object, resume verification, and apply a documented cleanup policy to abandoned data. Log the tenant ID, snapshot ID, object key, actor, transition, and outcome. Do not log a signed URL; its query string carries temporary credentials.

The relay does not remove state. It merely moves the earliest acceptance decision into Node.js. A client can still disconnect after the upstream write, a scanner can fail after reading most of a stream, and a process can stop between storing an object and committing database state. Pick an explicit rollback or quarantine rule for partial work. The trade-off is concrete: direct upload buys a thinner application data path but accepts a recoverable gap between stored and restorable; a relay buys earlier inspection but makes application capacity part of every transfer.

Authorization has two separate moments

An upload capability answers, “May this actor create this particular object now?” A restore capability answers, “May this actor read this accepted snapshot now?” They should not be interchangeable.

For direct intake, authenticate the user before signing. Resolve the tenant on the server, generate the snapshot ID there, and construct an immutable key such as tenants/{tenantId}/snapshots/{snapshotId}. Never sign an arbitrary complete key received from React. Constrain the HTTP method, expiration, and required headers supported by the chosen signing mechanism.

The restore side repeats authorization against current application state. Tenant membership may have changed since upload, and the snapshot may have been quarantined or removed from service. Possession of an upload URL must never imply restore permission. Generate a separate, short-lived read capability after checking the selected restorable record, or stream the download through an authorized server path.

CORS sits outside that authorization model. Browsers enforce CORS for cross-origin requests; it does not make a bucket private and does not constrain non-browser clients. Configure the deployed application origins, upload method, and required request headers. A PUT with non-safelisted headers triggers a preflight, so the storage response must permit the requested method and headers. Scheme, host, and port define an origin, which is why a working localhost test says little about the production origin.

Keep the header contract boring. If a header participates in the signature, React must send the matching value. Adding a custom header can change the preflight and can also invalidate a signed request. Expiration is another ordinary failure: request a fresh intent instead of relaxing the signature. Five minutes might be appropriate for one workload and wrong for another, so set the window from expected archive sizes and client networks, then test transfers that cross it.

Encode the boundary, not the storage SDK

The frontend needs an upload intent, not a vendor response. This TypeScript contract keeps the object key and storage credentials on the server while exposing only what React must execute.

type UploadIntent = {
  snapshotId: string;
  method: "PUT";
  url: string;
  headers: Record<string, string>;
  expiresAt: string;
};

type SnapshotRequest = {
  filename: string;
  contentType: "application/zip";
  size: number;
};

async function createSnapshotIntent(
  actorId: string,
  tenantId: string,
  input: SnapshotRequest,
): Promise<UploadIntent> {
  await requireTenantPermission(actorId, tenantId, "backup:write");
  assertAcceptedSnapshot(input);

  const snapshotId = crypto.randomUUID();
  const objectKey = `tenants/${tenantId}/snapshots/${snapshotId}`;
  const signed = await objectStore.signPut({
    objectKey,
    contentType: input.contentType,
    expiresInSeconds: 300,
  });

  await snapshots.insert({
    snapshotId,
    tenantId,
    objectKey,
    expectedSize: input.size,
    status: "pending",
  });

  return {
    snapshotId,
    method: "PUT",
    url: signed.url,
    headers: signed.headers,
    expiresAt: signed.expiresAt,
  };
}
Enter fullscreen mode Exit fullscreen mode

The 300-second value is an example policy input, not a general limit. The client cannot choose it. The storage adapter also owns differences in signing behavior; the rest of the application owns snapshot policy.

React then performs three visible steps: create intent, transfer bytes, request verification. The final step may return before slow validation work finishes, so the UI should display application state rather than infer readiness from the upload response.

async function submitSnapshot(file: File): Promise<string> {
  const intentResponse = await fetch("/api/snapshot-intents", {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({
      filename: file.name,
      contentType: file.type,
      size: file.size,
    }),
  });

  if (!intentResponse.ok) throw new Error("Could not create snapshot intent");
  const intent = (await intentResponse.json()) as UploadIntent;

  const uploadResponse = await fetch(intent.url, {
    method: intent.method,
    headers: intent.headers,
    body: file,
  });
  if (!uploadResponse.ok) throw new Error("Snapshot transfer failed");

  const verifyResponse = await fetch(
    `/api/snapshot-intents/${intent.snapshotId}/verify`,
    { method: "POST" },
  );
  if (!verifyResponse.ok) throw new Error("Snapshot verification failed");

  return intent.snapshotId;
}
Enter fullscreen mode Exit fullscreen mode

The verification handler retrieves the object key from its own database row, checks tenant permission again, and inspects the stored object before changing state. Duplicate calls must converge on the same result. Tests should cover cross-tenant snapshot IDs, expired signatures, mismatched signed headers, a lost completion call, repeated verification, missing objects, and cleanup racing with verification.

There is a portability catch. “S3-compatible” describes an API family, not identical behavior everywhere. Amazon S3 documents Signature Version 4 presigned URLs. Cloudflare R2 documents an S3-compatible API together with its own compatibility surface. Google Cloud Storage documents V4 signed URLs through its XML API and also provides resumable uploads. Keep signing behind the adapter and run the same contract tests against the service actually deployed. No brand name belongs in the domain model.

When should Node.js carry every byte?

The presigned path has a clear limitation: it cannot reject content based on bytes it has not read before those bytes reach storage. Use the relay when policy must run before untrusted bytes reach durable storage. Examples include mandatory inline scanning, rejecting content based on the stream itself, or transforming an archive into the representation that will be retained. It can also be the simpler delivery for tightly bounded, infrequent files because it avoids bucket CORS and a browser-to-storage completion gap.

That simplicity has a ceiling.

The application now owns request duration, bounded memory, backpressure, slow clients, upstream errors, abort propagation, and concurrent upload capacity. Stream the body; do not collect a backup into one Buffer. Put explicit size and duration limits at each proxy and decide what happens to a partial upstream object.

Multipart and resumable mechanisms help interruption-prone transfers continue without restarting every byte, but they introduce upload identifiers, part or session state, finalization, expiration, and orphan cleanup. Add that machinery after observed network behavior justifies it. Shipping it speculatively spends feature time on storage plumbing.

The acceptance tests should be unpleasant on purpose. Disconnect a slow client. Expire a capability. Stop the verifier between object inspection and the database transition. Attempt a restore from another tenant. Run reconciliation beside cleanup. Those cases reveal the real architecture more clearly than a successful local upload.

My decision rule stays narrow: presign opaque snapshots and verify them out of band; relay only when inline byte inspection is the control you are buying. Both designs can protect tenant backups. The better one is the failure boundary you can explain, test, and operate while still shipping the logistics product every week.

References

Top comments (0)