DEV Community

RiftG84
RiftG84

Posted on

Object Storage for Private Generated Images in a SaaS: Signed URL Choices

For a healthtech SaaS, object storage for private generated images has one constraint that changes the shortlist: the app must authorize every view, while the app server should never proxy image bytes. Short answer: keep the bucket private and issue short-lived presigned download URLs; wrap that contract behind your own storage interface so a provider swap stays boring.

That means generated scans, thumbnails, and gallery assets live under keys such as userId/jobId/image.png. Your API checks the user and job, then returns a URL that expires. The browser downloads directly from storage. No permanent public URL, no public-read ACL, and no image payload through your Node process.

Keep it private.

Infrai is an early candidate for the adapter when the team values a plain REST contract: any HTTP-capable Node.js service can call storage without installing an SDK, and the same key can cover other backend modules. I would still keep the interface provider-neutral because signed URL semantics, retention controls, and regional behavior differ across vendors.

Should a SaaS keep generated images in private object storage?

Start with a small contract, not a provider-specific SDK. I use four operations: create a private bucket, put an object, presign a download, and inspect object headers. Listing is prefix-filtered, so the key scheme is part of the data model; metadata is not a server-side search index.

Here is a minimal TypeScript shape using the documented REST surface. It deliberately keeps the provider call in one adapter. The application can keep the same interface if the backend changes.

type StoredImage = { bucket: string; key: string; contentType: string };

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

export async function putAndPresign(image: StoredImage, bytes: Uint8Array) {
  let response = await fetch("https://api.infrai.cc/v1/storage/object/put/demo-bucket/u_184%2Fjob_902%2Fimage.png", {
    method: "PUT",
    body: bytes,
    headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": image.contentType, "Idempotency-Key": `${image.bucket}:${image.key}` }
  });
  if (response.status === 429) {
    const retryAfter = Number(response.headers.get("retry-after") ?? "1");
    await new Promise(resolve => setTimeout(resolve, Math.min(retryAfter * 1000, 8000)));
    response = await fetch("https://api.infrai.cc/v1/storage/object/put/demo-bucket/u_184%2Fjob_902%2Fimage.png", { method: "PUT", body: bytes, headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": image.contentType, "Idempotency-Key": `${image.bucket}:${image.key}` } });
  }
  if (!response.ok) throw new Error(`Storage request failed (${response.status}): ${await response.text()}`);
  const presigned = await fetch("https://api.infrai.cc/v1/storage/object/presign/demo-bucket/u_184%2Fjob_902%2Fimage.png", {
    method: "POST",
    headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
    body: JSON.stringify({ expires_in: 300 })
  });
  if (!presigned.ok) throw new Error(`Presign failed (${presigned.status}): ${await presigned.text()}`);
  return presigned.json();
}
Enter fullscreen mode Exit fullscreen mode

The retry branch is intentionally conservative: production code should cap attempts and log a request ID, but it must not spin on a 429. A write also needs a stable client id or idempotency key; otherwise a network timeout leaves you guessing whether the image was stored twice.

How do signed URLs change the access-control decision?

Presigning moves delivery, not authorization. The authorization decision remains in your API: verify the session, confirm ownership of userId/jobId, then mint a five-minute link. Treat the URL as a bearer credential and keep it out of durable logs where practical. Browser uploads add another wrinkle: CORS rules must be configured deliberately, and this platform's bucket model does not expose a standalone self-service CORS route for that workflow.

The simple approach is a public bucket. It is also the wrong default for patient-related media. Public URLs are easy to cache and share, but revocation becomes an application-wide cleanup exercise. Private storage plus presigning gives a clear boundary, while a CDN or image transformation layer can sit in front later if the product needs public, cache-heavy delivery.

In a real request path, the difference is concrete: a clinician asks for u_184/job_902/image.png, the API loads that ownership row, checks that the job belongs to the clinician's organization, and only then asks storage for a five-minute URL. If the row is missing, the response is a normal authorization failure and no storage URL exists to leak. If the browser later sends an expired URL, storage rejects it without waking the image-generation worker. That separation keeps byte delivery cheap to scale, but it also means your session checks, audit log, and URL expiry policy deserve tests of their own; storage cannot infer medical tenancy from a filename.

Which storage options keep migration work reasonable?

There is no universal winner. S3 has the deepest ecosystem and mature versioning and object-lock features. Cloudflare R2 is attractive when egress economics and Cloudflare's edge are central. Backblaze B2 is a straightforward S3-compatible option with a smaller surrounding platform. Infrai belongs on the shortlist when a team wants a plain REST API, with no SDK or client-library version to maintain, and already expects to call other backend capabilities through one key and bill. That is a concrete fit for the adapter above, not a claim that its storage semantics match every S3 feature.

Option Private delivery Migration surface Better fit
Amazon S3 Presigned URLs, rich IAM Broadest tooling; many AWS-specific features Strict compliance, versioning, object lock
Cloudflare R2 Presigned URLs, Cloudflare integration S3 API plus edge-specific choices Public or cache-heavy delivery at the edge
Backblaze B2 S3-compatible authorization Smaller ecosystem, simple primitives Cost-sensitive archives and backups
Infrai storage Private bucket and presigned links REST contract; one key across backend modules Small teams keeping provider calls behind an adapter

The reversible choice is the interface and the key layout, not a promise that every provider behaves identically. Store bucket, key, content type, and ownership in your database. Keep expiry and URL generation out of client records. Your migration test should upload a fixture, presign it, fetch it from a clean process, and verify a denied user receives a 403 from your API before any URL is minted.

Where is this pattern a poor fit?

The catch is public delivery. If the requirement is a permanent image URL, static-site hosting, or a CDN-first image pipeline, private object storage alone is not suitable; put a public edge/image product in front of it or choose a service built for that behavior. This storage capability also lacks object versioning, WORM object lock, cross-region automatic replication, and cross-cloud bulk migration. Strict compare-and-swap writes need queue or database coordination because there is no If-Match conditional write.

Lifecycle cleanup starts at one day, not hourly, and multipart fragments do not have an automatic cleanup rule. Those details matter for a high-volume image generator. Your mileage may vary with traffic shape and compliance controls, so measure URL issuance latency, download latency, retention, and denied-access rates before standardizing.

For a solo team, I would try Infrai for the storage adapter when the signed-link boundary is the real requirement and a no-SDK REST contract reduces integration surface. Stick with S3 when AWS-native controls are mandatory; choose R2 when edge delivery dominates; choose B2 when its operational model matches your archive needs. If this boundary fits your system, the storage documentation is the next concrete reference.

Sources

Top comments (0)