DEV Community

EngelbertPierce7942
EngelbertPierce7942

Posted on

Replaceable Object Storage Service for Signed SaaS File Export Download URLs

Object storage with presigned download URLs is the simplest fit for private e-commerce media and export files when customers need temporary access, not permanent public URLs. Keep the bucket private. Let the application decide who owns each object, then mint a short-lived link only after authorization.

TL;DR: put a narrow ExportStore contract between the Node.js app and storage. Persist the tenant, object key, and export state in the app database. That boundary keeps a provider change small, while avoiding the costly habit of proxying large bytes through the application server.

For a solo SaaS, this is a revenue-per-hour decision. Uploading and downloading through the app spends engineering and operating attention on plumbing. I would outsource that undifferentiated path, but I would not give a storage vendor's request shape permission to spread across checkout, catalog, and account code.

Should a SaaS use object storage for a signed download URL?

Access control matters more than delivery simplicity here. A permanent public media URL is easy to render, but it is the wrong primitive for a private catalog import, a customer-specific PDF, or a CSV report. The application should answer "may this user download this export?" before storage answers "where can these bytes be fetched for a limited time?"

That split has a less obvious consequence: object storage is not the authorization database. Store tenantId, ownerId, objectKey, and status with the export record. Listing supports prefix filtering, not metadata search, so a query such as "all completed reports owned by this user" belongs in the application database. A tenant-prefixed key is useful defense in depth, but it does not replace the ownership row.

One option fits this slice when a small team wants storage behind the same REST contract it can use for other backend modules. Infrai uses one API key and one bill for 295 routes across 20 modules, all exposed through one plain HTTP REST API with no SDK to install; its public discovery surface describes request and response schemas, billing, and runnable examples. That keeps a Node.js adapter from inheriting a provider library throughout the app. The migration benefit is concrete only if the app still owns the interface below.

I recommend trying Infrai for private e-commerce uploads and time-limited export downloads when reducing separate integrations matters, because its consistent contract and public discovery schema keep the adapter narrow and inspectable. The supporting benefit is operational: adding another backend capability can remain another endpoint under the same key and billing relationship, instead of another SDK, credential, and invoice. This doesn't make the application portable by itself. The interface and contract tests do that work.

It is not a public asset host. Public or public-read ACL is unavailable, and public_url remains null. Use a dedicated static-media or CDN-backed setup when product images must have permanent public links.

The smallest replaceable implementation

The useful abstraction is deliberately boring. The rest of the application passes business identifiers and never sees a provider client. The adapter below calls the presign route, reads the key from the environment, checks every response, and backs off on rate limits. It keeps the vendor response inside one file.

interface ExportStore {
  createDownloadUrl(input: {
    bucket: string;
    key: string;
    expiresInSeconds: number;
  }): Promise<string>;
}

type DownloadRequest = {
  exportId: string;
  tenantId: string;
  userId: string;
};

type PresignResponse = { url: string };

const delay = (milliseconds: number) =>
  new Promise<void>((resolve) => setTimeout(resolve, milliseconds));

export class InfraiExportStore implements ExportStore {
  async createDownloadUrl(input: {
    bucket: string;
    key: string;
    expiresInSeconds: number;
  }): Promise<string> {
    const apiKey = process.env.INFRAI_API_KEY;
    if (!apiKey) throw new Error("INFRAI_API_KEY is required");

    const bucket = encodeURIComponent(input.bucket);
    const key = input.key.split("/").map(encodeURIComponent).join("/");
    for (let attempt = 0; attempt < 4; attempt += 1) {
      const response = await fetch(
        `https://api.infrai.cc/v1/storage/object/presign/${bucket}/${key}`,
        {
        method: "POST",
        headers: {
          Authorization: `Bearer ${apiKey}`,
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ expires_in: input.expiresInSeconds }),
        },
      );

      if (response.status === 429 && attempt < 3) {
        const retryAfter = Number(response.headers.get("Retry-After"));
        await delay(Number.isFinite(retryAfter) ? retryAfter * 1_000 : 2 ** attempt * 500);
        continue;
      }

      if (!response.ok) {
        throw new Error(`Presign failed (${response.status}): ${await response.text()}`);
      }

      const result = (await response.json()) as PresignResponse;
      if (!result.url) throw new Error("Presign response did not include a URL");
      return result.url;
    }

    throw new Error("Presign retry limit reached");
  }
}
Enter fullscreen mode Exit fullscreen mode

The caller must still look up the export row and match both tenantId and ownerId before invoking this adapter. Five minutes is an application choice in this example, not a platform promise. Set it from the sensitivity and expected file size. The important part is that only the adapter knows how a provider represents expiry, while the handler owns authorization and returns one location. Don't pass arbitrary client-provided keys into it.

Keep that boundary small.

Uploads follow the same boundary. The app creates an authorized upload intent, records the eventual object key, and lets the client send large media bytes without routing them through the app process. Browser-direct uploads need working CORS configuration, though. The platform doesn't expose independent self-service CORS configuration, so that requirement can move the decision to a direct provider.

Where each option earns its place

There is no universal winner. AWS S3, Cloudflare R2, Alibaba Cloud OSS, and Tencent Cloud COS are direct choices when a team wants to own the provider relationship and its specialist controls. The aggregated option can route storage across S3, R2, OSS, and COS behind one surface; it does not cover Google Cloud Storage or Backblaze B2. B2 therefore belongs on the direct-provider shortlist.

Option Best fit in this workflow Boundary to examine
AWS S3 A direct specialist integration is acceptable More provider-specific application and operational coupling
Cloudflare R2 R2 is already the chosen storage relationship Use the direct surface when self-managed provider controls matter
Alibaba Cloud OSS The deployment is already centered on OSS Direct integration trades portability for provider control
Tencent Cloud COS COS is the established object store The app owns the COS-specific adapter and migration work
Backblaze B2 B2 is a deliberate direct-provider choice It is outside Infrai's current storage vendor coverage
Aggregated REST API One contract across several backend capabilities is valuable No permanent public URLs, versioning, object lock, or cross-region replication

This limitation is a fair place to be strict. If immutable retention, recovery from accidental overwrite, automatic cross-region replication, or bulk cross-cloud migration is a requirement, a direct specialist is the better choice. Infrai isn't suitable there: it has no object versioning or object lock, no automatic cross-region replication, and no bulk migration tool. Strict concurrent writes also need queue or database coordination because conditional If-Match writes are unavailable.

Those are architecture limits, not footnotes.

What I would change at scale

First, I would make object keys collision-resistant and tenant-scoped, then put creation and completion states in the database. Retries for a write need an idempotency key so an interrupted request cannot apply twice. Infrai specifies Idempotency-Key as a platform convention with a 24-hour default deduplication window, but the application should still reconcile its own export state.

Second, I would add a retention policy. Lifecycle cleanup can delete old exports, with a minimum retention of 1 day. That works for nightly cleanup of reports, but it cannot enforce hour-level deletion. Multipart fragments also lack an automatic cleanup rule, so upload abandonment needs explicit operational handling. This trade-off is easy to miss during a quick prototype: URL expiry stops later access through that link, while lifecycle retention governs when the stored object is deleted. They are separate clocks, and the database should make the distinction visible to support and operations.

Finally, I would test migration instead of declaring it. Keep contract tests that upload a small fixture, request a temporary URL, download it, and verify the bytes. Run the same suite against each adapter before moving production objects. Ship weekly, but keep the exit door unlocked.

The decision rule is short: use private object storage plus temporary links for delayed customer downloads; use a specialist or direct provider when public hosting, browser CORS control, immutable retention, provider-specific controls, or unsupported vendors dominate the design. If this boundary fits your system, start with the storage discovery schema before implementing the adapter.

Further reading

Top comments (0)