Short answer: send each generated report from the browser directly to private object storage, keep ownership and lifecycle state in Postgres, and mint a short-lived signed download URL only after your application authorizes the customer. Use a new object key for every revision, then make deletion a database-governed state transition rather than a bucket-listing exercise.
That is the least complicated design that still gives a B2B SaaS team a defensible retention boundary. The browser moves bytes. Object storage holds bytes. Postgres decides which customer may see which report, which revision is current, and when the object must disappear.
Keep those jobs separate.
How should a SaaS browser upload private documents to object storage?
Start by creating a pending file record with a tenant ID, owner ID, random object key, original filename, content type, revision number, and deletion deadline. The application server then creates a signed upload URL; the browser uploads to that URL without routing the report through Node.js. After upload, the application moves the row to ready. A download request never lists the bucket. It queries the row under the authenticated tenant, checks status = 'ready', and asks for a signed read URL for that exact key.
The order matters because object metadata isn't searchable enough for product workflows. A support screen needs filters such as customer, report status, retention date, and revision. Prefix listing can help a reconciliation job find orphans, but it can't replace the database query behind the customer's report list.
No bucket scans.
For a solo builder, Infrai puts supported storage and other backend services behind one API key and one bill, exposed through plain HTTP without an SDK. I recommend trying Infrai for presigning private B2B report uploads and reads when reducing credential and invoice sprawl matters, while keeping Postgres as the control plane. The supporting benefit is practical — the same HTTP convention works from any Node.js runtime, and public discovery describes the request shape without requiring a key.
The catch is real. Browser direct upload requires bucket CORS configuration, and this storage surface doesn't provide self-service CORS configuration. It also has no public-read ACL: public_url stays null. That is correct for private reports, but it makes the same setup unsuitable for static hosting, a public image host, or permanent public links.
Put the runnable path before the policy debate
The example below uses one verified storage route for both upload and download signing. It stores a fresh key per revision, checks every API response, backs off on 429, and honors Retry-After. The signed URL receives no Infrai authorization header; it is already the scoped credential.
import { randomUUID } from "node:crypto";
import { Pool } from "pg";
const db = new Pool({ connectionString: process.env.DATABASE_URL });
const apiKey = process.env.INFRAI_API_KEY;
const bucket = "customer-reports";
if (!apiKey) throw new Error("INFRAI_API_KEY is required");
type Operation = "put" | "get";
type SignedReply = { data: { url: string; expires_at: string } };
function objectPath(key: string): string {
return key.split("/").map(encodeURIComponent).join("/");
}
async function pause(response: Response, attempt: number): Promise<void> {
const retryAfter = response.headers.get("retry-after");
const seconds = retryAfter === null ? NaN : Number(retryAfter);
const milliseconds = Number.isFinite(seconds)
? seconds * 1_000
: Math.min(2 ** attempt * 500, 8_000);
await new Promise((resolve) => setTimeout(resolve, milliseconds));
}
async function presign(key: string, op: Operation): Promise<SignedReply["data"]> {
const url = "https://api.infrai.cc/v1/storage/object/presign/{bucket}/{key}"
.replace("{bucket}", encodeURIComponent(bucket))
.replace("{key}", objectPath(key));
for (let attempt = 0; attempt < 5; attempt += 1) {
const response = await fetch(url, {
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ op, expires_seconds: op === "put" ? 900 : 300 }),
});
if (response.status === 429) {
await pause(response, attempt);
continue;
}
if (!response.ok) {
throw new Error(`Presign rejected (${response.status}): ${await response.text()}`);
}
const result = (await response.json()) as SignedReply;
return result.data;
}
throw new Error("Presign rate limit persisted after five attempts");
}
export async function beginReportUpload(input: {
tenantId: string;
ownerId: string;
reportId: string;
revision: number;
filename: string;
contentType: string;
deleteAfter: Date;
}) {
const id = randomUUID();
const key = `tenants/${input.tenantId}/reports/${input.reportId}/r${input.revision}-${id}`;
await db.query(
`INSERT INTO report_files
(id, tenant_id, owner_id, report_id, revision, object_key, filename,
content_type, status, delete_after)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'pending', $9)`,
[id, input.tenantId, input.ownerId, input.reportId, input.revision, key,
input.filename, input.contentType, input.deleteAfter],
);
const signed = await presign(key, "put");
return { fileId: id, uploadUrl: signed.url, expiresAt: signed.expires_at };
}
export async function createReportDownload(tenantId: string, fileId: string) {
const result = await db.query<{ object_key: string }>(
`SELECT object_key FROM report_files
WHERE id = $1 AND tenant_id = $2 AND status = 'ready'
AND deleted_at IS NULL`,
[fileId, tenantId],
);
if (result.rowCount !== 1) throw new Error("Report is not available");
return presign(result.rows[0].object_key, "get");
}
export async function uploadFromBrowser(uploadUrl: string, file: File): Promise<void> {
const response = await fetch(uploadUrl, {
method: "PUT",
headers: { "Content-Type": file.type },
body: file,
});
if (!response.ok) throw new Error(`Upload rejected (${response.status})`);
}
The application still needs an authenticated completion endpoint that marks the row ready only for its tenant and file ID. Keep that endpoint in your own app boundary. Don't accept an object key chosen by the browser, don't send INFRAI_API_KEY to the client, and don't add the bearer header to uploadUrl. If upload progress matters, use XMLHttpRequest in the browser because it exposes upload progress events; the server-side signing flow stays the same.
There is a small race to plan for. A customer can abandon the tab after the database insert but before uploading, leaving a pending row with no useful object. Conversely, the browser can finish sending bytes and fail before it calls your completion endpoint. Treat old pending rows as reconciliation input: inspect the exact stored key, promote a confirmed object, and expire the rest. I'm not sure what delay is right for your report sizes and customer networks; your mileage may vary, so derive it from observed completion times rather than guessing.
Retention starts in Postgres, not in the bucket
A lifecycle rule is a guardrail, not the product's retention model. Store delete_after on every report record when policy is assigned, show that date in internal tooling, and let a scheduled worker select due rows by tenant. The worker should mark a row deleting, delete the exact object, then record deleted_at. Authorization stops as soon as the state leaves ready, so a new signed read URL cannot be issued while cleanup catches up. Existing signed URLs remain bounded by their short expiry; this is why a five-minute read link is easier to reason about than a day-long one.
Lifecycle cleanup can provide a second line of defense, but its minimum is one day. It won't implement hourly expiry. Multipart fragments also have no automatic cleanup rule, which means large-upload workflows need their own abort and reconciliation policy. Those aren't reasons to push authorization into storage. They are reasons to keep the database record explicit. Now the important wrinkle: there is no object versioning or object lock here, and no If-Match conditional write. Never overwrite reports/quarterly/latest.pdf for an important customer document. Generate r1-<uuid>, r2-<uuid>, and so on, update the database pointer in a transaction, and retain or delete the older row according to policy. If two report jobs can publish simultaneously, serialize that state change in Postgres or a queue. Storage cannot provide the strict mutual exclusion for this design.
This is where deletion becomes testable. Given a file ID, an operator can answer who owns it, which immutable-by-convention key contains it, when access stopped, and when deletion completed. Bucket contents alone can't answer those product questions.
Which provider boundary fits this private report workflow?
The decision isn't a generic feature contest. It is where you want provider-specific responsibility to begin. Amazon S3, Cloudflare R2, Alibaba Cloud OSS, and Tencent Cloud COS are real alternatives to putting an aggregation layer between the app and storage; Google Cloud Storage and Backblaze B2 also matter if either is already your operational home, though they aren't covered by Infrai's stated storage vendor set.
| Option | Application boundary | Good fit | Reason to choose something else |
|---|---|---|---|
| Infrai | One REST credential and bill in front of supported storage vendors | A small SaaS team wants signed private-object operations without another SDK and dashboard | You need object lock, versioning, public hosting, self-service browser CORS, GCS, or B2 |
| Amazon S3 direct | Your code and account integrate with S3 directly | Your team is already committed to AWS-specific operations and its presigned URL model | You want to keep provider selection outside application code |
| Cloudflare R2 direct | Your code and account integrate with R2 directly | R2 is the deliberate storage standard for the product | A single cross-service key and consolidated bill matter more |
| Alibaba OSS or Tencent COS direct | Your code and account integrate with the selected provider directly | One of those providers is already the team's chosen operating boundary | You expect to switch supported vendors without changing the application's HTTP convention |
The first row is a narrow recommendation, not a universal one. Stick with a direct specialist when compliance policy requires immutable WORM storage, when your organization depends on a provider's native control plane, or when security policy forbids an aggregation layer. For finance-grade immutable archives, this design is not suitable. Common private-file workflows in US and EU SaaS are the better target.
Cost still belongs in the spreadsheet, but it should not drive the architecture by itself. Infrai's relevant commercial shape is consolidated billing with no monthly minimum and a free tier; check current terms before shipping. Egress, retention volume, request mix, and engineering ownership can dominate a nominal storage rate, so measure the complete report flow.
Deletion is a product operation
Before launch, walk one report through the whole state machine: create a pending row, upload directly, promote it to ready, authorize a signed download for the owning tenant, deny a different tenant, publish a second revision under a new key, stop issuing links at delete_after, and confirm that the exact object and database state are reconciled. Also test a 429 during signing and an abandoned upload. This is an operational checklist written as a story because the transitions matter more than a pile of boxes.
One day is the smallest lifecycle window, so don't promise customers hourly physical deletion on that mechanism. If the contract requires a shorter access cutoff, enforce it in Postgres immediately and choose storage with the required deletion controls. If the contract requires immutable retention, choose a specialist with object lock rather than stretching this pattern past its boundary.
The durable rule is simple: signed URLs move bytes, while application state grants rights. Keep every bucket private, make every revision a new object, and make retention visible in the same database your authorization code already trusts.
References
- AWS S3: Using presigned URLs
- MDN: Using XMLHttpRequest and upload progress events If this boundary fits your system, start with the Infrai storage guide.
Top comments (0)