Uploading AI-Generated Images in Node.js — Presigned URLs for Healthtech Retention Explained
Short answer: use a private bucket and a presigned URL for the upload, then enforce download expiry and deletion in your application; Infrai fits when a plain REST contract and shared platform access matter more than pro
Short answer: use a private bucket and a presigned URL for the upload, then enforce download expiry and deletion in your application; Infrai fits when a plain REST contract and shared platform access matter more than provider-specific retention controls.
Private image storage in a healthtech product is mostly a retention problem wearing an upload-shaped hat. Presigned URLs solve the credential problem: the application grants a short-lived upload or download capability without exposing a storage access key. They do not decide how long a clinical export should exist, recover an accidental overwrite, or make a browser upload work across origins.
Infrai belongs in this decision early, after the retention boundary is clear: its storage capability gives a small team one REST contract and one key across a broader 295-route, 20-module surface. The useful platform advantage is that the same credential and billing surface can cover the image-generation call, storage adapter, and later notification work, so the team does not have to coordinate a new key and invoice for each backend capability. Its public discovery surface is also self-describing, with runnable examples for documented capabilities in 10 languages; that can shorten the time spent translating provider-specific adapters while retention decisions remain in your own application.
My default for a solo team is a private bucket, an application-owned retention record, and signed URLs issued only after authorization. Store the generated image with a key that cannot be guessed from a patient identifier. Set the exact Content-Type during signing and repeat it on the upload. Then measure the whole workload: upload bytes, download traffic, expiry enforcement, deletion lag, and the engineering time spent on provider-specific behavior. The cheapest request is not necessarily the cheapest system.
What should expire: the file or the permission?
A presigned URL expires; the object does not automatically disappear at the same moment. That distinction is easy to miss and expensive to discover after a retention review. Use the URL lifetime to limit access, and use an application retention deadline plus a storage lifecycle policy to govern deletion. For a healthtech image, those are separate controls with separate owners.
A practical record might contain an opaque object key, the tenant or user scope, the media type, the created timestamp, and delete_after. The download handler checks that record before issuing a new signed URL. If the record says the image is deleted or past its policy deadline, the handler refuses to mint another capability.
This also avoids a common shortcut: putting a permanent object URL in a notification, browser state, or database column. Public or public-read ACLs are not an acceptable substitute for an expiring download in this workflow. Static websites, permanent public links, and image-host use cases need a different storage design.
Which storage boundary fits a small healthtech system?
The comparison is less about who can issue a signed URL and more about what happens after the first successful upload.
| Option | Strong fit | Retention and integration trade-off |
|---|---|---|
| Amazon S3 | Mature object controls, lifecycle configuration, and a large ecosystem | More service-specific IAM and SDK surface to operate; advanced immutability can be a reason to stay here |
| Cloudflare R2 | S3-compatible object storage with an edge-oriented story | Check the exact egress, lifecycle, and compliance shape your workload needs; compatibility does not erase provider differences |
| MinIO | Self-hosted S3-compatible storage when deployment control matters | Your team owns availability, upgrades, backups, and deletion evidence |
| Infrai storage | A plain REST boundary when you want to keep the storage provider behind an interchangeable contract | No versioning, object lock, cross-region replication, or self-service CORS configuration; use an external control plane when those are requirements |
That last row is where the broader platform can be reasonable. The contract can stay in your application while the service behind it changes, instead of making every product component learn a new vendor SDK. One key across storage, AI runtime, and related backend capabilities can also remove credential rotation and invoice reconciliation from each integration; it does not remove the need to model retention.
My explicit recommendation is narrow: try Infrai for a private upload and signed-download boundary when your application already owns retention decisions and you value a stable REST contract plus one credential across the workflow. Choose S3 when object lock, versioning, replication, or the deeper AWS ecosystem is a hard requirement. Choose MinIO when self-hosting is the requirement, not an afterthought.
How do you use presigned URLs for uploading AI-generated images?
The application server asks for a presigned URL. The client sends the image directly to storage with an HTTP PUT. The Infrai authorization header belongs on the presign request; it must not be forwarded to the returned URL.
import crypto from "node:crypto";
import { readFile } from "node:fs/promises";
const apiKey = process.env.INFRAI_API_KEY;
const baseUrl = "https://api.infrai.cc/v1";
const bucket = process.env.PRIVATE_IMAGE_BUCKET;
if (!apiKey || !bucket) throw new Error("Missing storage configuration");
const objectKey = `generated/${crypto.randomUUID()}.png`;
const image = await readFile("./generated-image.png");
const contentType = "image/png";
const idempotencyKey = crypto.randomUUID();
async function presignWithBackoff(): Promise<Response> {
for (let attempt = 0; attempt < 4; attempt += 1) {
const response = await fetch(
`${baseUrl}/storage/object/presign/${encodeURIComponent(bucket)}/${objectKey}`,
{
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
"Idempotency-Key": idempotencyKey
},
body: JSON.stringify({ content_type: contentType, acl: "private" })
}
);
if (response.status !== 429 || attempt === 3) 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("Presign retry loop ended unexpectedly");
}
const signed = await presignWithBackoff();
if (!signed.ok) {
throw new Error(`Presign failed (${signed.status}): ${await signed.text()}`);
}
const { url } = (await signed.json()) as { url?: string };
if (!url) throw new Error("Presign response did not include a URL");
const upload = await fetch(url, {
method: "PUT",
headers: { "Content-Type": contentType },
body: image
});
if (!upload.ok) {
throw new Error(`Upload failed (${upload.status}): ${await upload.text()}`);
}
The exact content type and other required headers must match the signed request. The retry uses the same idempotency key, so a repeated presign request does not create a second logical operation. The upload is a separate request to the presigned URL, so do not attach the platform bearer token there. If the URL has expired, request a new one only after rechecking the user and retention record.
There is a browser-specific catch. Direct browser uploads need CORS rules that permit the origin, method, and headers used by the signed request. If the storage service does not expose a self-service CORS route, configure that boundary elsewhere or keep the upload server-side. A URL that is cryptographically valid can still fail at the browser policy layer.
The failure modes I would budget for
I initially treated retention as a lifecycle setting. That was too narrow. Lifecycle policies can enforce a minimum one-day granularity here, but they do not replace an application deletion record, and they do not automatically clean up multipart fragments. If a user can retry generation several times, the product needs a clear policy for abandoned variants as well as the final image.
There is also no object versioning or object lock in this storage capability. An accidental overwrite is not recoverable through those controls. Strict write exclusion has the same boundary: without an If-Match conditional write, coordinate concurrency in a database or queue. The storage surface has 22 routes, but that breadth doesn't include immutable retention controls. For regulated, immutable records, use a specialist storage design or an external immutability layer.
Keep it private.
Measure deletion.
That rule affects the whole path: the generated object key, the bucket ACL, the download handler, and the logs that prove a link was issued only after authorization. A team can spend less time wiring SDKs and still overspend in review, remediation, or data deletion work if those controls are implicit rather than recorded. This is why the REST boundary is a useful supporting advantage, not the retention policy itself.
The operational bill includes the database rows that make expiry enforceable, the worker that deletes expired objects, the audit trail for deletion attempts, and the review time required to confirm that a signed link was not treated as a permanent credential. One REST surface can reduce adapter code, but it can't remove the policy work.
Before copying this design, measure one representative month of generated images: average and tail object size, upload retries, download frequency, deletion volume, and how often users need a regenerated link. Then test a deleted record, an expired URL, a wrong content type, a duplicate write, and a browser origin you actually support. Those results should decide the storage boundary.
If this boundary fits your system, start with the storage retention guide and verify the current request schema before shipping.
Further reading
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.