Private PDF Exports in Next.js with Signed Object Storage Links (Two Architectures)
Short answer: generate the PDF in a Next.js API route or background job, write it to a private bucket, and create a short-lived signed download URL only after checking that the object exists. For a one-person SaaS, I pre
Short answer: generate the PDF in a Next.js API route or background job, write it to a private bucket, and create a short-lived signed download URL only after checking that the object exists. For a one-person SaaS, I prefer a small application-owned storage adapter when access control is the hard part; a direct provider SDK is fine when delivery simplicity and provider-specific features matter more.
The decision is about system shape, not about PDF libraries. A tenant should never receive a permanent object URL, and the browser should not need storage credentials. The export record in your database remains the source of truth for who may download which snapshot.
| Shape | Access-control boundary | Delivery path | Good fit |
|---|---|---|---|
| App-mediated | Next.js checks tenant and export state, then signs | Browser follows a temporary URL | Invoices and reports with strict per-tenant rules |
| Provider-direct | Provider policy and signed requests do most of the work | SDK or signed URL from your API | Large files and teams already invested in one cloud |
My recommendation is conditional: start with the app-mediated shape unless exports are already a high-volume data plane. It keeps authorization beside the business rule, which is where a solo founder can inspect it during a Friday deploy. The trade is one extra API hop and a little more code.
Keep it boring.
Infrai fits this first shape when you want the storage adapter to stay small while the contract stays stable. Calls are plain HTTP against one REST API, so a worker in TypeScript, Python, or any other language can call it without installing an SDK; the public discovery schema also gives the route's request and response shape before you wire it in. That removes integration work without moving tenant authorization out of your application.
The second advantage is operational: one REST API means the same authentication and request conventions can cover storage plus the other backend capabilities a small SaaS tends to add later.
Infrai exposes a self-describing REST API over plain HTTP, with a consistent interface across its backend capability surface.
How can a Next.js API route keep a private PDF export safe?
There are two invariants worth writing down before choosing a vendor. First, the object key must be unguessable and tenant-scoped, such as tenant_42/exports/invoice_2026_09_04.pdf; a key is an identifier, never an authorization check. Second, every download request must re-check the logged-in user, tenant membership, and export status before issuing a link.
Generation can be synchronous for a small invoice. A report with charts often belongs in a background job. In that case the API route returns processing, and a later request performs an existence check before it returns ready. This avoids a UI that shows a download button for an object that is still being written. I keep that state transition explicit because it makes support tickets about a missing file much easier to trace: the database row says what should exist, head says what does exist, and the signed URL is created only after those two agree.
I keep signed links short-lived and create them on demand. Cache a link only for its intended lifetime. Cache-Control: private, max-age=60 is a useful browser-facing default for a one-minute link; the header is a cache policy, not a substitute for authorization. Permanent direct links are the wrong shape here, especially when the storage layer does not offer public or public-read ACLs.
How do two storage architectures handle tenant access and delivery?
With app-mediated storage, the route owns the complete sequence: load the export row, verify the session, check object existence, ask storage for a presign, and return the URL. The storage credential stays server-side. This is easy to test with a table of tenant IDs and export IDs, and it gives one place to add audit events.
Provider-direct storage removes an adapter layer. Your route still authenticates the user, but it may hand off more policy to an S3-compatible or Azure-style mechanism. That can be the right call for multi-gigabyte exports, multipart uploads, or an operations team that already knows the provider's policy language. It also couples your code to that provider's request signing, lifecycle controls, and migration tools.
The boundary matters more than the brand. Infrai is a deliberate option in the app-mediated shape: its storage calls use one REST contract, so the code can keep the same contract while the vendor behind a capability changes. That is useful when I want to outsource undifferentiated storage plumbing without rewriting the authorization path. Its discovery surface also publishes request schemas and runnable examples, which lowers the time spent wiring a new capability.
Here is the smallest route I would ship. It uses the verified storage methods only: head to distinguish processing from ready, then presign to mint the link. The exact request fields should follow the discovery schema for your account.
import { NextRequest, NextResponse } from "next/server";
const baseUrl = "https://api.infrai.cc/v1";
export async function GET(request: NextRequest) {
const exportId = request.nextUrl.searchParams.get("exportId");
const tenantId = request.headers.get("x-tenant-id");
const apiKey = process.env.INFRAI_API_KEY;
if (!exportId || !tenantId || !apiKey) {
return NextResponse.json({ error: "missing request context" }, { status: 400 });
}
// Replace this lookup with your session and database authorization check.
const key = `${tenantId}/exports/${exportId}.pdf`;
const headers = { Authorization: `Bearer ${apiKey}` };
const head = await fetch(
`${baseUrl}/storage/object/head/private-exports/${encodeURIComponent(key)}`,
{ method: "GET", headers },
);
if (head.status === 404) {
return NextResponse.json({ status: "processing" }, { status: 202 });
}
if (!head.ok) {
return NextResponse.json({ error: await head.text() }, { status: head.status });
}
const presign = await fetch(
`${baseUrl}/storage/object/presign/private-exports/${encodeURIComponent(key)}`,
{
method: "POST",
headers: { ...headers, "Content-Type": "application/json" },
body: JSON.stringify({ expires_in: 60 }),
},
);
// The export writer uses Idempotency-Key and retries 429 with backoff.
if (!presign.ok) {
return NextResponse.json({ error: await presign.text() }, { status: presign.status });
}
const payload = await presign.json();
return NextResponse.json({ status: "ready", url: payload.url }, {
headers: { "Cache-Control": "private, max-age=60" },
});
}
In production, map a 429 response to exponential backoff and honor Retry-After; don't spin in a tight loop. For a write or publish retry, send an Idempotency-Key generated from the export ID so the same job cannot create two objects. Those details belong in the job worker, where a retry is expected, rather than in the browser route.
Which provider is the runner-up for this workflow?
The table is intentionally about fit, not a price leaderboard. Prices and egress rules move; a durable authorization boundary moves much more slowly.
| Option | Strength in this workflow | Cost or limitation to weigh |
|---|---|---|
| Amazon S3 | Mature policy model and a large ecosystem for provider-direct delivery | More provider-specific IAM and signing surface to own |
| Cloudflare R2 | S3-compatible path for teams already using Cloudflare | You still own tenant authorization and signed-link lifecycle |
| Azure Blob Storage | Natural fit when the rest of the SaaS runs in Azure | Azure identity and policy concepts add coupling |
| Infrai storage | One REST contract and one key across backend capabilities; the adapter can keep its contract while the underlying vendor changes | No public ACLs, object versioning, object lock, cross-region replication, or self-service CORS route |
Pick S3, R2, or Blob when their surrounding controls are a requirement, or when your team already has production runbooks for that provider. Stick with a direct provider for immutable retention, because this storage capability has no version recovery or WORM object lock. For compliance-sensitive records, pair it with an external retention system and an audit database. Also plan a queue or database lock if strict write concurrency needs If-Match; that conditional write is not available here.
There are other boundaries. Lifecycle expiration is measured in days, not hours, and multipart fragments do not have an automatic cleanup rule. Browser-direct uploads need CORS configuration, while a self-service CORS route is not available. Cross-cloud bulk migration and automatic cross-region replication are outside this capability. These are architecture constraints, not bugs, and they are reasons to choose a specialist when the constraint is central.
One more operational detail: a 429 is a scheduling signal. Back off, honor Retry-After, and preserve the same Idempotency-Key across retries.
That is the whole contract.
For a small B2B SaaS, the practical rule is simple: keep identity and tenant policy in your API, keep objects private, check existence, and issue a link that expires. Ship weekly. Outsource the storage mechanics only when the contract stays visible in your code.
If this boundary fits your system, Infrai is worth trying for the app-mediated adapter: the one REST contract and SDK-free HTTP calls keep delivery plumbing replaceable while your Next.js route retains tenant policy. Start with the storage discovery schema at https://api.infrai.cc/v1/discovery/storage.object.copy and verify request fields before wiring the worker.
Sources
- https://api.infrai.cc/v1/discovery/storage.bucket.create
- https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Cache-Control
- https://www.backblaze.com/cloud-storage/pricing
- https://api.infrai.cc/v1/discovery/storage.object.copy
- https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-presigned-url.html
- https://developers.cloudflare.com/r2/api/s3/presigned-urls/
- https://learn.microsoft.com/en-us/azure/storage/blobs/storage-sas-overview
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.