Short answer: make the Next.js route a small, auditable write coordinator, not a byte proxy. It should accept or generate the PNG on the server, derive a tenant's US or EU destination from policy, record a stable object key and write state, then mint a short-lived signed download link only after the object is confirmed. That design favors recovery and auditability over the tempting simplicity of latest.png.
The application is an e-commerce SaaS that stores AI-generated product images. The hard part isn't putting bytes in a bucket. It is knowing what happened when generation succeeds, storage succeeds, the database write doesn't, and the browser retries the whole request. I would design around that uncertainty first, then optimize delivery.
Test the failure boundary first.
What should be tested before shipping generated PNG storage?
The test matrix should cover the workflow, not just a successful PNG response:
- A US tenant cannot write or sign an EU key, and tenant A cannot read tenant B's prefix.
- A repeated generation id does not create a second render record or overwrite a different generation.
- A lost database write after a confirmed upload is recoverable by reconciliation.
- A non-PNG payload and an oversized image are rejected before storage.
- An expired signed link causes the client to request a new link rather than retrying the old URL forever.
- Logs contain the key and generation id where useful, but not the signed query string.
For observability, separate generation, upload, signing, download first-byte, retry, and orphan-cleanup measurements. Track counts by region and render state. I am not sure a single latency target is meaningful until the product knows whether users download once, refresh repeatedly, or share links; those patterns change the right expiry and cache policy.
What should a Next.js API route record before storing AI-generated PNGs?
Start with a render record, not a URL. It needs a tenant id, a generation id, the residency region, the object key, the expected content type, and an explicit state such as pending, stored, or failed. The signed download link is temporary output and should not be the identity of the image. Save the key; create the link when a client is authorized to view it.
The generation id should exist before the slow work begins. A retry carrying the same id can safely inspect or complete the same intended write. A new random id on every retry turns one button click into multiple model calls and multiple objects, which is a data-governance problem as much as a cost problem.
The route should resolve residency from trusted tenant policy. A request body saying eu must not override an account configured for the US, and an absent mapping must not silently select a default. Keep tenant prefixes in the key, such as tenants/acme/renders/gen_8f31.png, and never accept a client-supplied bucket or arbitrary key.
Here is the application boundary. The interface is deliberately generic; its implementation must follow the selected object-storage service's documented API and signing rules.
import { NextRequest, NextResponse } from "next/server"; type Region = "us" | "eu"; type RenderState = "pending" | "stored" | "failed"; interface ObjectStore { put(input: { bucket: string; key: string; body: Uint8Array; contentType: "image/png"; }): Promise<void>; signGet(input: { bucket: string; key: string; expiresInSeconds: number; }): Promise<string>; } declare const objectStore: ObjectStore; const buckets: Record<Region, string> = { us: "private-images-us", eu: "private-images-eu", }; export async function POST(request: NextRequest) { const user = await authenticate(request); if (!user) return NextResponse.json({ error: "unauthorized" }, { status: 401 }); const tenant = await loadTenant(user.tenantId); if (!tenant || !(tenant.region in buckets)) { return NextResponse.json({ error: "tenant region is not configured" }, { status: 409 }); } const generationId = await getOrCreateGenerationId(request); await saveRender({ tenantId: tenant.id, generationId, region: tenant.region, key: null, state: "pending" as RenderState, }); const png = await generatePng(request); const key = `tenants/${tenant.id}/renders/${generationId}.png`; await objectStore.put({ bucket: buckets[tenant.region], key, body: png, contentType: "image/png", }); await saveRender({ tenantId: tenant.id, generationId, region: tenant.region, key, state: "stored" as RenderState, }); const downloadUrl = await objectStore.signGet({ bucket: buckets[tenant.region], key, expiresInSeconds: 600, }); return NextResponse.json({ generationId, objectKey: key, downloadUrl }); } The important properties are the order and the boundary. Authentication, tenant policy, and key construction stay server-side. generatePng returns bytes; it does not hand the browser a temporary filesystem path. The media type and size should be validated before the write. A database adapter would usually make the pending-to-stored transition conditional on the generation id, so a duplicate request cannot quietly replace another tenant's record.
How do retries, regions, and signed links shape reliable image storage?
Treat each transition as observable. A pending render with no object key means generation or upload has not completed. A stored render with a key means the object write was confirmed. A failed render should retain enough metadata to explain the failure without retaining the signed URL. This state model gives a cleanup process something precise to inspect.
The most useful recovery case is an upload that completes just before the database connection disappears. The client receives an error and retries. With a stable generation id, the route can check the existing render, verify that its region and tenant prefix still match policy, and avoid producing a second object. If the record is pending and no object is present, it can continue. If an object is present but the record is incomplete, reconciliation can repair the record or mark the object for controlled cleanup. It should distinguish an abandoned upload from a pending model job, keep the original generation id in both records, and retain the reason for every cleanup decision so an operator can reconcile a disputed image without guessing which request produced it. I would measure these cases separately from ordinary success; one overall success rate hides them.
Regional storage also belongs in the audit trail. Record the selected region with the render, include it in structured logs, and make it immutable after the object is written. Moving an object between US and EU is a data movement event, not a cosmetic bucket rename. Your mileage may vary with the legal meaning of residency, so the application policy and the storage policy need a deliberate review rather than an assumption that a region label settles everything.
Signed links simplify delivery because the browser can fetch the object directly. They also have a sharp boundary: they are bearer capabilities until expiry. Keep their lifetime short enough for the product's download flow, never put the full link in ordinary logs, and return a fresh one when the old link expires. Cache-Control must be chosen with the privacy model in mind; a cache header that improves repeat reads can also make private media reusable by a cache for longer than intended.
Which storage workflow fits private, public, and regulated PNGs?
For private product renders and workspace previews, use a private object key plus an authorization check before signing. For a public gallery, a signed-link workflow may add needless friction because the product intentionally wants cacheable anonymous delivery. For regulated records, select retention, deletion, and access controls that match the requirement; a temporary link does not create immutable retention by itself.
Browser-direct uploads are another boundary. They can be appropriate when the application must avoid proxying large files, but they need a documented presigned-upload flow with explicit type, size, tenant-prefix, and origin constraints. Do not reuse a download link as an upload capability. Different verbs, different permissions, different tests.
The catch is that this route pattern is not suitable when every read must be revocable immediately, when users need permanent public URLs, or when the object-storage provider lacks the controls required by the residency policy. Stick with a simpler public delivery design for deliberately public assets, and choose a storage system with matching governance controls for regulated data. The decision is about the access model, not the label on the bucket.
This is the reliability rule I would ship: stable identity first, policy-derived placement second, confirmed object state third, signed delivery last. It keeps the Next.js route small while making failures explainable, which matters more than shaving a few lines from the handler.
