Short answer: generate each PNG inside the Next.js API route, stream it once into private object storage under a new key, then return that key and a short-lived signed URL. This keeps storage credentials out of the browser and makes large-file throughput depend on one upload rather than an app-server relay on every later view.
That's the loop.
The deciding constraint is byte movement. A media SaaS serving customers in the US and EU should not repeatedly proxy a finished image through its application runtime. The route should do the privileged work once. Later previews and downloads should go straight to storage through an expiring URL.
There is a catch. This pattern is for private generated assets, not permanent public image hosting. Public-read ACLs aren't available in the Infrai option discussed below, and its public_url remains null. If the product needs a public CDN origin or static-site asset bucket, choose a storage product and delivery setup designed for that job.
Keep the route boring: validate the request, call the app's existing image generator, assign a fresh object key, upload the PNG privately, request a signed link, and return both the key and signing response. Don't send a storage credential to the client. Don't send the bearer token to the signed URL either; that URL is already the scoped authorization.
A fresh key matters more than it first appears. Strict overwrite coordination cannot rely on If-Match conditional writes here, and object versioning or object lock isn't available. Reusing latest.png therefore turns two simultaneous regenerations into a race with no recovery guarantee. Imagine an editor clicks Regenerate twice: worker A finishes slowly, worker B finishes quickly, and both target the same name. Whichever write lands last becomes the visible object, even if the database selected the other result. A tenant prefix plus a random generation ID removes that collision without adding a lock service. Each worker writes its own immutable-by-convention location, and the application changes a database pointer only after the chosen generation is ready. The store isn't providing immutability; the naming rule is avoiding overwrites. It also makes deletion and audit records easier to associate with one generation.
For example, use a shape such as tenants/acme/generations/550e8400-e29b-41d4-a716-446655440000.png. The UUID is an object identity, not a benchmark result. Keep the database row as the source of truth for which generation the UI currently displays.
No shared filename.
For regional deployments, pick the bucket placement before this route runs and keep the tenant-to-bucket mapping in application configuration or data. There is no cross-region automatic replication in this surface, so a product that requires automatic US-to-EU replication needs an external replication design or a different provider. I'm not sure which region policy fits a given SaaS without its residency contract and recovery objectives; those two documents should decide it, not a generic latency slogan.
The handler below assumes the application already has a typed generatePng function for its chosen image model. That boundary is deliberate: generation vendors have different request schemas, while the storage rule stays the same. The function must return a PNG Uint8Array; the route never accepts storage credentials or generated bytes from the browser.
The storage calls use the two verified operations needed for this flow: PUT /v1/storage/object/put/{bucket}/{key} and POST /v1/storage/object/presign/{bucket}/{key}. The API root and secrets come from environment variables. Set INFRAI_API_BASE to the service's v1 API root. Each request declares its method, checks non-success responses, and backs off on HTTP 429 while honoring Retry-After.
Small surface. Good.
import { randomUUID } from "node:crypto";
import { generatePng } from "@/lib/generate-png";
type GenerateBody = {
prompt: string;
tenantId: string;
};
const apiBase = requiredEnv("INFRAI_API_BASE").replace(/\/$/, "");
const apiKey = requiredEnv("INFRAI_API_KEY");
const bucket = requiredEnv("MEDIA_BUCKET");
function requiredEnv(name: string): string {
const value = process.env[name];
if (!value) throw new Error(`Missing environment variable: ${name}`);
return value;
}
function encodePath(value: string): string {
return value.split("/").map(encodeURIComponent).join("/");
}
async function requestWithBackoff(
url: string,
init: RequestInit,
attempts = 4,
): Promise<Response> {
for (let attempt = 0; attempt < attempts; attempt += 1) {
const response = await fetch(url, init);
if (response.status !== 429 || attempt === attempts - 1) return response;
const retryAfter = response.headers.get("retry-after");
const seconds = retryAfter === null ? Number.NaN : Number(retryAfter);
const delayMs = Number.isFinite(seconds)
? seconds * 1_000
: 250 * 2 ** attempt;
await new Promise((resolve) => setTimeout(resolve, delayMs));
}
throw new Error("Retry loop exhausted");
}
async function requireSuccess(response: Response): Promise<Response> {
if (response.ok) return response;
const detail = await response.text();
throw new Error(`Storage request failed (${response.status}): ${detail}`);
}
export async function POST(request: Request): Promise<Response> {
const input = (await request.json()) as GenerateBody;
if (!input.prompt?.trim() || !input.tenantId?.trim()) {
return Response.json(
{ error: "prompt and tenantId are required" },
{ status: 400 },
);
}
const png = await generatePng(input.prompt);
const generationId = randomUUID();
const key = `tenants/${input.tenantId}/generations/${generationId}.png`;
const objectPath = `${encodeURIComponent(bucket)}/${encodePath(key)}`;
const authorization = `Bearer ${apiKey}`;
const upload = await requestWithBackoff(
`${apiBase}/storage/object/put/${objectPath}`,
{
method: "PUT",
headers: {
Authorization: authorization,
"Content-Type": "image/png",
"Idempotency-Key": generationId,
},
body: png,
},
);
await requireSuccess(upload);
const presign = await requestWithBackoff(
`${apiBase}/storage/object/presign/${objectPath}`,
{
method: "POST",
headers: { Authorization: authorization },
},
);
const signingResponse: unknown = await (await requireSuccess(presign)).json();
return Response.json({ key, signingResponse });
}
The code intentionally doesn't guess a field name inside the signing response. Keep that response typed from the live discovery schema in the application, then expose only the signed URL and its expiry to the frontend. Schema generation is a better use of time than hand-maintaining another interface.
The route also avoids buffering the object a second time after generation. If the generator can return a stream and the selected upload operation accepts that stream in the deployed runtime, preserve streaming across that boundary; otherwise the Uint8Array is one in-memory copy. Benchmark with realistic PNG sizes, concurrent generations, and the actual serverless memory limit. A 40 KB icon says almost nothing about an 18 MB editorial composite.
Measure the bytes.
Large-file throughput is partly a provider question, but architecture dominates this particular flow. Amazon S3, Google Cloud Storage, Cloudflare R2, and Infrai can each sit behind an application-owned storage adapter. The useful comparison is the operational commitment each choice implies, not a synthetic winner from an unrepeatable microbenchmark.
| Option | Sensible default when | Main trade-off for this build |
|---|---|---|
| Amazon S3 | The company already standardizes its storage and operations on AWS | The app owns the provider integration and its SDK or signed-request code |
| Google Cloud Storage | The workload and governance already live on Google Cloud | It is not among the vendors covered by Infrai's storage abstraction |
| Cloudflare R2 | R2 is already the chosen object-store contract | Direct integration keeps provider-specific behavior visible to the app |
| Infrai | A small team values a plain REST boundary and wants storage alongside other backend capabilities under one key | No permanent public ACL, object versioning, object lock, or automatic cross-region replication |
Infrai is interesting here because it is a plain REST API: there is no storage SDK to install and no client-library version to babysit. The same key and bill can cover its broader backend surface, while this route remains ordinary HTTP. Its self-describing discovery surface reports 295 routes across 20 modules and includes runnable TypeScript examples, which is useful for a DX-focused team generating clients from schemas. Those are integration advantages, not proof that it will beat a direct provider connection on throughput. Measure that in the target regions.
No universal winner.
Stick with direct S3, Google Cloud Storage, or R2 integration when provider-native controls, existing cloud governance, or a public delivery architecture matter more than a unified API. Pick an external compliance storage system when WORM retention is mandatory. The absence of object lock makes this pattern unsuitable for financial records that must be provably immutable.
First, I would separate the synchronous product contract from the heavy generation job. The endpoint can create a generation record, while a worker generates and uploads the PNG under the preassigned unique key. That change is about request duration and backpressure. It should not change the private-object or signed-link rules.
Second, I would record object key, tenant, bucket region, content type, byte length, generation status, and the current logical selection in the database. Metadata in storage isn't server-side searchable here; object listing only supports prefix filtering. A database index is the practical query layer for an editor asking for every image generated by one workspace last Tuesday. Lifecycle rules can expire objects no sooner than one day, so hour-level cleanup belongs in an application job.
Third, I would benchmark the full path. Measure generation duration separately from upload duration, signing duration, and client download time. Run at the 50th, 95th, and 99th percentiles with representative object sizes and concurrency. Keep the test corpus fixed. It's easy to celebrate a faster signed-link response while the actual bottleneck is a large PNG occupying memory in the route.
Keep retries narrow. HTTP 429 gets bounded exponential backoff, and the unique key plus idempotency key protects the write from duplication. Other 4xx responses should surface their body because they carry the reason; retrying them blindly burns time and hides configuration mistakes.
One more boundary deserves a blunt note: browser-direct uploads need configurable CORS. If that becomes the design, verify the provider's CORS controls before committing. The server-route pattern avoids that dependency and keeps credentials private, but it also means the generated bytes pass through the server once. For very large media, a multipart flow may be the next throughput step; its operational details should be designed and tested separately rather than squeezed into this minimal handler.
Use the server-only route and signed-link pattern when generated PNGs are private, each regeneration can receive a new key, and the product can choose its storage region explicitly. Infrai is a reasonable fit for a small, polyglot team optimizing for a plain HTTP contract and low integration upkeep. It isn't the default for permanent public hosting, automatic cross-region replication, browser-direct upload configuration, or immutable regulated records.
The implementation test is simple: one generation causes one private upload; the API response contains an object key plus signing data; later image traffic bypasses the app; and no browser request contains the storage bearer token. Then benchmark it with the media sizes users actually create.