DEV Community

RiftG84
RiftG84

Posted on

Property Receipts: Large Files, Browser Direct Uploads — Node.js Presigned Multipart Parts

Short answer: for a property-management receipt, keep the browser on a direct upload path, sign one multipart plan in Node.js, and make retention state explicit before you call complete.

The original receipt is an audit record. A thumbnail or extracted text is not a substitute. That changes the design: the upload service owns authorization and state, while object storage receives the large file. The browser should never receive a long-lived storage credential.

Keep the original.

The retention decision comes before the upload

Start with a receipt record in your application database. It needs an owner, property identifier, content type, expected size, retention deadline, and an upload status such as initiated, complete, aborted, or expired. Generate an object key from an internal receipt ID, not from the filename. Filenames are user input and are poor identifiers.

For a browser direct upload, the control flow is short:

  1. The browser asks Node.js to start an upload for a receipt.
  2. Node.js creates a multipart upload and returns short-lived presigned URLs for numbered parts.
  3. The browser sends each part directly to storage and records the returned ETag.
  4. Node.js validates the part list, completes the upload, and marks the receipt complete.
  5. A retention job deletes expired objects and the corresponding database row only after the policy allows deletion.

Do not mark a receipt complete when the first part arrives. A multipart upload is an in-progress storage resource until it is completed or aborted; AWS documents both termination paths in its multipart overview. That unfinished state is the thing your cleanup process must see.

How should Node.js handle browser direct upload, presigned parts, complete, and abort?

The following control-plane example uses the S3 API shape, so the same application boundary can target S3-compatible storage. It signs one part at a time in this sample to keep the API response bounded. In production, sign a bounded window (for example, 8 or 16 parts) and issue another window after the browser reports progress.

import {
  AbortMultipartUploadCommand,
  CompleteMultipartUploadCommand,
  CreateMultipartUploadCommand,
  S3Client,
  type CompletedPart,
} from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";

const bucket = process.env.RECEIPT_BUCKET!;
const s3 = new S3Client({ region: process.env.AWS_REGION ?? "us-east-1" });

type ReceiptUpload = {
  receiptId: string;
  key: string;
  uploadId: string;
  partSize: number;
};

export async function beginReceiptUpload(receiptId: string, contentType: string): Promise<ReceiptUpload> {
  const key = `receipts/${receiptId}/original`;
  const result = await s3.send(new CreateMultipartUploadCommand({
    Bucket: bucket,
    Key: key,
    ContentType: contentType,
    Metadata: { receiptId },
  }));
  if (!result.UploadId) throw new Error("storage did not return an upload id");
  return { receiptId, key, uploadId: result.UploadId, partSize: 8 * 1024 * 1024 };
}

export async function signReceiptPart(upload: ReceiptUpload, partNumber: number): Promise<string> {
  if (!Number.isInteger(partNumber) || partNumber < 1) throw new Error("invalid part number");
  return getSignedUrl(s3, new UploadPartCommand({
    Bucket: bucket,
    Key: upload.key,
    UploadId: upload.uploadId,
    PartNumber: partNumber,
  }), { expiresIn: 900 });
}

export async function finishReceiptUpload(upload: ReceiptUpload, parts: CompletedPart[]) {
  const ordered = [...parts].sort((a, b) => (a.PartNumber ?? 0) - (b.PartNumber ?? 0));
  if (!ordered.length || ordered.some((part) => !part.PartNumber || !part.ETag)) {
    throw new Error("a complete part list is required");
  }
  return s3.send(new CompleteMultipartUploadCommand({
    Bucket: bucket,
    Key: upload.key,
    UploadId: upload.uploadId,
    MultipartUpload: { Parts: ordered },
  }));
}

export async function cancelReceiptUpload(upload: ReceiptUpload) {
  return s3.send(new AbortMultipartUploadCommand({
    Bucket: bucket,
    Key: upload.key,
    UploadId: upload.uploadId,
  }));
}
Enter fullscreen mode Exit fullscreen mode

The browser calculates the byte range itself and sends the ETag back to Node.js. It should retry a failed part with the same part number, but it must not silently replace the file with a new upload ID. A new ID means a new database state and a new cleanup obligation.

export async function putPart(file: File, url: string, partNumber: number, partSize: number) {
  const start = (partNumber - 1) * partSize;
  const body = file.slice(start, Math.min(start + partSize, file.size));
  const response = await fetch(url, { method: "PUT", body });
  if (!response.ok) throw new Error(`part ${partNumber} failed: ${response.status}`);
  const etag = response.headers.get("ETag");
  if (!etag) throw new Error(`part ${partNumber} did not return an ETag`);
  return { PartNumber: partNumber, ETag: etag };
}
Enter fullscreen mode Exit fullscreen mode

The API that wraps these functions should check the authenticated user against the property and receipt before signing anything. It should also cap the declared size, restrict content types, and bind the object key to the receipt ID. Those checks belong in Node.js because a presigned URL is an authorization artifact, not an input-validation layer.

What fails in real receipt pipelines?

The first failure mode is a tab that disappears after 37 of 120 parts. Storage still has an incomplete upload, and a receipt row that says only initiated tells an operator very little about what happened next. Record the upload ID, expected part count, byte total, user, property, and last activity timestamp in the database. On every signed-part request, update that timestamp; on completion, keep the final object key and checksum metadata alongside the audit record. Then run a scheduled reaper that aborts uploads past an inactivity window, records the reason, and emits a metric grouped by property rather than by anonymous object key. The window is a policy choice; your mileage may vary when users upload over a mobile connection. A 15-minute timeout that works for office Ethernet can punish a 4G tenant portal, so test with the slowest connection your support team actually sees. The useful invariant is simpler: an abandoned session has a bounded lifetime and one visible owner.

The second is a successful PUT followed by a lost client response. The part may exist even though the browser thinks it failed. Keep the part number idempotent, ask the control plane for the current session, and retry that part before creating another multipart upload. Completion must use the exact part numbers and ETag values returned by storage.

The third is declaring success before the original is durable enough for your audit workflow. Write the database transition only after the complete call returns, then enqueue text extraction or thumbnail work from that committed state. Derived artifacts can be rebuilt; the original receipt should not depend on an asynchronous consumer finishing first.

I also separate user cancellation from policy deletion. Cancellation calls abort immediately and leaves a trace. Retention deletion runs only for a complete receipt whose deadline has passed. This distinction makes an audit report explainable six months later.

A practical retention and cost checklist

Choose part size from the failure domain you can tolerate. Smaller parts retry cheaply but create more signing and bookkeeping traffic; larger parts reduce request count but repeat more bytes after a transient failure. Keep the value in configuration and store it with the upload session so a resumed browser uses the same arithmetic.

Measure the control plane separately from storage transfer: time to create, time to sign, part retry rate, completion latency, and age of the oldest incomplete upload. Alert on age and count, not only on HTTP errors. A quiet leak can cost money without producing a failed request. Storage providers publish different request and retention terms, so compare the policy and lifecycle controls you actually need rather than a headline per-gigabyte number.

Test the ugly paths. Kill the browser halfway through, reorder parts, send a stale upload ID, exceed the declared size, and call complete twice. In each case, the database should land in one of a small set of states, and a later cleanup run should have a deterministic action. Log receipt ID, upload ID, part number, and correlation ID; never log the presigned URL itself.

The catch is that direct multipart upload adds a control plane you must operate. It is not suitable when files are tiny, retention is informal, or you cannot run a cleanup job; a single authenticated upload endpoint is easier there. Stick with a simpler path for those cases. For large originals that must remain auditable, explicit complete-or-abort state is the feature that protects the record.

References

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

The line that landed for me is 'keep the original' — a receipt is an audit record, not a file, and that one sentence reframes the whole design. The failure mode I would have missed is the second one: a PUT that succeeded while the browser thinks it failed, because the response was lost. Most people would just retry the part and move on, but checking the ETag is what keeps the part list honest. One question: when a tab disappears after 37 of 120 parts, what does the operator actually see first — is it the orphaned multipart upload, or the receipt stuck in initiated? I am curious which signal you would surface in the dashboard so a human notices before the retention job does.