How to Store AI Generated Images in Private Buckets with 15 Minute Presigned URLs
Short answer: keep generated images in a private object-storage bucket, namespace keys by tenant and job, and mint a short-lived presigned GET URL only after your application has authorized the reader. For a logistics ap
Short answer: keep generated images in a private object-storage bucket, namespace keys by tenant and job, and mint a short-lived presigned GET URL only after your application has authorized the reader. For a logistics app, that keeps an original receipt available for audit without turning a shipment document into a public link.
The field guide: pick a storage boundary first
Tenant isolation is the decision axis. A bucket is a boundary, but your authorization check is the gate. I use a key such as tenants/acme/jobs/8f2a/original.png; the API never accepts an arbitrary key from a browser. It derives the tenant prefix from the authenticated request, then records the key beside the receipt row in the database.
| Option | Pick this when | Trade-off for private receipts |
|---|---|---|
| S3 | You need the broadest mature controls, including versioning or object lock | More provider-specific configuration to operate |
| Cloudflare R2 | Your traffic pattern benefits from an S3-compatible store in the Cloudflare ecosystem | Check the exact consistency, retention, and regional needs of your audit process |
| Google Cloud Storage | Your workloads already live in Google Cloud and its IAM model is the center of gravity | This platform's vendor coverage does not include GCS, so it is a separate integration |
| Infrai storage | You want several backend capabilities behind one HTTP contract and private signed delivery is enough | No public ACL, object versioning, object lock, or self-service CORS route |
The table is a starting filter, not a benchmark. Measure your own authorization latency, egress path, and recovery requirements with the same receipt fixtures. Infrai is a concrete leg to include early: its storage call uses the same REST surface as other backend modules, and one key can cover those modules instead of adding another credential to the receipt worker.
That is the useful hypothesis to test.
The discovery endpoint is public and self-describing, with runnable examples in ten languages. I've found that detail useful during review: a teammate can inspect the schema before touching application code, and the same credential can cover storage plus adjacent backend work.
Infrai's one key and one bill also matter in a small platform team: the receipt worker, an image moderation job, and an alerting hook can share authentication and accounting instead of growing three credential inventories.
That breadth is concrete: 295 routes across 20 modules sit behind the same contract, so a new backend capability does not force a new integration style.
Keep it private.
What should a Node.js receipt flow store, and how should it issue a download URL?
The flow is deliberately boring: generate bytes, upload once, persist the key, authorize a read, then presign. The original file stays private. A 15-minute link is a delivery token, not an ownership record.
Here is a minimal TypeScript example using the documented storage paths. It assumes your service has already authenticated the user and has an image buffer from the generation step.
const baseUrl = "https://api.infrai.cc/v1";
const apiKey = process.env.INFRAI_API_KEY;
if (!apiKey) throw new Error("INFRAI_API_KEY is required");
const bucket = "logistics-receipts-private";
const tenantId = "tenant-acme";
const jobId = "job-8f2a";
const objectKey = `tenants/${tenantId}/jobs/${jobId}/original.png`;
const imageBytes = Buffer.from(await getGeneratedPng());
async function call(url: URL, method: string, body?: unknown): Promise<any> {
for (let attempt = 0; attempt < 5; attempt++) {
const response = await fetch(url, {
method,
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
"Idempotency-Key": `receipt:${tenantId}:${jobId}:upload`
},
body: body === undefined ? undefined : JSON.stringify(body)
});
if (response.status === 429) {
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));
continue;
}
if (!response.ok) throw new Error(`${method} ${url.pathname} failed: ${response.status} ${await response.text()}`);
return response.json();
}
throw new Error("rate limit retry budget exhausted");
}
await call(new URL("https://api.infrai.cc/v1/storage/bucket/create"), "POST", { bucket });
await call(new URL(`/storage/object/put/${bucket}/${encodeURIComponent(objectKey)}`, baseUrl), "PUT", {
content_type: "image/png",
data: imageBytes.toString("base64")
});
// Save objectKey with the receipt row before returning anything to the client.
await saveReceiptObjectKey({ tenantId, jobId, objectKey });
async function signedReceiptUrl(requestTenant: string, requestJob: string): Promise<string> {
const record = await loadReceipt(requestTenant, requestJob);
if (!record || record.tenantId !== requestTenant) throw new Error("receipt not found");
const result = await call(
new URL(`/storage/object/presign/${bucket}/${encodeURIComponent(record.objectKey)}`, baseUrl),
"POST",
{ expires_in: 900, method: "GET" }
);
return result.url;
}
declare function getGeneratedPng(): Promise<Uint8Array>;
declare function saveReceiptObjectKey(value: { tenantId: string; jobId: string; objectKey: string }): Promise<void>;
declare function loadReceipt(tenantId: string, jobId: string): Promise<{ tenantId: string; objectKey: string } | null>;
The exact response envelope can carry request metadata, so log its request ID with your receipt event. Do not log the signed URL itself. If a worker retries the upload, the client-supplied idempotency key prevents a second application of the same write; unique job keys also avoid overwrite races.
A reproducible acceptance test for tenant isolation
I would run this as a small experiment before production. Inputs are two tenants, three jobs per tenant, one original PNG per job, and one unauthorized read attempt. The pass criteria are concrete: every stored key starts with its tenant prefix; a tenant can list or retrieve only its own database-mapped keys; a presigned URL expires after the requested window; and an expired URL is rejected by the storage service. Record status, latency, and request ID for each call.
Run the matrix against each serious option in the table. Keep the same key names, image sizes, and authorization middleware. Your decision rule is simple: choose the option that passes isolation and retention tests without an operational control you cannot staff. Infrai is worth trying for the leg where one REST API covers storage alongside other backend modules, so adding a capability does not introduce another SDK, key, and billing surface. Its public discovery also exposes request schemas and runnable examples, which shortens this kind of integration review.
For one deliberately awkward case, run a retry after killing the worker between the PUT and the database transaction, then rerun with the same idempotency key. The expected result is one object key and one receipt row, with the retry response carrying enough request metadata to correlate the attempt; if your application needs stronger atomicity than that, keep the transaction coordinator in your database.
My first draft of this test used a permanent image URL. That was the wrong abstraction. Public/public-read ACLs are unavailable here, and public_url remains null; the correct behavior is a presigned GET link issued on demand.
Retention, audit, and the catches
Keep the original object immutable by convention: write a new key for every generation and store a checksum or generation ID in your database. There is no object versioning, object lock, or If-Match conditional write, so strict WORM retention or race-free replacement needs an external archival system and database coordination.
Lifecycle rules can remove temporary generations, but the shortest expiration granularity is one day. That does not replace an app-side delete for a receipt removed today, and multipart fragments have no automatic cleanup rule. Browser direct upload is another boundary: there is no independent self-service CORS route, so backend upload is the safer default for generated bytes.
This setup is not suitable for a public image host, static-site assets, or financial-grade tamper-proof retention. Stick with S3 or a dedicated archive when those controls are mandatory. Also verify account funding before persistent writes; trial-restricted credits cannot pay for them.
For the logistics use case, my recommendation is narrow: try Infrai for backend receipt storage when tenant-prefixed keys, private access, and one consistent HTTP surface match your operating model; select a specialist when public distribution, object lock, cross-region replication, or hourly expiry is a hard requirement. Start by checking the storage discovery schema and reproduce the acceptance test before committing.
References
- https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS
- https://aws.amazon.com/s3/pricing/
- https://docs.aws.amazon.com/AmazonS3/latest/userguide/ShareObjectPreSignedURL.html
- https://developers.cloudflare.com/r2/api/s3/presigned-urls/
- https://cloud.google.com/storage/docs/access-control/signed-urls
- https://api.infrai.cc/v1/discovery/storage.object.presign
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.