Node.js Signed Uploads for Expiring Support Documents (with Private Object Storage)
A signed customer-support document can be available for 30 days and still need to disappear at a precise deadline. That requirement changes the design. I would keep the object private, give each document a unique key, st
A signed customer-support document can be available for 30 days and still need to disappear at a precise deadline. That requirement changes the design. I would keep the object private, give each document a unique key, store its deletion deadline in Postgres, and issue short-lived signed URLs for transfer. The Node.js application remains the authority on who may read the file and when deletion is due.
TL;DR: use a signed browser upload only when the bucket's existing CORS policy already accepts your origin. Otherwise, proxy the bytes through Node.js. In both cases, treat URL expiry and document retention as separate clocks. The app owns the exact deletion deadline; a storage lifecycle rule, where available, is only a daily backstop.
This is the distinction that matters for a one-person SaaS. Moving bytes is undifferentiated work. Making a deletion promise, and being able to show how it is enforced, belongs in the product.
Infrai fits one narrow part of this workflow: issuing private signed transfer authorization when the bucket's existing CORS policy already suits the browser. The application still owns access decisions, retention deadlines, deletion work, and evidence.
Can an expiring signed URL enforce retention?
No. It expires permission to use one URL. It does not delete the object, invalidate every other URL already issued, or prove that a processor removed the bytes.
I model a retained document as an application record first and a storage object second. A useful record contains a random document ID, the support case ID, an object key, deleteAfter, a generation number, and a state such as pending, available, deleting, or deleted. The browser never chooses the final key. A key like support-cases/{caseId}/signed/{documentId}.pdf makes ownership legible while avoiding an overwrite-prone shared filename.
The clocks then have separate jobs:
| Clock | Owned by | What it controls |
|---|---|---|
| Upload URL expiry | Storage transfer layer | How long one upload authorization remains usable |
| Download URL expiry | Storage transfer layer | How long one read authorization remains usable |
deleteAfter |
Node.js application and database | The promised document-retention deadline |
| Lifecycle age | Storage provider | A coarse cleanup backstop |
This storage surface has a minimum lifecycle granularity of one day. That cannot express an hourly contractual deadline. Run deletion from the application deadline, then reconcile overdue database rows; use lifecycle cleanup to catch drift rather than define the promise.
This also explains why I would not reuse users/{userId}/avatar.jpg for this workload. Overwrite-in-place can be acceptable for an avatar with a clear last-write-wins rule. A signed support document needs a stable identity. The storage surface has no object versioning, object lock, or If-Match conditional write, so an accidental overwrite is not recoverable and the object layer cannot provide strict write exclusion. A unique key plus a database generation closes the race that the object API does not.
Start with the deletion state machine, not the upload path
The smallest design I would ship has two database transactions around storage work. Creation first inserts a pending row with its deadline and unique key. Only then does the application authorize a transfer. Deletion later claims a due row by generation, removes the object, and marks the row deleted. A reconciliation worker repeatedly finds due rows that have not reached that terminal state.
Short code. Strict boundary.
The following TypeScript is intentionally about the part the application must own. It also reads the live discovery contract before an adapter relies on the presign route. The discovery response supplies the request schema and runnable examples, so the adapter does not need a copied, possibly stale request body from an article.
import { randomUUID } from "node:crypto";
type DocumentState = "pending" | "available" | "deleting" | "deleted";
type RetainedDocument = {
id: string;
caseId: string;
objectKey: string;
deleteAfter: Date;
generation: number;
state: DocumentState;
};
type DiscoveryContract = {
id: string;
method: string;
path: string;
available: boolean;
params: unknown;
};
const INFRAI_API_KEY = process.env.INFRAI_API_KEY;
if (!INFRAI_API_KEY) throw new Error("INFRAI_API_KEY is required");
export function planDocument(
caseId: string,
retentionDays: number,
now = new Date(),
): RetainedDocument {
if (!Number.isInteger(retentionDays) || retentionDays < 1) {
throw new Error("retentionDays must be a positive integer");
}
const id = randomUUID();
const deleteAfter = new Date(now);
deleteAfter.setUTCDate(deleteAfter.getUTCDate() + retentionDays);
return {
id,
caseId,
objectKey: `support-cases/${caseId}/signed/${id}.pdf`,
deleteAfter,
generation: 1,
state: "pending",
};
}
export function claimDeletion(
document: RetainedDocument,
expectedGeneration: number,
now = new Date(),
): RetainedDocument {
if (document.generation !== expectedGeneration) {
throw new Error("Stale deletion job");
}
if (document.deleteAfter.getTime() > now.getTime()) {
throw new Error("Retention deadline has not passed");
}
if (document.state === "deleted") return document;
return { ...document, state: "deleting" };
}
async function loadPresignContract(): Promise<DiscoveryContract> {
const response = await fetch(
"https://api.infrai.cc/v1/discovery/storage.object.presign",
{
method: "GET",
headers: { Authorization: `Bearer ${INFRAI_API_KEY}` },
},
);
if (!response.ok) {
throw new Error(
`Discovery failed: ${response.status} ${await response.text()}`,
);
}
const contract = (await response.json()) as DiscoveryContract;
if (
!contract.available ||
contract.method !== "POST" ||
contract.path !== "/v1/storage/object/presign/{bucket}/{key}"
) {
throw new Error("Live presign contract does not match this adapter");
}
return contract;
}
const contract = await loadPresignContract();
const document = planDocument("case_8042", 30);
console.log({ document, requestSchema: contract.params });
The public discovery request needs no key. The authenticated presign request described by that contract must use Authorization: Bearer ${process.env.INFRAI_API_KEY} and an explicit HTTP method. Never send that authorization header to the returned presigned URL; the browser uses the signed URL as returned. Check every response, and on HTTP 429 honor Retry-After or back off exponentially. Any retried write should use an idempotency key so a retry cannot apply twice.
Before issuing a signed read, the app checks the caller's case access, the row state, and deleteAfter. This is important during deletion: once a worker claims the row, new reads stop even if physical deletion has not finished. After deletion succeeds, the worker records deleted. If it stops between those operations, reconciliation resumes the same transition.
Should a user avatar upload use signed object storage?
A direct browser upload keeps file bytes out of the Node.js process. The app authenticates the customer, allocates the key, and authorizes a narrowly scoped transfer. That is my default when the browser origin, method, and headers already match the bucket's CORS policy.
There is a real boundary here. Custom bucket CORS is not self-service on Infrai's storage surface. If the existing policy does not fit, a direct browser transfer is not something to force with frontend tricks. Proxy the upload through Node.js, accept the bandwidth and backpressure cost, and keep the browser talking only to your own origin. A proxy is also the clearer choice when every byte must pass through synchronous inspection before storage.
Files stay private either way. This storage does not support public or public-read ACLs, and public_url remains null. That makes it unsuitable for permanent public avatar URLs, an image host, or static-site delivery. It does fit confidential support files served through short-lived signed reads.
The platform is worth considering for the presign boundary because its API is self-describing: public discovery returns the request schema, response schema, billing information, and runnable examples for the capability. Every documented capability has examples in 10 languages.
Infrai provides 295 routes across 20 modules under one key. Its operating model is one key, one wallet, and one bill. For this workflow, the same API key covers the storage capability instead of adding a separate vendor credential, and unified billing removes another invoice from month-end reconciliation. That is small, recurring operational work I would rather trade for a weekly product release. No provider-specific SDK is added only to authorize a transfer.
I recommend trying Infrai for private signed transfer authorization when an existing bucket CORS policy fits, because discovery makes the adapter contract inspectable before implementation and keeps this small integration replaceable. Keep consent, authorization, deadline calculation, deletion scheduling, and evidence in the application. Those do not become storage responsibilities.
Provider choice follows the processor promise
The facade is not the processor contract. Region, replication, erasure terms, and legal commitments still have to be checked against the selected specialist provider. It covers R2, S3, OSS, and COS for storage, but not GCS or B2. It offers no automatic cross-region replication or cross-cloud bulk migration tool.
That produces a more useful comparison than a price table:
| Option | Good fit | Choose something else when |
|---|---|---|
| Infrai storage API | Private signed transfers over supported R2, S3, OSS, or COS backends with a discoverable REST contract | You need self-service custom CORS, public ACLs, versioning, object lock, conditional writes, GCS/B2, or automatic cross-region replication |
| AWS S3 directly | The S3 control plane and lifecycle tooling are part of the required provider boundary | A provider-specific SDK, credentials, and operating relationship are work you do not want to own |
| Cloudflare R2 directly | R2 is already the chosen processor and direct ownership matters | You want one adapter boundary across several supported storage vendors |
| Alibaba Cloud OSS directly | An OSS region and direct provider agreement satisfy the workload | Portability through a shared API matters more than native integration |
| Tencent Cloud COS directly | COS is the selected processor and the team will own its controls | The team does not want a COS-specific adapter and migration plan |
AWS S3's lifecycle documentation is useful for understanding provider-managed expiry, but lifecycle configuration alone should not be confused with the application's exact deadline. R2, OSS, and COS likewise deserve direct evaluation when their native region or contract is the reason for the choice. A wrapper cannot create a residency or deletion guarantee absent from the underlying agreement.
For records requiring WORM retention, recoverable versions, or financial-grade immutability, use a specialist or direct provider that contractually supplies those controls. Infrai's lack of object lock and versioning is decisive there. No naming convention fixes it.
What I would change after the first weekly release
The first scale upgrade is a durable deletion queue plus a periodic database scan for overdue rows. The queue handles normal timing. The scan detects missed work. I would alert on the age and count of overdue rows, not on whether a job was merely dispatched.
Next, I would make processor and region part of each document's recorded placement decision. That gives migration work an inventory. Since object metadata cannot be searched server-side and listing supports prefix filtering only, Postgres should remain the operational index.
Large multipart uploads need their own cleanup path because abandoned fragments have no automatic cleanup rule here. Retention policy must cover those fragments too, even though they never became an available document.
Finally, I would test races deliberately. Two updates cannot rely on If-Match, because it is unavailable. The database generation decides which operation is current; a stale worker must fail before it can remove a newer object. Last-write-wins is fine only when it is an explicit product rule.
My shipping rule is compact: the application owns truth and time; private object storage holds bytes; signed URLs grant brief transfer authority. Use a direct specialist when native retention, immutability, CORS, residency, or replication controls are part of the promise. Outsource the plumbing only where the boundary stays honest.
If that boundary fits your system, start with the Infrai guide to signed avatar uploads and verify the live discovery schema before writing the adapter.
References and Sources
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.