Put signed e-commerce documents in object storage, keep their metadata and deletion state in the application database, and issue short-lived download URLs only after an authenticated tenant check. Do not use a Node.js server's local disk as the durable file store. The deciding constraint is not raw storage price. It is whether one tenant can ever name, fetch, retain, or delete another tenant's document while every file still disappears on its explicit deadline.
That answer creates four boundaries: identity, object naming, delivery, and deletion. Signed URLs solve only the delivery boundary. They do not establish tenant ownership, and their expiration does not delete an object.
This distinction matters for a signed return authorization, supplier agreement, or proof-of-delivery PDF. The download may be valid for five minutes while the underlying record must remain available for 90 days. Mixing those clocks is an easy way to ship a system that looks correct in a demo and fails its retention contract later.
Should Node.js SaaS file export delivery use signed URLs or server storage?
A signed URL is a temporary capability to perform a specific storage operation. Anyone who obtains a still-valid URL can generally use it until it expires, subject to the conditions encoded by the storage service. The application must therefore decide who may receive that capability before it creates one.
The unsafe pattern accepts an object key from the browser and signs it. A user from tenant shop_17 can then try a key belonging to shop_42. An unguessable key reduces casual discovery, but guessing resistance is not authorization.
The safer flow starts with an application-level document ID. The server queries metadata using both tenant_id and document_id, checks document state, and only then asks the storage adapter for a download URL. The browser never gets an API that signs arbitrary keys.
Keep the object key opaque as well. A shape such as tenants/<tenant-id>/documents/<random-id> makes operational inspection easier and supports prefix-scoped policies, but the prefix remains defense in depth. Database authorization is still mandatory. Do not put customer names, email addresses, order numbers, or original filenames in the key; keys leak into logs and operational tooling.
Four checks carry most of the design:
- Every metadata lookup includes the authenticated tenant ID.
- The storage key comes from that metadata row, never from request input.
- URL lifetime is much shorter than document retention.
- Deletion is tracked as state, not inferred from a missing download link.
Short link. Long record. Separate clocks.
The constraint that changes the implementation
Local app-server storage is attractive because the first call is tiny: write a file, return a route, move on. That advantage collapses once Node.js runs on more than one instance. A document written to instance A is absent from instance B unless both mount shared storage. Deployments, instance replacement, disk limits, backup scope, and deletion jobs all become part of the file API.
Object storage moves the bytes behind a service boundary designed around objects and keys. AWS documents lifecycle rules that can expire current object versions and describes lifecycle actions as asynchronous. Google Cloud Storage likewise documents object lifecycle management and signed URLs. Those are useful primitives, but neither relieves the application of recording its own deadline and access decision.
Versioning deserves special attention. If a bucket retains noncurrent versions, deleting the current object may not remove every stored version. Lifecycle configuration has separate concepts for current and noncurrent versions. A legal or contractual deletion deadline must be translated into rules for all versions, incomplete uploads, replicas, and backups that are in scope. "The GET now returns 404" is a weak deletion test.
There is another trap: treating lifecycle policy as a precise scheduler. Lifecycle processing can be asynchronous, so an application that promises deletion at an exact instant needs an explicit deletion worker and an auditable state transition. A lifecycle rule is valuable as a backstop for stranded objects. It is not the only control.
Smallest working Node.js boundary
I want the handler boring enough to review in one screen. Storage-specific signing stays behind an interface, while authorization and retention semantics remain visible in the application. All durations below are policy examples, not claims about a provider limit.
type DocumentRow = {
id: string;
tenantId: string;
objectKey: string;
originalName: string;
state: "available" | "deleting" | "deleted";
deleteAfter: Date;
};
interface DocumentRepository {
findForTenant(tenantId: string, documentId: string): Promise<DocumentRow | null>;
claimExpired(now: Date, limit: number): Promise<DocumentRow[]>;
markDeleted(documentId: string, deletedAt: Date): Promise<void>;
releaseDeletionClaim(documentId: string): Promise<void>;
}
interface ObjectStore {
createDownloadUrl(input: {
key: string;
expiresInSeconds: number;
downloadName: string;
}): Promise<string>;
deleteObject(key: string): Promise<void>;
}
type DownloadRequest = {
authenticatedTenantId: string;
documentId: string;
};
export async function createDocumentDownload(
request: DownloadRequest,
documents: DocumentRepository,
objects: ObjectStore,
now = new Date(),
): Promise<{ url: string; expiresAt: string }> {
const document = await documents.findForTenant(
request.authenticatedTenantId,
request.documentId,
);
if (!document || document.state !== "available" || document.deleteAfter <= now) {
throw new Error("Document is not available");
}
const expiresInSeconds = 300;
const url = await objects.createDownloadUrl({
key: document.objectKey,
expiresInSeconds,
downloadName: document.originalName,
});
return {
url,
expiresAt: new Date(now.getTime() + expiresInSeconds * 1_000).toISOString(),
};
}
The deliberately generic error avoids confirming that another tenant's document exists. The repository contract forces the ownership predicate into the lookup. This is a small DX choice with a large review payoff: a handler cannot retrieve a row globally and remember to compare tenants several lines later.
The signing adapter should also constrain response disposition and filename where the storage API supports it. Still, the application must sanitize the filename before persisting it and must never interpolate it into an object key. Keep content type as verified metadata rather than trusting an upload header forever.
Deletion uses a separate worker. Claiming rows prevents two workers from doing the same work concurrently; the exact claim mechanism belongs in the database implementation.
export async function deleteExpiredDocuments(
documents: DocumentRepository,
objects: ObjectStore,
now = new Date(),
): Promise<void> {
const batch = await documents.claimExpired(now, 100);
for (const document of batch) {
try {
await objects.deleteObject(document.objectKey);
await documents.markDeleted(document.id, now);
} catch (error) {
await documents.releaseDeletionClaim(document.id);
throw error;
}
}
}
This code assumes deleteObject is safe to retry when the object is already absent; enforce that contract in the adapter. It also stops the batch on failure, which is easy to reason about but limits throughput. A production queue can retry items independently. Start with semantics, then optimize.
The database row should survive byte deletion long enough to answer audit questions without retaining the document itself. Store the scheduled deadline, deletion completion time, object identifier, policy version, and a non-sensitive failure classification. Avoid logging signed URLs. They are credentials until they expire.
What I would change at scale
At higher volume, I would keep the same four boundaries and replace the polling loop with claimed batches or queued deletion tasks. The worker needs bounded retries, dead-letter handling, and a reconciliation pass that compares overdue metadata with storage state. Metrics should cover overdue objects, deletion latency, signing failures, and authorization denials by tenant. Do not label a request with the raw object key; high-cardinality, sensitive labels make observability worse.
I would benchmark the path that users feel: time from clicking Download to receiving a usable redirect, plus the first-byte time from storage. Benchmarking only the signing function flatters the architecture. The test matrix should include two tenants with similarly shaped document IDs, an expired retention deadline, a deleted object, a replayed URL, simultaneous deletion workers, and a signer outage.
Tenant isolation can become physical later. Large or regulated tenants may justify separate buckets, accounts, projects, or encryption keys, but those choices multiply policy, lifecycle, monitoring, and deployment configuration. I would not begin there without a stated isolation requirement. A shared bucket with tenant-prefixed opaque keys, narrowly scoped service credentials, and mandatory database authorization is simpler to operate. The trade-off is a larger blast radius if storage policy is misconfigured.
Config bloat is real. Bucket policies, lifecycle rules, cross-origin settings, key management, and worker schedules can drift across environments. Put them in reviewed infrastructure definitions, then run deployment checks that upload, authorize, download, expire, delete, and verify a synthetic document. One end-to-end probe catches more than a page of configuration screenshots.
Choosing without turning price into the architecture
Compare any candidate against the workflow, not a headline price. The useful unit is a retained document delivered under policy: stored bytes, write and read operations, outbound transfer, deletion operations, request latency, operational labor, and the cost of a missed deadline. Published prices change. The boundary does not.
The decision table is short because the hard part sits above the storage API.
| Option | First implementation | Multi-instance behavior | Tenant boundary | Deadline deletion |
|---|---|---|---|---|
| App instance disk | Fewest calls | Requires affinity or shared disk | Entirely application-controlled | Worker plus host and backup handling |
| Shared filesystem | Familiar file API | Shared by design | Application checks and filesystem policy | Worker plus snapshot handling |
| Object storage | Adapter and signer required | Independent of app instances | Application checks plus storage policy | Worker, lifecycle backstop, and version handling |
For this e-commerce workload, object storage wins on operational shape, not because it is universally cheaper. The Node.js service owns identity and policy. Storage owns durable bytes and temporary capabilities. The database owns the deadline and the evidence that deletion ran.
That split is simple enough for an SDK consumer to understand and strict enough to test. More important, it gives every clock one job.
References
- https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-lifecycle-mgmt.html
- https://docs.aws.amazon.com/AmazonS3/latest/userguide/lifecycle-expire-general-considerations.html
- https://cloud.google.com/storage/docs
- https://cloud.google.com/storage/docs/access-control/signed-urls
- https://cloud.google.com/storage/docs/lifecycle
- https://owasp.org/www-project-application-security-verification-standard/
Top comments (0)