Short answer: authorize the export in the Next.js API route, select the tenant's storage region on the server, and return a short-lived signed download URL for one private PDF object. The application should move identity and policy; object storage should move the bytes.
That split won my evaluation constraint: a download request must never expose another tenant's export, yet the app runtime must not proxy a 180 MB catalog PDF. The deceptively simple alternative was an application endpoint that opened the object and streamed it to the browser. It kept access control in one place, but it also made every byte consume application bandwidth and runtime capacity. A public bucket avoided that load while throwing away the boundary the route was meant to enforce.
There is a catch. A signed URL is a bearer capability until it expires. If access must be revoked immediately after issuance, or every byte must pass a fresh policy check, an app-mediated download or an authenticated delivery layer is a better fit. Don't stretch a short lifetime into a claim that the link cannot be shared.
The same boundary appears in e-commerce uploads. Product videos can go directly from the browser to a private object store after the app authorizes a key and content constraints. This article keeps the focused example on PDF export downloads, but the decision axis is identical: centralized access control versus simple, direct delivery.
How can a Next.js API route contain private PDF signed URL exposure?
Treat the route as a capability mint, not as a file server. The browser presents an authenticated session and an opaque export ID. The route resolves that ID within the current tenant, verifies that the export is ready, derives the object key and approved region from server-side records, and asks the matching regional signer for a read URL. The client must never submit a bucket, object key, tenant ID, or region that the server trusts directly.
Order matters. Authentication comes first, tenant-scoped lookup second, state validation third, and signing last. If lookup is performed by a globally unique export ID before tenant scoping, the route can accidentally turn record existence into an oracle even when it refuses the eventual download. Returning the same not-found response for an absent export and an export owned by a different tenant keeps that detail out of the public contract.
The object key should carry enough structure for operations, but it is not an authorization mechanism. A shape such as tenants/{tenantId}/exports/{exportId}.pdf makes lifecycle rules and incident review easier. It doesn't replace the database check. Object names leak into logs, signed query strings, and browser history, so keep customer names, email addresses, and order contents out of them.
Region selection belongs to the export record as well. An EU tenant's request should resolve to an EU object reference because the record says so, not because the browser sent region=eu. This makes the route deterministic and prevents a caller from probing a second region. It also gives migration code one controlled place to change the mapping later.
Fail closed.
The byte path should follow the revocation requirement, not fashion:
| Delivery path | App carries file bytes | Access decision | Main limitation |
|---|---|---|---|
| Authenticated app proxy | Yes | On every request | Runtime bandwidth and duration grow with the file |
| Short-lived signed object URL | No | When the URL is issued | The capability remains usable until expiry |
| Authenticated delivery layer | No | At the delivery edge | Adds another policy system to operate |
For response behavior, avoid caching the API route's authorization result in a shared cache. Cache-Control: private, no-store expresses that the response is specific to one user and should not be stored. MDN distinguishes shared caches from private browser caches and documents no-store as the directive that asks caches not to store the response. That header does not revoke the object-store capability; its lifetime is still enforced by the signer.
The bandwidth bill is an architectural trace
The useful abstraction is small: tenant-scoped export lookup plus a regional signing interface. Keep provider credentials and SDK types behind that interface. The route then remains boring when storage placement changes, which matters more to a solo team than a grand storage abstraction that models operations the product never performs.
type Region = "us" | "eu";
type Session = {
userId: string;
tenantId: string;
};
type ExportRecord = {
id: string;
tenantId: string;
status: "pending" | "ready" | "expired";
region: Region;
bucket: string;
objectKey: string;
};
type Dependencies = {
requireSession(request: Request): Promise<Session>;
findExport(tenantId: string, exportId: string): Promise<ExportRecord | null>;
signDownload(input: {
region: Region;
bucket: string;
objectKey: string;
expiresInSeconds: number;
responseContentType: "application/pdf";
responseContentDisposition: string;
}): Promise<string>;
};
const safeFilename = (exportId: string): string =>
`catalog-${exportId.replace(/[^a-zA-Z0-9_-]/g, "_")}.pdf`;
export const makeDownloadHandler = (deps: Dependencies) =>
async function GET(
request: Request,
context: { params: Promise<{ exportId: string }> },
): Promise<Response> {
const session = await deps.requireSession(request);
const { exportId } = await context.params;
const record = await deps.findExport(session.tenantId, exportId);
if (!record || record.tenantId !== session.tenantId) {
return Response.json({ error: "Export not found" }, { status: 404 });
}
if (record.status !== "ready") {
return Response.json({ error: "Export is not ready" }, { status: 409 });
}
const url = await deps.signDownload({
region: record.region,
bucket: record.bucket,
objectKey: record.objectKey,
expiresInSeconds: 60,
responseContentType: "application/pdf",
responseContentDisposition: `attachment; filename="${safeFilename(record.id)}"`,
});
return Response.json(
{ url, expiresInSeconds: 60 },
{ headers: { "Cache-Control": "private, no-store" } },
);
};
This example returns JSON instead of redirecting. That gives the browser an explicit expiry value and lets the UI request a fresh capability if the user waits too long before clicking. A redirect is also defensible when the route is entered only by an immediate navigation. Pick one contract and test it; don't mix redirect behavior, JSON parsing, and retry logic across clients.
Sixty seconds is an example policy, not a universal optimum. The right value must cover the delay between issuance and the object store receiving the request, including slow devices and queued browser work. It need not cover the entire transfer if the storage service validates the signature when accepting the request, but that behavior must be confirmed for the chosen signer. I'm not sure a generic number can settle this because the evidence is deployment-specific: measure issuance-to-first-byte delay at the tail, then add a deliberate margin.
The signer should set download disposition and PDF content type as part of the signed request when the storage implementation supports response overrides. Keep the filename derived from a server-owned identifier and sanitize it before placing it in a header value. The route does not reveal the storage location until every policy check has passed.
Failure drills matter more than happy-path tests
Walk one export through the ugly path before trusting the happy one. An authenticated user is not automatically authorized for every export ID they can guess or obtain from an old log, so repository methods should require both tenant ID and export ID rather than loading globally and relying on a later comparison; the explicit comparison in the example is defense in depth, not the primary filter. Now let the user leave the tab open. The link can expire between rendering and clicking, and the UI should respond to denial from storage by confirming the session and asking the API route for a new link, not by repeatedly retrying the same expired URL. Keep that refresh bounded so a bad client does not mint capabilities in a loop. Next, inspect every place the JSON can travel: shared caches, analytics payloads, error trackers, browser history, and verbose request logs can all extend the audience of the temporary secret. Redact query strings from downstream download logs, avoid putting the URL in analytics events, and keep the API response out of shared storage; private, no-store is one layer, not an observability policy. Finally, test the deployed route with a PDF larger than the platform's comfortable response size and inspect application egress. The API response should remain tiny while the object store accounts for the file transfer. In the upload variant, the same check proves that a 600 MB product video travels browser-to-storage rather than browser-to-app-to-storage. One exercise covers ownership, expiry, secret handling, and the actual byte path, which is far more useful than a test that merely sees a URL-shaped string.
Logs leak.
Regional placement needs negative tests. Create two fixtures with the same human-facing filename, one in each region, and assert that a US tenant can mint only the US object's capability while an EU tenant can mint only the EU object's capability. Also test an export ID owned by a different tenant, a pending export, an expired export, a malformed ID, and a link used after its lifetime. The exact storage error response varies by implementation, so assert denial rather than coupling the application test to one vendor's error body.
Direct delivery is not suitable when the download must stop the instant an administrator revokes access, when policy must be reevaluated during a long transfer, or when content inspection must occur inline on every request. Stick with an authenticated proxy or a delivery service that can enforce those controls. Direct object delivery is a strong default when authorization at issuance is sufficient and avoiding application data transfer is the primary operational goal.
Operational evidence decides whether direct delivery survives
Start with four signals: capability-mint latency, issuance-to-first-byte latency, refresh rate for expired links, and application egress bytes per completed export. Break the first two down by US and EU placement. A regional average can hide the exact tail that makes a 60-second policy annoying on slow clients.
Add authorization counters without high-cardinality object keys. Count not-found, not-ready, and successful mint outcomes by region, while keeping tenant IDs out of metric labels. Audit events can retain a controlled tenant and export reference under the application's retention policy, but ordinary metrics should stay aggregatable and cheap.
Cost deserves measurement, not a headline. Compare stored bytes, download bytes, request counts, and any application egress that remains after deployment. Provider pricing pages can help populate the model, but published prices and included allowances can change. Recheck them for the actual region and traffic pattern before committing to a forecast.
Finally, deploy the signer boundary before introducing a second storage implementation. A fake signer can make unit tests deterministic, while an integration test in each real region proves that response headers, expiry, and object permissions agree with the route's assumptions. The point is not maximal portability. It is containing credentials, policy, and regional choice so the rest of the application doesn't learn how a signed URL is assembled.
Measure first. Then shorten or lengthen the capability lifetime, change the redirect contract, or choose app-mediated delivery based on evidence from the workload rather than a copied default.
Top comments (1)
One failure case I would add to the route tests is a
readyexport whose object is deleted between the tenant-scoped lookup and the browser GET. Minting another URL cannot repair that state; an automatic refresh loop would only create more capabilities.I would distinguish an expired-signature denial from a confirmed storage
NotFound. The former can trigger one bounded capability refresh. The latter should stop the retry path and send the export to reconciliation rather than leaving the metadata indefinitelyready. The exact HTTP mapping is provider-specific, so this seems best tested against the deployed storage boundary rather than hard-coding one vendor’s error body.