DEV Community

SolomonFletcher5872
SolomonFletcher5872

Posted on

Tenant-Isolated Next.js API Route for Private PDF Export via Signed Object Storage

For a gaming product that exports signed documents, the difficult part is not generating a PDF or signing a URL. It is proving that the player asking for the file belongs to the tenant that owns it, while still honoring a deletion deadline.

Short answer: keep the PDF private, store an application-owned export record, resolve the tenant's US or EU placement on the server, and let the authenticated Next.js API route mint a short-lived download URL only after the object and authorization checks pass.

That choice also gives the system a useful test target. A download request is either authorized and ready, authorized but still processing, or rejected. The browser never chooses the bucket, region, or object key.

Retention and regional policy come first

The tempting implementation is a button that receives a storage URL from the export worker. It works in a happy-path demo. It makes a poor security boundary in a multi-tenant game, where a document might contain tournament results, moderation evidence, or a signed partnership agreement.

The durable record should be an export ID in the application database. It needs the tenant ID, the server-derived object key, the selected region, the export state, and the deletion deadline. The object store holds bytes; the application owns the relationship between those bytes and a tenant.

That separation matters after a browser refresh. A URL copied into a log or email should not become the application's permanent authorization record. The API route can issue a fresh link when the player asks for the file, and a cleanup worker can delete the object when its deadline arrives. A signed URL is delivery machinery, not identity.

Keep it private.

I also want the export state to be explicit. processing means the worker has not made a downloadable object available. ready means the application found the expected object for the already-authorized export. A missing object must not turn into a guess at a different key, a second render, or a client-controlled path.

Can a tenant-owned ID carry a private PDF export through a Next.js API route?

Put the checks in this order:

  1. Validate the authenticated session.
  2. Load the export record by its application-owned ID.
  3. Compare the session tenant with the record tenant.
  4. Resolve the approved US or EU placement from trusted tenant configuration.
  5. Use the stored key for that placement and check whether the object is ready.
  6. Mint a temporary signed download URL for that exact object.

The client can send an export ID. It must not send a bucket, region, prefix, or object key and ask the route to sign it. That distinction is the tenant-isolation rule in one sentence.

Here is the decision logic behind the route. The storage adapter is intentionally generic: its job is to make the application policy visible, while the provider-specific signing implementation stays behind the interface.

from dataclasses import dataclass
from datetime import datetime, timezone
from typing import Protocol


class PrivateObjectStore(Protocol):
    def exists(self, *, region: str, key: str) -> bool:
        ...

    def sign_download(self, *, region: str, key: str, expires_seconds: int) -> str:
        ...


@dataclass(frozen=True)
class Export:
    export_id: str
    tenant_id: str
    region: str
    object_key: str
    delete_at: datetime


def download_state(
    *,
    session_tenant_id: str,
    export: Export,
    store: PrivateObjectStore,
    now: datetime | None = None,
) -> dict[str, str]:
    current_time = now or datetime.now(timezone.utc)

    if session_tenant_id != export.tenant_id:
        return {"state": "forbidden"}
    if current_time >= export.delete_at:
        return {"state": "expired"}
    if not store.exists(region=export.region, key=export.object_key):
        return {"state": "processing"}

    url = store.sign_download(
        region=export.region,
        key=export.object_key,
        expires_seconds=300,
    )
    return {"state": "ready", "download_url": url}
Enter fullscreen mode Exit fullscreen mode

The real Next.js handler still has web concerns: parse the request, call the session and database layers, translate forbidden and expired into the application's response contract, and avoid putting secrets in the response. None of those concerns should change the storage key supplied to the adapter.

The deletion check belongs in this path even if a scheduled cleanup job exists. Cleanup is an operational action; authorization is a request-time decision. Those clocks can disagree for a while. A signed URL should also have a shorter lifetime than the document's retention window, so a link copied shortly before deletion does not become a long-lived access path.

Evaluate the tenant matrix before the adapter

There are two records to expire: the object and the application index. Mark the export expired according to the product's policy, stop issuing new links, and make the cleanup worker idempotent. If the worker runs twice, the second run should be an ordinary already-clean state, not a new export or a tenant lookup based on user input.

For a gaming workflow, deletion is often tied to an event: a competition closes, a dispute window ends, or an agreement reaches its retention date. Store that deadline as data. Do not calculate it from the browser's clock, and do not treat the timestamp embedded in a filename as policy.

HTTP caching is another easy place to leak the wrong thing. The authenticated API response should use an explicit private cache policy suited to the session. MDN documents Cache-Control response directives, including private and no-store; choose the directive that matches whether any local or shared cache may retain the response. The signed destination should remain temporary, and the PDF itself should not be made public merely to simplify browser delivery.

The export worker deserves its own boundary. Render the PDF, upload it to the server-selected region and key, then mark the export ready in the application database. If marking ready fails, the worker can retry the state transition without inventing a new object key. If the upload fails, the record stays processing and the retry policy can be evaluated separately from download authorization.

Failure and retry are separate clocks

Notebook-to-prod thinking helps here: first write the cases as small assertions, then connect them to the route and storage adapter. I care about the assertions more than a polished demo because an AI-generated export can look correct while its authorization branch is wrong.

At minimum, evaluate this matrix:

Case Expected result What it protects
Matching tenant, object exists Ready link for the stored key Normal delivery
Matching tenant, object missing Processing state No guessed path or duplicate render
Different tenant, same export ID Forbidden Cross-tenant isolation
Deadline has passed Expired, no new link Retention policy
US tenant with EU request input Use configured US placement Region is not client-controlled
Link requested again Fresh temporary link No permanent URL record

The last two cases are where many quick examples get vague. Test both placements with the same export policy, and assert the exact region and key passed to the adapter. Also log an opaque export ID, tenant ID, placement, state transition, and request outcome. Do not log the signed URL or document contents.

Measure the stages separately: PDF render time, queue wait, object availability delay, link issuance, and cleanup lag. For generated documents, track prompt and token cost separately from storage latency. I’m not sure one aggregate download-time number would tell a team which part to fix; your mileage may vary, but stage-level measurements make the decision testable.

Rolling the boundary into production

The answer depends on controls the product must own. A direct object-storage integration can be the right fit when the team needs a particular provider's retention, replication, lifecycle, or recovery features and is ready to operate that integration. A simpler abstraction can be preferable when the application needs the same private-object workflow across multiple backend capabilities, provided it exposes the required regional placement and deletion semantics.

Do not choose from a price table first. Compare the interfaces and the failure modes:

Decision question Why it matters
Can the route sign only a server-derived key? Prevents arbitrary object access
Can placement be selected and audited per tenant? Makes US/EU policy testable
Can deletion be enforced before link issuance? Separates retention from cleanup timing
Can the team observe upload, ready, and cleanup states? Avoids treating storage as the export database
Does the integration supply the recovery and retention controls required by the product? Prevents a private-download design from becoming an inadequate archive

The catch is that a private PDF delivery path is not automatically a document-archive design. If the game needs immutable legal retention, recovery from accidental overwrite, cross-region replication, or public asset delivery, choose a storage architecture that explicitly supplies those controls. Stick with the direct design when those requirements are central. Use the smaller private-export boundary when the application owns the index, the retention deadline, and the authorization decision.

Before copying the pattern, run the matrix against a real export lifecycle, including a worker retry and a cleanup retry. The useful result is not that one URL opened in a browser. It is evidence that a tenant can retrieve only its own ready document, from the approved placement, until the stated deadline.

Sources

Top comments (0)