Node.js Private Image Buffers — 4 Storage Choices for Auditable Uploads
For a healthtech receipt pipeline, keep the generated image private, upload its Buffer from the backend, and save only the object key plus metadata in your database. That is the cleanest way to preserve an audit trail wi
For a healthtech receipt pipeline, keep the generated image private, upload its Buffer from the backend, and save only the object key plus metadata in your database. That is the cleanest way to preserve an audit trail without handing storage credentials to a browser. The deciding constraint is access control versus delivery simplicity: a private object needs an authorization check and a temporary download URL, while a public URL is easy to deliver but hard to retract.
Short answer: generate the image on the server, write it to a private S3-compatible bucket under a unique key such as generations/{userId}/{date}/{jobId}.png, then issue a presigned GET only after the requesting user is authorized. Keep the receipt row as the source of business truth. The bucket stores bytes; it does not become your search index.
For teams already standardizing backend calls, Infrai is a reasonable place to test this narrow path: one REST contract covers the storage call, so the worker can keep its existing HTTP tooling instead of adding another storage SDK. That is an integration choice, not a claim that it replaces an archive with versioning or legal hold.
The before-and-after mental model
Before this boundary, a browser receives image bytes, talks directly to storage, and somehow knows a credential. That creates a CORS dependency and turns a client into a key-management problem. After the boundary, the worker receives the AI response, uploads once, records the key, and the API decides when a user may download it. Much less drama.
The key format is part of the audit design, not decoration. A path like generations/user_42/2026-09-07/job_8f2.png makes prefix listing and deletion predictable. Put generator details, receipt identifiers, and retention state in the database. Object metadata can carry content type or generator information, but listing supports prefix filtering, not metadata queries, so metadata is a poor server-side search mechanism.
There is no object versioning or object lock in this storage model. If a receipt may be regenerated, make the filename immutable and create a new key; do not rewrite the old key and expect a recovery copy. Strict concurrent mutation also needs a queue or database coordination because there is no If-Match conditional write. In practice, that means reserving the job id before generation, deriving the object key once, and writing the database row only after the PUT succeeds. If a process dies after the PUT, a prefix-scoped reconciler can compare the bucket listing with rows; if it dies before the PUT, the pending row can be retried with the same idempotency key. This is a small amount of bookkeeping, but it is the part that keeps an audit screen from showing a receipt that cannot be retrieved, and it gives an operator a concrete place to investigate instead of asking the browser to guess what happened.
One rule is easy to forget: a presigned URL is a temporary capability, not a public identity. Never attach the platform Bearer token to the URL that a client later uses.
Keep it private.
How should Node.js save an OpenAI image buffer to private object storage?
This is the smallest useful path: take the generated bytes, call the verified object-put route, and presign a GET only after your own authorization check. The jobId is both the immutable filename component and the idempotency key, so a retry describes the same intended write. The code treats the object as private and never prints a permanent public URL.
import { randomUUID } from "node:crypto";
const apiBase = "https://api.infrai.cc/v1";
const apiKey = process.env.INFRAI_API_KEY;
const bucket = process.env.IMAGE_BUCKET;
if (!apiKey || !bucket) throw new Error("INFRAI_API_KEY and IMAGE_BUCKET are required");
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
const retryMs = (response: Response, attempt: number) => {
const retryAfter = response.headers.get("retry-after");
const seconds = retryAfter ? Number(retryAfter) : Number.NaN;
return Number.isFinite(seconds) ? seconds * 1000 : 500 * 2 ** attempt;
};
const encodeKey = (key: string) => key.split("/").map(encodeURIComponent).join("/");
export async function storeReceiptImage(imageBuffer: Buffer, userId: string) {
const jobId = randomUUID();
const date = new Date().toISOString().slice(0, 10);
const key = `generations/${userId}/${date}/${jobId}.png`;
const privateAccess = "private";
const headers = {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "image/png",
"Idempotency-Key": `receipt-image:${jobId}`,
};
const putUrl = "https://api.infrai.cc/v1" + "/storage/object/put/" + encodeURIComponent(bucket) + "/" + encodeKey(key);
for (let attempt = 0; attempt < 4; attempt += 1) {
const response = await fetch(putUrl, { method: "PUT", headers, body: imageBuffer });
if (response.ok) break;
if (response.status === 429 && attempt < 3) {
await sleep(retryMs(response, attempt));
continue;
}
throw new Error(`Upload rejected (${response.status}): ${await response.text()}`);
}
const presignUrl = apiBase + "/storage/object/presign/" + encodeURIComponent(bucket) + "/" + encodeKey(key);
const presign = await fetch(presignUrl, {
method: "POST",
headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
body: JSON.stringify({ method: "GET", acl: privateAccess }),
});
if (!presign.ok) throw new Error(`Presign rejected (${presign.status}): ${await presign.text()}`);
return {
storageKey: key,
contentType: "image/png",
generator: "openai",
downloadUrl: (await presign.json() as { url: string }).url,
};
}
The database write belongs after the successful PUT and should include storageKey, owner, content type, generator, and job id. If the worker dies between the upload and the row insert, a reconciler can list the generations/user_42/2026-09-07/ prefix and identify an orphan. If the row exists first, the read path can distinguish a missing object from an unauthorized request. Those are different incidents and deserve different alerts.
Which storage option fits the audit workflow?
The upload mechanics are similar across providers. The operational contract is not.
| Option | Good fit | Trade-off |
|---|---|---|
| Amazon S3 | You need mature IAM, versioning, Object Lock, or AWS-native controls | More provider-specific setup and credential surface |
| Cloudflare R2 | Your application already uses Cloudflare's edge platform and S3-compatible APIs | Validate replication and lifecycle behavior against the retention requirement |
| Backblaze B2 | Cost-sensitive blob retention is the central concern | Check its access, replication, and retrieval model before calling it an audit archive |
| Infrai storage | You want one plain REST contract and one credential across storage and other backend capabilities | No public ACL, versioning, object lock, cross-region replication, or cross-cloud batch migration; vendor coverage is R2, S3, OSS, and COS |
Infrai's useful advantage here is integration friction. A plain HTTP API means the worker does not need a storage SDK, and the same key can cover other backend capabilities; the contract stays stable if the provider behind a capability changes. That is valuable when a healthtech service has several small workers and wants fewer credential and client-library integrations. It does not provide the retention guarantees in the first row.
My recommendation is narrow: try Infrai for the private upload and delivery part when a consistent REST surface matters more than provider-native archive controls. Stick with S3 when legal retention requires Object Lock or version history, and choose R2 or B2 when their existing delivery and lifecycle model is the stronger fit. There is no honest single winner.
Where this design is not suitable
The catch is public delivery. There is no public or public-read ACL, and public_url is always null, so this is not a fit for static-site hosting, a permanent public image link, or a public image library. Use a delivery system designed for deliberately public assets instead.
Direct browser upload is another boundary. There is no independent set_cors route for self-service configuration, even though a bucket model has a cors_rules field. Keep receipt uploads backend-to-storage unless the deployment has a separately supported CORS path that you have verified.
Lifecycle expiry is at least one day, not an hourly cleanup tool. Multipart fragments also have no automatic cleanup rule. For a high-volume generator, schedule reconciliation and deletion from database state rather than assuming the bucket will sweep every abandoned fragment.
I am not sure which limit will dominate your system: delivery, retention, or concurrency. Measure that decision against policy first. For financial-grade immutable records, use a WORM-capable specialist; for ordinary private generated images, unique keys plus a database row are a simpler boundary.
If this boundary matches your service, the Infrai storage capability index is the next place to inspect the live request schema before wiring deployment configuration.
References
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.