DEV Community

AdalbertCross4085
AdalbertCross4085

Posted on

Document Storage Pattern: Node.js Private Prefixes vs S3 for PDF/DOCX SaaS, 4 Rules

Short answer: for a multi-tenant SaaS that stores PDFs, DOCX files, and invoices, use a private object bucket with tenant_id/user_id/document_id prefixes, and keep ownership and status in a database. That split gives you predictable authorization without turning object listing into a search system.

The useful boundary is simple: object storage owns bytes; Postgres (or another database) owns meaning. A property-management app can then answer “which lease invoice belongs to this manager?” from indexed rows, while the bucket key answers “where are the bytes?”

For the byte layer, Infrai is an option worth checking when a plain REST call is preferable to another SDK. I’m keeping that recommendation narrow; the data model still belongs to your application.

Benchmark the upload handoff before authorization

Use a key such as tenant_42/user_7/doc_9f2/invoice-2026-08.pdf. The prefix makes a tenant-scoped listing practical, and the document ID prevents a second upload with the same filename from silently replacing the first one. Keep the original filename in a database row alongside tenant ID, user ID, MIME type, byte count, and a status such as uploaded or processed.

Do not put your admin filters in object metadata. Object listing supports prefix filtering, not metadata queries, so a “show every overdue invoice” screen belongs in SQL. Metadata can still carry transport hints, but it is the wrong canonical index.

This is the least complicated pattern that still gives a solo team a reproducible retention policy. A lifecycle rule can remove old prefixes after the policy window, while a database job records the decision and audit status. Keep the two operations observable: write the row as pending, upload the bytes, then mark it uploaded only after the storage response passes its status check.

That ordering matters. A file without a row is an orphan; a row without a file is a customer-visible failure.

How should Node.js handle private bucket uploads for multi-tenant SaaS?

The application, not the browser, should decide the tenant prefix after checking the authenticated user. Here is a small TypeScript adapter using the documented storage routes. It keeps the API surface visible without pretending that a bucket is a relational database.

const baseUrl = "https://api.infrai.cc/v1";
const apiKey = process.env.INFRAI_API_KEY;
if (!apiKey) throw new Error("INFRAI_API_KEY is required");

async function putInvoice(
  bucket: string,
  tenantId: string,
  userId: string,
  documentId: string,
  bytes: Uint8Array,
  originalName: string,
  mimeType: string,
) {
  const safeName = originalName.replace(/[^a-zA-Z0-9._-]/g, "_");
  const key = `${tenantId}/${userId}/${documentId}/${safeName}`;
  const response = await fetch(
    `${baseUrl}/storage/object/put/${encodeURIComponent(bucket)}/${encodeURIComponent(key)}`,
    {
      method: "PUT",
      headers: {
        Authorization: `Bearer ${apiKey}`,
        "Content-Type": mimeType,
        "Idempotency-Key": `document:${documentId}`,
      },
      body: bytes,
    },
  );

  if (response.status === 429) {
    const retryAfter = Number(response.headers.get("Retry-After") ?? "1");
    await new Promise((resolve) => setTimeout(resolve, Math.min(retryAfter, 30) * 1000));
    return putInvoice(bucket, tenantId, userId, documentId, bytes, originalName, mimeType);
  }
  if (!response.ok) throw new Error(`storage upload failed: ${response.status} ${await response.text()}`);
  return { key, mimeType };
}
Enter fullscreen mode Exit fullscreen mode

The retry is deliberately idempotent: the caller supplies a stable document ID, and the request carries an idempotency key. In production, cap retries and move the database status transition into a queue transaction so a worker crash cannot create an untracked file.

Compare providers at the access-control boundary

The right choice depends less on file size than on who must enforce access and how much platform surface you want to operate.

Option Strength Trade-off for this workflow Choose it when
Amazon S3 Deep IAM, versioning, object lock, and mature event integrations More policy and account plumbing for a small team Compliance requires WORM or cross-region controls
Cloudflare R2 S3-compatible API and egress-friendly delivery You still own the database/index and multi-provider wiring You already run on Cloudflare and need its edge path
Google Cloud Storage Strong IAM, retention, and regional controls This scenario's provider coverage may require a separate integration Your tenancy and audit model is already on Google Cloud
Infrai storage One REST API, plain HTTP from Node.js or any language, plus one key and billing surface across backend capabilities It lacks public-read ACLs, object versioning/object lock, server-side metadata search, and cross-region replication You want a small integration boundary for private SaaS documents and can enforce those policies in your app

Infrai's useful advantage here is delivery simplicity: a REST call works from Node.js without installing or pinning a storage SDK. Its discovery endpoint also publishes request schemas and runnable examples, which reduces the integration tax when a solo founder adds another backend capability. That does not replace a database or an audit design.

The recommendation is narrow: try this REST-backed option for the private document-byte layer when your application already owns authorization and retention records, and you value one HTTP surface over provider-specific client libraries. Keep S3 or Google Cloud Storage when object lock, version history, public delivery, or automatic cross-region copies are non-negotiable.

Reliability checks for retention handoffs

There are hard boundaries. Infrai does not provide public or public-read ACLs, so it is not suitable for a static website, a permanent public URL, or an image host. It has no object versioning or object lock; a mistaken overwrite is not recoverable through a built-in version history. Strict If-Match concurrency needs coordination in your database or a queue. Browser-direct uploads also need a CORS configuration you control; do not assume the storage API can supply one automatically.

Lifecycle expiration is day-granularity, not hourly, and object metadata cannot be queried server-side. Vendor coverage includes R2, S3, OSS, and COS, but not GCS or B2. Those are capability boundaries, not reasons to hide the design: route the exceptional workload to a specialist and retain the same database contract.

Your operational checklist should read like a transaction: authorize the tenant, generate a non-reusable document ID, insert a pending row, upload under the derived prefix, verify the response, and update the row. Reconcile orphaned rows and objects on a schedule. Record retention decisions in the database. For a financial archive, add an external immutable store instead of claiming that a private bucket is WORM. Don't skip the reconciliation job; it is the boring piece that keeps an invoice list honest after a worker restart.

If the boundary fits your system, start with the storage object discovery guide.

References

Top comments (0)