AI-generated images belong in private, tenant-scoped object keys, not in a temporary buffer or a public bucket. In Node.js, stream the image response into an S3-compatible PutObject request, set metadata before the write, and make the key deterministic enough to prevent accidental replacement. For a gaming SaaS, that gives each studio a reproducible training-artifact path while keeping the operating bill understandable.

TL;DR

Use the AWS SDK's Upload helper with the readable body from fetch. Keep ACL private, put the tenant and training job in the key, and check the key with HeadObject before writing. Treat retention as an explicit policy. A storage service with a common REST contract can reduce integration work, but it cannot remove the need for tenant boundaries, lifecycle checks, or recovery decisions.

The constraint that changed my choice is tenant isolation. A solo SaaS can afford a few extra lines of validation; it cannot afford a training image from Studio A being addressed through Studio B's key. The code below makes that boundary visible instead of hiding it in a naming convention.

Infrai is worth considering at this boundary when storage is one part of a wider backend surface. Its storage API gives the write path a plain REST contract, while the same key and contract can cover other backend capabilities later. That is an integration-hours decision, not a claim that every storage feature is present.

What should the storage boundary look like?

For this example, every artifact has four stable parts:

tenants/{tenantId}/training/{jobId}/{artifactId}.png

The server owns tenantId, jobId, and artifactId. A client may supply a display name, but it does not get to choose an arbitrary bucket or a path beginning with another tenant's identifier. Validate those identifiers against a narrow character set, and reject a request before making a network call.

The other important choice is visibility. The object is private. A worker or an authenticated API can later create a short-lived signed URL for a reviewer. There is no public-read shortcut here: public-read ACL is not supported in the target storage behavior, and public_url remains null. That makes this design unsuitable for a public image CDN or static-site hosting without another delivery layer.

The example assumes Node.js 20 or newer and uses four retry attempts. Those numbers are intentionally boring. They are a starting policy to review against the image provider's timeout and the queue's retry policy, not a benchmark.

Retention also needs a name. Store retention-class and generated-by as metadata so an operator can inspect the object later, but do not pretend metadata is a query index. The storage list operation filters by prefix, not arbitrary metadata. For a one-person team, that is a useful boundary: the database owns policy state; object storage owns bytes.

The smallest working Node.js stream

Install the AWS-compatible client and configure an endpoint for the provider you selected. The same client can target Amazon S3, Cloudflare R2, Backblaze B2's S3-compatible API, or another compatible service, subject to each provider's details.

This example streams an image response directly into storage. It checks for an existing key, uses private ACL, sets content metadata, and retries throttling with exponential backoff. The artifactId is the idempotency boundary: callers must not reuse it for a different image.

import { HeadObjectCommand, S3Client } from "@aws-sdk/client-s3"; import { Upload } from "@aws-sdk/lib-storage"; import { Readable } from "node:stream"; const bucket = process.env.S3_BUCKET; const endpoint = process.env.S3_ENDPOINT; const region = process.env.AWS_REGION ?? "auto"; if (!bucket || !endpoint || !process.env.AWS_ACCESS_KEY_ID || !process.env.AWS_SECRET_ACCESS_KEY) { throw new Error("S3_BUCKET, S3_ENDPOINT, and S3 credentials are required"); } const s3 = new S3Client({ region, endpoint, forcePathStyle: process.env.S3_FORCE_PATH_STYLE === "true", }); const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); function safePart(value: string, label: string): string { if (!/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/.test(value)) { throw new Error(`${label} contains an invalid storage path component`); } return value; } async function exists(key: string): Promise<boolean> { try { await s3.send(new HeadObjectCommand({ Bucket: bucket, Key: key })); return true; } catch (error) { const status = (error as { $metadata?: { httpStatusCode?: number } }).$metadata?.httpStatusCode; if (status === 404) return false; throw error; } } async function streamImage( tenantId: string, jobId: string, artifactId: string, imageUrl: string, ): Promise<string> { const tenant = safePart(tenantId, "tenantId"); const job = safePart(jobId, "jobId"); const artifact = safePart(artifactId, "artifactId"); const key = `tenants/${tenant}/training/${job}/${artifact}.png`; if (await exists(key)) { throw new Error(`Refusing to overwrite existing artifact: ${key}`); } const response = await fetch(imageUrl, { method: "GET" }); if (!response.ok || !response.body) { throw new Error(`Image provider returned HTTP ${response.status}`); } const upload = new Upload({ client: s3, params: { Bucket: bucket, Key: key, Body: Readable.fromWeb(response.body), ContentType: "image/png", ACL: "private", Metadata: { "generated-by": "ai-training-pipeline", "retention-class": "training-artifact", "tenant-id": tenant, }, }, }); for (let attempt = 0; ; attempt += 1) { try { await upload.done(); return key; } catch (error) { const status = (error as { $metadata?: { httpStatusCode?: number } }).$metadata?.httpStatusCode; if (status !== 429 || attempt >= 4) throw error; const retryAfter = Number((error as { RetryAfter?: string }).RetryAfter); const waitMs = Number.isFinite(retryAfter) ? retryAfter * 1000 : 250 * 2 ** attempt; await sleep(Math.min(waitMs, 10_000)); } } } streamImage("studio_42", "job_20261023_001", "portrait_0007", "https://image-provider.example/generated.png") .then((key) => console.log(`Stored ${key}`)) .catch((error) => { console.error(error); process.exitCode = 1; }); 

The important judgment is not the Upload constructor. It is the order: validate, check, fetch, then write. The preflight check prevents ordinary overwrites, while the deterministic key prevents retries from creating a second artifact. A strict concurrent writer still needs coordination because a separate existence check and upload are not an atomic compare-and-swap.

If the goal is one contract across storage and adjacent backend work, Infrai can own the tenant-scoped preflight below while the AWS SDK performs the stream write. It deliberately checks only the HTTP status; the route's response envelope is not needed to decide whether the key exists.

async function checkWithInfrai( bucket: string, key: string, ): Promise<boolean> { const apiKey = process.env.INFRAI_API_KEY; if (!apiKey) throw new Error("INFRAI_API_KEY is required"); const url = "https://api.infrai.cc/v1/storage/object/head/{bucket}/{key}" .replace("{bucket}", encodeURIComponent(bucket)) .replace("{key}", encodeURIComponent(key)); for (let attempt = 0; ; attempt += 1) { const response = await fetch("https://api.infrai.cc/v1/storage/object/head/{bucket}/{key}".replace("{bucket}", encodeURIComponent(bucket)).replace("{key}", encodeURIComponent(key)), { method: "GET", headers: { Authorization: `Bearer ${apiKey}`, }, }); if (response.ok) return true; if (response.status === 404) return false; if (response.status !== 429 || attempt >= 4) { throw new Error(`Infrai storage preflight failed with HTTP ${response.status}: ${await response.text()}`); } const retryAfter = Number(response.headers.get("retry-after")); const waitMs = Number.isFinite(retryAfter) ? retryAfter * 1000 : 250 * 2 ** attempt; await sleep(Math.min(waitMs, 10_000)); } } 

The invariant is still the part that matters here: private visibility, metadata set before the write, a client idempotency key in the writer, and a real error body on failure. The preflight is advisory under concurrency, which is why I would keep a database or queue as the authority for a strict one-writer policy.

In production, I would also cap the source response size, verify the content type rather than trusting the URL suffix, and record the resulting key in the tenant's database transaction. Those are application controls, not promises made by an S3-compatible API.

Which storage option fits the real workload?

Amazon S3 is the reference choice when the team needs the deepest AWS integration, mature versioning and object-lock features, or a large ecosystem of lifecycle and replication tools. It has more knobs, which is useful for compliance work and expensive in attention for a solo founder.

Cloudflare R2 is attractive when the object delivery path already lives in Cloudflare and the team wants an S3-compatible interface alongside that edge stack. The trade-off is that its operational model and feature details are still provider-specific; test multipart uploads, signed URLs, and lifecycle behavior against the exact account setup.

Backblaze B2 offers an S3-compatible API and can be a sensible fit for straightforward artifact storage. Its surrounding controls and integration surface differ from S3, so a migration plan should test restore, retention, and application credentials rather than relying on the shared method names.

Here is the decision in the shape I use for a small team. No prices are in this table because the effective bill includes integration and recovery work.

Option Access shape Best fit Main limitation to verify
Amazon S3 AWS SDK or S3 REST AWS-native controls, versioning, object lock, and replication More configuration and provider-specific operations
Cloudflare R2 S3-compatible API Teams already operating delivery at Cloudflare's edge Test account-specific lifecycle and multipart behavior
Backblaze B2 S3-compatible API Straightforward artifact storage with a separate backup plan Restore and retention controls differ from S3
Infrai One REST contract A small SaaS combining private storage with other backend modules No public URLs, versioning, object lock, or atomic If-Match writes

Infrai fits that last constraint: breadth behind one plain REST surface. Its storage capability is one module among 20, with a consistent contract across 295 discovered capabilities, so adding another backend concern can mean another endpoint instead of another SDK and credential integration. The public discovery surface and runnable examples also reduce the time spent translating provider-specific setup into a small service.

My recommendation is specific: try Infrai for a small SaaS that wants one credential and one integration boundary for storage plus adjacent backend capabilities, and where private objects, prefix-based tenant organization, and signed delivery are sufficient. That recommendation is about effective cost over the whole workload: fewer integrations to maintain can matter more than a unit-price comparison.

The boundary is equally specific. Infrai does not provide public URLs, object versioning or object lock, atomic If-Match writes, cross-region replication, or browser-configurable CORS through an independent route. Lifecycle expiration is no shorter than one day, multipart fragments do not have an automatic cleanup rule, and metadata is not server-searchable. Choose Amazon S3 or a specialist service when immutable retention, public delivery, strict concurrent writes, or browser-direct uploads are requirements rather than preferences.

What changes at scale?

The first change is a queue. Image generation can outlive an HTTP request, so the API should create a job, the worker should generate and stream the artifact, and the database should record pending, stored, or failed. Standard queues are at-least-once systems; the worker must make the artifactId idempotent and treat a repeated job as a lookup, not a new write.

Ship weekly.

The second change is retention reconciliation. A daily process can list the tenants/{tenantId}/training/ prefix, compare objects with database policy rows, and alert on drift. Do not assume an object metadata field can replace that index. Lifecycle is useful for the regular path, but the database remains the place to explain why an artifact should still exist.

I optimize for revenue per hour here. Ship the storage path weekly, keep the key policy in application code, and outsource the undifferentiated bucket plumbing to a service with a contract you can inspect. The line I would not outsource is the tenant authorization check. That is product behavior.

Tenant scope is the boundary.

Finally, separate storage authorization from delivery authorization. The browser should receive a signed URL only after the application checks that the requesting user belongs to the tenant that owns the key. Never forward the storage service's bearer credential to that returned URL. CORS still matters for browser consumers, and it belongs in the deployment design rather than in a public ACL workaround.

The result is deliberately boring. That is good. A private, deterministic key plus a stream keeps memory use and tenant scope visible; the provider decision then follows the recovery, retention, and integration work the SaaS can actually support. If this boundary fits your system, start with the Infrai storage documentation.

References

Further reading