Use short-lived signed links only after the API has authorized the export, selected its fixed storage region, and confirmed that retention has not expired. The browser can then move a large PDF or supporting media directly to or from object storage; the application handles control data, never the file bytes. The hard part isn't signing. It is making deletion state observable enough that an expired fintech export cannot quietly remain downloadable.
| Delivery model | Pick this when | Retention consequence | Main operational signal |
|---|---|---|---|
| Application proxy | Files are small or every byte must pass an inspection layer | One enforcement point, but application capacity scales with transfer volume | Proxy duration and aborted-transfer rate |
| Signed object-storage URL | Large exports and evidence media should bypass the application | The API must check policy before every signature, while storage lifecycle rules provide a backstop | Sign decisions by region and policy result |
| Managed download gateway | Central policy or detailed download accounting outweighs another network hop | Gateway policy becomes part of the deletion control | Allowed, denied, and expired requests by tenant |
The default here is the signed-URL model. Keep the object private, keep its region immutable, and treat each URL as a brief capability rather than a durable download address.
Pick the delivery model from the enforcement point
An application proxy is easy to reason about: authenticate, read the object, stream it to the browser. It is also the wrong data path when a quarterly audit bundle contains a PDF plus hundreds of megabytes of recorded evidence. Each download occupies application bandwidth and a live execution context. Stick with the proxy when content inspection must happen during each read, or when the storage signer cannot express the response constraints your policy requires.
A signed URL moves the data plane away from the application. The route still owns the consequential decisions: tenant membership, export status, allowed purpose, residency, retention deadline, and requested filename. It returns a location only after those checks pass. This is the useful before/after: before, the route is a file server; after, it is a capability issuer with a small, testable decision surface.
The catch is revocation. A URL already issued may remain usable until its own expiry even if an operator deletes the database row one second later. That makes this model unsuitable when access must stop instantly. Use a gateway or proxy for immediate per-request revocation, and accept the extra hop deliberately.
A managed gateway occupies the middle ground. It can evaluate live policy on every request and centralize audit events, but it adds a component whose availability and latency now sit in the download path. There isn't one universal winner. Retention semantics choose the architecture.
How should a Next.js API route issue private PDF export signed download URLs?
The route should authorize a business record, not accept an arbitrary object key. That distinction closes a common tenant-isolation hole: a caller can guess or copy a key, but cannot make the server sign it unless the export row belongs to the caller's tenant. The row also carries the region selected when the export was created. Don't infer region from the request, latency, or current user location; moving the signing decision does not move stored data. Picture the flow in words. Browser to API: “May this member download export exp_7F3?” API to policy store: “Does it belong to this tenant, is it ready, and is deleteAfter still in the future?” API to the regional signer: “Issue a short capability for this exact key and filename.” Browser to object storage: “Redeem that capability.” The PDF bytes take the last path only. Use distinct outcomes at the control boundary. Return 404 when the export is absent or belongs to another tenant, so the route doesn't disclose cross-tenant identifiers. Return 409 while a legitimate export is still being generated. Return 410 once retention has elapsed or deletion is recorded. A 403 is appropriate for an authenticated tenant member who lacks the download permission. Those stable classes are much easier to alert on than a pile of generic failures. Cache behavior matters too. The JSON response contains a bearer-like URL, so send Cache-Control: private, no-store. private keeps a shared cache from storing the response, while no-store asks caches not to store it at all; the MDN reference documents the directives and their scope. The object response should use the filename and content disposition that were bound during signing, not query values copied blindly from the browser. Short expiry is useful, but “short” belongs in configuration. Five minutes may fit a normal PDF and fail for a slow connection or a large evidence package. I'm not sure a single duration works across mobile clients and corporate networks; download-duration telemetry, object sizes, and retry rates should settle that choice. Keep the upper bound below the remaining retention window.
Implement the control plane, not a byte proxy
The following route uses generic repositories and a regional signer interface. That keeps the example focused on the boundary that matters. The concrete signer can target any object store that supports time-limited download authorization, while tests can replace it with a deterministic fake.
import { NextRequest, NextResponse } from "next/server";
type Region = "us" | "eu";
type ExportRecord = {
id: string;
tenantId: string;
state: "building" | "ready" | "deleted";
region: Region;
objectKey: string;
fileName: string;
deleteAfter: Date;
};
type Session = {
tenantId: string;
permissions: ReadonlySet<string>;
};
interface ExportRepository {
findById(id: string): Promise<ExportRecord | null>;
}
interface DownloadSigner {
sign(input: {
key: string;
expiresInSeconds: number;
fileName: string;
contentType: "application/pdf";
}): Promise<string>;
}
declare const exportsRepo: ExportRepository;
declare const signers: Record<Region, DownloadSigner>;
declare function requireSession(request: NextRequest): Promise<Session>;
declare function audit(event: Record<string, string | number>): void;
const JSON_HEADERS = { "Cache-Control": "private, no-store" };
const MAX_URL_TTL_SECONDS = 300;
export async function GET(
request: NextRequest,
context: { params: Promise<{ exportId: string }> },
): Promise<NextResponse> {
const startedAt = Date.now();
const session = await requireSession(request);
const { exportId } = await context.params;
const record = await exportsRepo.findById(exportId);
if (!record || record.tenantId !== session.tenantId) {
return NextResponse.json({ error: "not_found" }, { status: 404, headers: JSON_HEADERS });
}
if (!session.permissions.has("exports:download")) {
return NextResponse.json({ error: "forbidden" }, { status: 403, headers: JSON_HEADERS });
}
if (record.state === "building") {
return NextResponse.json({ error: "not_ready" }, { status: 409, headers: JSON_HEADERS });
}
const retentionSeconds = Math.floor((record.deleteAfter.getTime() - Date.now()) / 1000);
if (record.state === "deleted" || retentionSeconds <= 0) {
return NextResponse.json({ error: "expired" }, { status: 410, headers: JSON_HEADERS });
}
const expiresInSeconds = Math.min(MAX_URL_TTL_SECONDS, retentionSeconds);
const url = await signers[record.region].sign({
key: record.objectKey,
expiresInSeconds,
fileName: record.fileName,
contentType: "application/pdf",
});
audit({
event: "export.download_url_issued",
exportId: record.id,
tenantId: record.tenantId,
region: record.region,
expiresInSeconds,
decisionMs: Date.now() - startedAt,
});
return NextResponse.json(
{ url, expiresAt: new Date(Date.now() + expiresInSeconds * 1000).toISOString() },
{ headers: JSON_HEADERS },
);
}
Notice what is missing from the response: objectKey, bucket name, tenant ID, and permanent storage address. The browser needs none of them. The audit event also omits the signed URL because logs are copied widely and often retained longer than application data. Record the decision inputs and TTL, not the credential.
Direct uploads use the same split. The API creates an export or evidence record, fixes its region from the tenant's residency policy, and signs a narrowly scoped upload. The browser sends bytes straight to that region. A completion callback or explicit finalize route then verifies the stored object's expected key and metadata before changing the record to ready. Keep an abandoned-upload lifecycle rule, because a browser can receive an upload capability and disappear before finalization.
Deletion needs two layers. The application scheduler marks the record unavailable at deleteAfter and queues physical object deletion; the storage lifecycle policy is a backstop for missed jobs and orphaned uploads. Never let lifecycle timing define user-visible authorization. Authorization stops at the database deadline, while a deletion worker measures when physical removal completes.
Observe retention as a deadline, not a cleanup chore
Start with a counter for signing decisions labeled by result and region: issued, forbidden, not-ready, expired, and not-found. Add a histogram for decision latency, another for issued TTL, and a gauge for objects past deleteAfter that have not yet reached a terminal deletion state. Avoid tenant IDs and export IDs as metric labels; they create unbounded cardinality. Put those identifiers in structured audit logs with access controls instead.
One alert deserves special care: overdue physical deletions. Alert on the oldest overdue age and the count of overdue objects, split only by region. A single delayed deletion might warrant investigation without paging; a growing queue or an age beyond the documented deletion objective is the page-worthy signal. The exact threshold is policy-specific. Write it down beside the retention promise so compliance, product, and operations are looking at the same clock.
Test time explicitly. With a fake clock and fake signer, cover one second before expiry, exact expiry, and one second after. Verify that the signer isn't called for 404, 403, 409, or 410 paths. Verify that a US record always selects the US signer even when the request originates in the EU, and vice versa. Then run an integration test that uploads a representative large object directly, finalizes it, downloads it, advances retention, runs deletion, and proves both the API denial and object absence.
Retries need identity. A deletion job should be idempotent: repeated execution reaches the same deleted state, and an already absent object counts as success. Store attempt count and last-attempt time for operations, but don't extend the user's access deadline just because cleanup is retrying.
Roll this out with decision-only logging first. Compare expected region, policy result, and proposed TTL without issuing a URL. Next, enable signed delivery for an internal tenant while retaining the proxy as a controlled fallback. Watch download completion, URL reissue rate, signing latency, and the old proxy's traffic. Remove the proxy only after the retention and regional deletion drills pass. Crisp evidence beats a hopeful launch.
Cost belongs in the review, though it should not lead it. Model stored bytes over the retention window, request volume, retrieval or egress treatment, and the application capacity avoided by direct transfer. Provider policies differ; for example, the Backblaze B2 pricing page documents its own storage, download, and transaction terms. Recheck the current primary pricing page for any provider before turning an estimate into a budget.
Know the limits before choosing signed delivery
Signed object URLs are a poor fit for instant revocation, mandatory inspection on every read, or policy that must react during a transfer. Use a gateway or application proxy in those cases. They are also insufficient as deletion evidence by themselves: an expired link proves only that one capability ended, not that every object copy was removed.
For the fintech case, the decision rule is compact: choose direct signed transfer when large files should bypass the app and a bounded revocation delay is acceptable; choose a live enforcement hop when access must be withdrawn immediately. In both designs, residency comes from the persisted tenant policy, retention denial happens before signing, and physical deletion has its own measured deadline.
No mystery. Just two clocks, two regions, and evidence for both.
Top comments (0)