Dev.to Security πŸ” Cybersecurity πŸ‘ 0 πŸ“– 7 min read

Tenant Image Upload Retention: Presigned URLs and Proxy Backends in Node.js

Short answer: for a B2B SaaS that stores product images and later creates tenant-scoped exports, let the browser upload directly to private object storage with a short-lived presigned URL. Keep the proxy backend as a del

Short answer: for a B2B SaaS that stores product images and later creates tenant-scoped exports, let the browser upload directly to private object storage with a short-lived presigned URL. Keep the proxy backend as a deliberate control point for exceptional files, not as the default byte path. The deciding factor is retention: the upload method must make ownership, expiry, deletion, and export isolation easy to prove.

That choice leaves more of a one-person team's week for product work. It also changes where the hard problems live. A proxy concentrates policy and bytes in one process; a signed direct upload moves bytes out of the process and makes policy explicit in the session your API issues.

The small decision matrix I use

Concern Browser to storage with a presigned URL Browser to proxy backend
App bandwidth File bytes bypass the app server Every byte crosses the app server
Latency One upload hop after signing Browser, app, then storage
Security boundary Short-lived capability plus private bucket Authenticated request plus server-held storage credentials
Retention work Delete by tenant-prefixed key and lifecycle rule Same storage work, plus proxy cleanup paths
Best fit Normal images and large media Inline inspection, transformation, or strict synchronous policy

For a normal image, direct upload is the least complex option that still gives the backend authority. The API authenticates the user, selects a tenant-scoped key, and issues a presigned URL. The browser never receives a storage secret and cannot choose an arbitrary tenant path.

I would still record an upload session in the database before returning the URL. Store the tenant ID, object key, expected content type, byte limit, and an expiry timestamp. A completed request then marks the session ready for processing. An abandoned session becomes a deletion job, rather than an orphan that quietly survives a trial account.

How should a Node.js SaaS compare presigned URLs and proxy uploads for retention?

Retention is not a cron expression pasted onto a bucket. It is an ownership invariant: every object has one tenant, one purpose, and a known deletion event. Product images might be current, replaced, or attached to an audit record. An export is different: it is a derived snapshot with a shorter useful life.

Boring, but critical.

Use keys that encode an immutable tenant identifier and a random upload ID, for example tenants/t_42/images/01J.../original.webp. Do not use the user-supplied filename as the key. Keep the friendly filename in your database and set download metadata separately. This makes replacement an insert-plus-delete operation instead of an overwrite race.

The storage API can support the narrow actions the application needs. A server can request a presigned operation through /v1/storage/object/presign/{bucket}/{key}, verify an object with /v1/storage/object/head/{bucket}/{key}, and set download metadata with /v1/storage/object/set_metadata/{bucket}/{key}. Those three calls are enough for a small workflow; a route list is not a retention strategy.

Here is the shape of the signing endpoint in TypeScript. The storage client is intentionally abstract, so the policy remains testable without a vendor SDK.

type UploadRequest = {
  tenantId: string;
  userId: string;
  filename: string;
  contentType: string;
  bytes: number;
};

const allowedTypes = new Set(["image/jpeg", "image/png", "image/webp"]);

async function createImageUpload(input: UploadRequest) {
  if (!allowedTypes.has(input.contentType) || input.bytes > 10_000_000) {
    throw new Error("image policy rejected");
  }

  const uploadId = crypto.randomUUID();
  const key = `tenants/${input.tenantId}/images/${uploadId}/original`;
  await uploads.insert({
    uploadId,
    tenantId: input.tenantId,
    userId: input.userId,
    key,
    expectedBytes: input.bytes,
    expiresAt: new Date(Date.now() + 10 * 60_000),
  });

  const url = await storage.presign({
    method: "PUT",
    bucket: "private-assets",
    key,
    contentType: input.contentType,
    expiresInSeconds: 600,
  });

  return { uploadId, key, url };
}

After the browser sends the PUT, the backend should perform a HEAD check and compare the recorded size and type. Do not trust a client-side success callback. A queue can then generate thumbnails and exports. The export worker should write to a separate prefix such as tenants/t_42/exports/export_2026-09-03.csv, attach an expiry, and return a fresh signed download link only after checking the requesting tenant.

One bug in my first version was conceptual, not cryptographic: I deleted the database row but left the object. The UI looked clean while storage retention kept growing, and a support export could still find bytes that the product insisted were gone. I traced the path from the delete button to the worker queue and found that the row deletion committed before the object-delete job was even enqueued; a transient queue failure meant there was no durable record of the missing cleanup. The repair was a reconciliation job that samples database keys, checks storage metadata, and deletes objects whose upload session expired or whose tenant no longer exists. It compares the object generation recorded in the ledger, so a late cleanup cannot remove a replacement that reused a logical filename. The job runs with a dry-run mode, emits counts and a bounded sample of keys, and only enables deletion after those counts match an operator-approved run. This is extra code, but it turns a hopeful retention promise into something I can test after a schema migration or a queue outage.

Where direct uploads fail in real systems

Presigned URLs are capabilities, not permissions. Anyone who obtains one can use it until it expires, so keep the lifetime short and bind the signature to the intended method, key, and content type. Your API still needs normal authentication and authorization before signing.

Browsers also enforce CORS before a cross-origin upload. Test the exact origin, method, and headers in a staging browser; a successful server-side request does not prove that a browser request will pass preflight. Limit the allowed headers to what the upload actually sends.

Deletion has a race too. If a user replaces an image while a thumbnail job is running, a late worker must not recreate a deleted variant. Put a generation or upload ID in the job payload, and have the worker check that the generation is still current before writing derived objects.

Proxying is the better tool when bytes must be inspected before storage: malware scanning, content transformation that must happen synchronously, or a policy that cannot tolerate an untrusted object appearing even briefly. It is also a reasonable fallback for clients that cannot satisfy your CORS contract. The catch is operational load: request limits, streaming backpressure, retries, and timeout settings now sit on your application path.

What should you measure before committing to a path?

Measure the workflow, not just upload speed. Track time from sign request to first byte, completion rate by file size, abandoned sessions, expired links, deletion lag, and export authorization failures. A direct path can have lower app latency while still producing a poor user experience if the UI cannot resume a dropped connection.

Run a small test matrix: a 200 KB image, a 9 MB image, a revoked session, a duplicate upload, a tenant mismatch, and an expired download link. Assert that the object key never escapes its tenant prefix, that a second tenant cannot HEAD it, and that cleanup removes both originals and derivatives. Keep these tests in CI with a storage emulator or a disposable test bucket.

Watch your revenue-per-hour lens. If proxying consumes enough CPU and egress to delay a feature, move ordinary images to direct upload. If investigating a cross-tenant deletion would cost a week, invest in the database ledger and reconciliation before polishing progress bars. Ship weekly, and outsource the undifferentiated byte transport to storage while retaining policy in code you own.

I’m not sure one threshold fits every product; your mileage may vary with mobile networks, regulated data, and export size. Re-measure after a change in retention policy or traffic shape.

When is a proxy backend the better choice?

Stick with a proxy when the server must read every byte before accepting it, when your browser clients cannot use the required CORS headers, or when a compliance review demands a single ingress log. A proxy can stream to storage without buffering the whole file, but it still needs bounded body sizes, cancellation handling, and idempotency keys.

For the tenant-image scenario, that is the runner-up. Direct signed upload handles the common path; a narrow proxy endpoint handles quarantined or exceptional content. Both paths should create the same upload-session record and feed the same verification and deletion jobs. Consistency here matters more than choosing one transport everywhere.

The final rule is boring and useful: choose the path that makes a deleted tenant leave no bytes behind, then prove it with a test. Latency and infrastructure spend follow from that discipline.

Further reading

πŸ“° Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.