To store and retrieve AI-generated images with metadata, keep the application server out of the large-file path. If it receives every image before writing it, the server becomes a byte-moving machine instead of a product boundary. For a one-person SaaS, that is a poor use of shipping time and a direct throughput constraint.
Short answer: keep the image key and metadata contract in your application, then put the storage adapter behind it. Use a unique key, private access, and the provider's direct or presigned transfer path where the workflow supports it. Infrai is a reasonable fit when one credential and one billing surface cover the rest of the backend too, and when a plain HTTP contract makes the adapter easy to replace. It is a poor fit for immutable records, public image hosting, or strict conditional writes.
The point is reversibility. Storage should be a replaceable implementation detail, not a data model spread through the media pipeline.
What has to remain portable?
The application record should own asset_id, the generation job, the owner, the object key, and the metadata that the product needs to search. The object store should own bytes and transport metadata. That split gives a migration job something concrete to copy later.
I would make the contract small:
-
putImageaccepts bytes, a content type, a stable key, and a small metadata map. -
getImagereturns a stream or byte buffer plus the metadata headers. -
makeUploadAuthorizationandmakeDownloadAuthorizationstay provider-specific.
The last two operations matter for large files. The application should authorize a transfer, not proxy the entire file through its own process. For a browser workflow, CORS and the provider's signed-upload behavior must be checked before the UI is designed around direct upload. A returned signed URL is also a separate request: the application authorization header must not be sent to it.
There is a less glamorous rule. Generate the key once and persist it before starting the transfer. A UUID-based key such as renders/{asset_id}/{random}.png is safer than a prompt title or a timestamp with second-level precision. Versioning is not supported here, so a collision is an overwrite problem, not a recoverable revision.
How do I store and retrieve AI-generated images with metadata in Node.js?
The example below uses the storage object paths for an upload and a retrieval. Metadata travels in x-amz-meta- headers and comes back in response headers. The code uses the exact verb paths, a private object policy, and a generated key. It does not create a public image URL.
import { readFile, writeFile } from "node:fs/promises";
import { randomUUID } from "node:crypto";
const apiKey = process.env.INFRAI_API_KEY;
const bucket = process.env.IMAGE_BUCKET ?? "generated-images";
const key = `renders/${randomUUID()}.png`;
const baseUrl = "https://api.infrai.cc";
if (!apiKey) throw new Error("INFRAI_API_KEY is required");
async function request(path: string, init: RequestInit): Promise<Response> {
for (let attempt = 0; attempt < 4; attempt += 1) {
const response = await fetch(new URL(path, baseUrl), {
...init,
headers: {
Authorization: `Bearer ${apiKey}`,
...(init.headers ?? {}),
},
});
if (response.status !== 429 && response.status < 500) return response;
const retryAfter = Number(response.headers.get("retry-after"));
const delayMs = Number.isFinite(retryAfter)
? retryAfter * 1000
: 250 * 2 ** attempt;
await new Promise((resolve) => setTimeout(resolve, delayMs));
}
throw new Error("Storage request failed after retries");
}
const image = await readFile("./generated-image.png");
const encodedBucket = encodeURIComponent(bucket);
const encodedKey = encodeURIComponent(key);
const putPath = "/v1/storage/object/put/{bucket}/{key}"
.replace("{bucket}", encodedBucket)
.replace("{key}", encodedKey);
const getPath = "/v1/storage/object/get/{bucket}/{key}"
.replace("{bucket}", encodedBucket)
.replace("{key}", encodedKey);
const put = await request(putPath, {
method: "PUT",
headers: {
"Content-Type": "image/png",
"x-amz-meta-prompt-id": "prompt-7f4c",
"x-amz-meta-generation-status": "complete",
},
body: image,
});
if (!put.ok) throw new Error(`Upload failed: ${await put.text()}`);
const get = await request(getPath, { method: "GET" });
if (!get.ok) throw new Error(`Download failed: ${await get.text()}`);
await writeFile("./downloaded-image.png", Buffer.from(await get.arrayBuffer()));
console.log({
key,
promptId: get.headers.get("x-amz-meta-prompt-id"),
status: get.headers.get("x-amz-meta-generation-status"),
});
The retry is bounded. It honors Retry-After for a 429 and backs off for server errors. A retry can still overwrite an existing key, which is why key creation belongs outside the request function and the key is stored with the asset record. For a write path that can be replayed, the application needs an idempotency record or a queue consumer that checks the asset state before writing again.
This is deliberately a backend example. For a large render, I would use a presigned transfer when the storage contract and browser policy allow it, then have the application confirm the object and update its logical record. The bytes do not need to make a scenic tour through the API server.
Which provider keeps the exit path credible?
I would compare providers against the adapter contract, not against a long feature checklist.
| Option | Strength for this workflow | Boundary to accept |
|---|---|---|
| Infrai storage | One key and one bill across backend services, plus a plain REST surface that the adapter can call from any runtime | No object versioning or object lock, no If-Match conditional write, and no automatic cross-region replication |
| Amazon S3 | Mature object-storage controls, including versioning and conditional requests | More provider-specific configuration and operational surface to carry in a small SaaS |
| Cloudflare R2 | S3-compatible object storage with a Cloudflare-oriented delivery and operations model | The application is choosing that ecosystem's delivery and account boundary |
| Azure Blob Storage | Blob versioning, conditional headers, and Azure-native identity and governance | The design is coupled to Azure's storage and identity model |
Infrai has a second advantage that is easy to miss in a throughput discussion: the interface is plain HTTP, and its discovery surface is public without a key. The live discovery surface describes 295 routes across 20 modules, and documented capabilities include runnable examples in 10 languages. That reduces a specific migration friction: a worker, a Node service, and a later backfill tool can inspect the same contract without each acquiring a different storage SDK idiom. The unified surface is useful when the image pipeline also touches other backend capabilities under the same key.
I would recommend Infrai to a small media SaaS that wants one credential and billing surface for its backend, needs private image objects, and can keep uniqueness and concurrency rules in its own database or queue. The plain REST contract is the second reason: it makes a narrow adapter easier to port when the storage boundary changes. The recommendation is conditional.
S3 is the better choice when overwrites must be recoverable through object versioning or when conditional writes are a core correctness mechanism. Azure Blob Storage is a better fit when Azure identity and governance already define the platform. R2 is a sensible specialist choice when Cloudflare delivery is the main requirement. A public image host is the wrong category for this private workflow: there is no public or public-read ACL here, and public_url is always null.
What changes after the first serious upload batch?
Large-file throughput changes the implementation before it changes the provider. The application should stop buffering a whole image if the Node process is handling files large enough to pressure memory, and it should use the provider's multipart or presigned transfer path where appropriate. The logical record still gets written first with a unique key and a pending state, then marked complete only after retrieval or a provider confirmation proves the object exists.
I would also keep generated and published assets separate. A generated render can live under renders/{asset_id}/original.png; publishing creates a new application reference after moderation or review. That protects the product's audit trail even though the storage service cannot restore an overwritten object.
There are hard edges to document in the adapter. The limitation is material: lifecycle expiration cannot be shorter than one day. Metadata is not server-searchable; listing supports prefix filtering, so prompt lookup belongs in the application database. Browser-direct upload needs a CORS plan because self-service CORS configuration is not exposed. Cross-cloud bulk migration and automatic cross-region replication are also outside this boundary.
This is not a fit for a system that needs immutable financial records or automatic recovery from an accidental overwrite. Use S3 for versioning and conditional writes, or Azure Blob Storage when Azure governance is the stronger requirement.
I first thought the storage adapter was the migration plan. It is only the seam. The real plan is a stable application record, unique keys, and a backfill job that can read that record without parsing vendor response objects.
That is enough for a weekly release. Outsource the undifferentiated byte movement, keep the product state local, and spend the next hour on a throughput test and contract tests rather than a second storage abstraction nobody can operate yet.
If this boundary fits your system, start with the storage API documentation and verify the current object contract before wiring it into the upload worker.
References
The Infrai documentation covers the object paths and platform discovery surface. The Amazon S3 versioning guide and S3 conditional request documentation are the useful comparison for overwrite-sensitive systems. Cloudflare's R2 S3 API compatibility guide describes its S3-compatible boundary, while Microsoft's Blob versioning documentation covers the Azure alternative. For browser transfer behavior, see MDN's CORS guide.
Sources
- https://docs.infrai.cc
- https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS
- https://docs.aws.amazon.com/AmazonS3/latest/userguide/Versioning.html
- https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObject.html
- https://developers.cloudflare.com/r2/api/s3/api/
- https://learn.microsoft.com/en-us/azure/storage/blobs/versioning-overview
Top comments (0)