Short answer: let the browser upload the original logistics image directly to a tenant-scoped private object key, then let a background Node.js worker create the thumbnail; the Next.js API route should authorize and record the work, not proxy or resize the bytes.

Choice Large-file path Tenant boundary Best fit
Direct upload, queued thumbnail Browser to object storage Tenant-derived keys plus server-side authorization Default for delivery photos, damage evidence, and signed documents
Direct upload, synchronous thumbnail request Browser to storage, then API waits for resize Same boundary, but tied to request lifetime Small, tightly bounded images when the thumbnail must exist before the response
Upload through the application Browser through the web process Application controls every byte Small files or environments where direct storage access is prohibited

The first row is my default. It keeps a 200 MB loading-dock video out of the web process and makes thumbnail retries independent of a deploy. More important, it gives tenant isolation one enforceable source of truth: the authenticated tenant determines both the original key and every derivative key. A filename supplied by the browser never gets to choose that boundary.

The catch is latency. A queued derivative is eventually available, so a product that requires an image preview in the same response should use the synchronous runner-up and impose a strict input-size limit. Stick with application-proxied uploads when policy requires content inspection before any byte reaches object storage. Those are real constraints, not edge trivia.

Which architecture should create a private thumbnail after a direct logistics upload?

Use three stages: authorize an upload intent, accept a completion signal, and process a durable thumbnail job. The upload-intent endpoint authenticates the user, creates a media row owned by that user's tenant, chooses an opaque object key, and returns a short-lived signed upload URL. The completion endpoint does not trust a client-supplied key. It loads the media row through the tenant boundary, checks the stored object metadata against the declared constraints, and enqueues a job containing an internal media identifier.

Then the worker reads the original from private storage, applies an orientation-aware resize, writes a deterministic derivative key, and marks that derivative ready. The read path returns another short-lived signed URL only after authorizing the media row for the current tenant. Signed URLs are bearer capabilities: anyone holding one can use it until it expires, within its permissions. Keep their lifetime narrow and never log the query string.

This split matters in a one-person SaaS because request time is expensive operational coupling. A resize competing with page requests for memory can turn a routine deploy into a queue of slow responses. A durable job can be retried, rate-limited, and observed without holding open an HTTP request. It also makes weekly shipping less dramatic: the web release records stable intent, while the worker owns CPU-heavy image work behind a small job contract.

Keep it boring.

The browser may report that its upload finished, but that statement is not proof of ownership, media type, or acceptable size. Treat it as a prompt to verify storage state. Reject a missing object, a size outside the upload policy, or a media record that is not in the expected state with a client-safe 409; record the internal reason separately. If an upload is larger than the product allows, fail before downloading it into Sharp. Content type from the client is only a hint, so decode the image in the worker and enforce a pixel limit as well as a byte limit. Decompression bombs are about decoded dimensions, not merely transfer size.

Tenant isolation is a data rule, not a folder convention

A readable key such as acme/proof.jpg looks organized but proves nothing. The application must derive the tenant from the authenticated session, load the media row with a tenant predicate, and obtain the object key from that row. Never accept tenantId, source key, destination key, or an arbitrary callback URL as authority from the request body.

Use opaque identifiers and deterministic derivatives, for example tenants/{internalTenantId}/media/{mediaId}/original and tenants/{internalTenantId}/media/{mediaId}/thumb-480.jpg. The names make operations legible, but authorization still lives in the database and storage policy. A worker should receive mediaId, look up the owning tenant, and rebuild the keys from trusted records. That closes the classic cross-tenant substitution path where a valid user asks the server to resize somebody else's object by changing one string.

Consider a dispatcher signed into tenant T17 who has legitimately created media record M44. The server has already assigned that record an original key under T17, so the browser needs only the signed write capability and later sends { "mediaId": "M44" } to the completion route. Now suppose the same caller has observed media ID M91 in a copied support message, and M91 belongs to tenant T23. Sending { "mediaId": "M91" } must fail at findOwned before storage is queried. Adding an objectKey for T23 to the JSON must make no difference because the schema rejects that extra authority rather than using it. The queue message for M44 contains no tenant or key supplied by the browser; when the worker receives it, the database lookup yields T17 and the stored original key, then the worker derives the T17 thumbnail destination. Finally, a download request for M44 repeats the tenant-owned lookup before creating a read capability. This example crosses four components — browser, API, queue, and worker — yet only the authenticated API creates the ownership relationship, while every later component reloads it. If a test changes M44 to M91 and still reaches storage.stat, the boundary is already broken even if the storage call eventually denies access. Fix the data flow, not the error message. That single negative test is more valuable than a folder-naming diagram because it proves an untrusted identifier cannot become an object read, a derivative write, or a signed download for another customer.

One ID. No keys.

There are two boundaries to test. At the application layer, tenant A must get 404 or the product's equivalent non-disclosing response for tenant B's media ID. At the storage layer, the worker identity should have only the prefixes and operations it needs; browser upload credentials should permit a single constrained write rather than general listing or reading. Storage policy syntax differs, so I'm not sure a copied policy example is correct for any reader's account. Resolve that uncertainty with the provider's policy simulator and an automated negative test against a disposable bucket before deployment.

Isolation also reaches observability. Log internal tenant and media IDs, job attempt, source byte count, decoded dimensions, output byte count, and elapsed resize time. Don't log signed URLs, cookies, or raw customer filenames. Metrics should separate rejected input, authorization denial, decoding failure, and retryable transport failure. A single "thumbnail failed" counter hides the decision you need to make at 2 a.m.

How should a Next.js API route create Sharp thumbnails after a user upload?

It shouldn't perform the resize itself for large uploads. The route below authenticates a completion request and queues a trusted identifier. A separate worker streams the private object through Sharp and back to storage, so neither component buffers the original as a single application-level Buffer. The storage and queue modules are deliberately adapters: their implementations can target a cloud service or self-hosted system without changing the tenant rule.

// app/api/uploads/complete/route.ts import { NextRequest, NextResponse } from "next/server"; import { requireSession } from "@/lib/auth"; import { db } from "@/lib/db"; import { jobs } from "@/lib/jobs"; import { storage } from "@/lib/storage"; export async function POST(request: NextRequest): Promise<NextResponse> { const session = await requireSession(request); const body: unknown = await request.json(); if (!isCompletion(body)) { return NextResponse.json({ error: "invalid_request" }, { status: 400 }); } const media = await db.media.findOwned(body.mediaId, session.tenantId); if (!media) { return NextResponse.json({ error: "not_found" }, { status: 404 }); } const source = await storage.stat(media.originalKey); if (!source || source.bytes !== media.expectedBytes) { return NextResponse.json({ error: "upload_not_ready" }, { status: 409 }); } await jobs.enqueueOnce(`thumbnail:${media.id}`, { kind: "create-thumbnail", mediaId: media.id, }); return NextResponse.json({ mediaId: media.id, status: "processing" }, { status: 202 }); } function isCompletion(value: unknown): value is { mediaId: string } { if (typeof value !== "object" || value === null) return false; const mediaId = Reflect.get(value, "mediaId"); return typeof mediaId === "string" && /^[a-zA-Z0-9_-]{16,64}$/.test(mediaId); } 
// workers/create-thumbnail.ts import sharp from "sharp"; import { pipeline } from "node:stream/promises"; import { db } from "@/lib/db"; import { storage } from "@/lib/storage"; type ThumbnailJob = { kind: "create-thumbnail"; mediaId: string; }; export async function createThumbnail(job: ThumbnailJob): Promise<void> { const media = await db.media.findById(job.mediaId); if (!media) return; const derivativeKey = `tenants/${media.tenantId}/media/${media.id}/thumb-480.jpg`; if (await storage.exists(derivativeKey)) { await db.media.markThumbnailReady(media.id, derivativeKey); return; } const input = await storage.createReadStream(media.originalKey); const output = await storage.createWriteStream(derivativeKey, { contentType: "image/jpeg", cacheControl: "private, max-age=31536000, immutable", }); const transform = sharp({ limitInputPixels: 40_000_000 }) .rotate() .resize({ width: 480, height: 480, fit: "inside", withoutEnlargement: true }) .jpeg({ quality: 82 }); await pipeline(input, transform, output); await db.media.markThumbnailReady(media.id, derivativeKey); } 

The enqueueOnce operation and deterministic key make duplicate completion calls harmless at the application level. For concurrent workers, the queue needs exclusive job ownership or the storage adapter needs conditional creation; which mechanism is available depends on the chosen systems. Do not assume an existence check alone is atomic. The database state should move from uploaded to processing to ready under a compare-and-set rule, and a retry should either acquire that transition or observe the completed derivative.

The fixed output contract is intentional. Letting each request choose width, format, quality, and destination turns a thumbnail worker into an unbounded image-processing endpoint. Add variants through reviewed server-side presets. For logistics evidence, preserve the original object and its metadata separately; a thumbnail is a viewing aid, not the record of truth.

Operate the pipeline by invariants

The useful service-level measure is time from verified upload to authorized thumbnail availability, split into queue delay and processing time. Track the oldest queued job, not just average throughput. A small average can coexist with one tenant's stuck work, especially when a few very large images dominate CPU or decoded pixels.

Deploy with four invariant tests: tenant A cannot complete tenant B's media; a duplicate completion creates one logical derivative; an image above the decoded-pixel ceiling is rejected; and a successful derivative is never publicly listable. Add a fixture with EXIF orientation so .rotate() remains covered. Also test a truncated JPEG and a non-image payload carrying an image content type. Those cases exercise the decoder rather than trusting metadata.

Retries need a ceiling and backoff. Permanent input errors go to a terminal state with a safe user message, while transient storage errors return to the queue. After the attempt limit, retain enough structured context to diagnose the job without retaining a signed credential. Reconciliation should periodically find uploaded media with no ready derivative and enqueue the same idempotency key again. This repairs the gap between recording an upload and publishing a queue message without inventing a second public workflow.

For capacity, measure actual inputs before tuning. Sharp uses native memory outside the JavaScript heap, so container memory and concurrency both matter. Start with low worker concurrency, observe peak resident memory and decoded dimensions, then raise it deliberately. Revenue-per-hour favors a slower stable queue over hand-tuning a fleet before customers create enough work to justify it. Outsource the undifferentiated parts, but keep tenant authorization and media-state transitions in code you can test.

Ship weekly. Change one preset at a time, version its derivative key, and let old thumbnails remain addressable until the database points to the new one. An immutable cache policy is safe only because a changed image gets a changed key; overwriting bytes beneath the same long-lived key risks stale previews.

When is the runner-up better?

Choose synchronous thumbnailing after a direct upload when inputs are strictly small, request duration is controlled, and the product cannot proceed without the preview. It reduces queue machinery, but the route still has to fetch the object after upload, enforce decoded limits, and avoid accepting a caller-selected tenant key. This can be sensible for an internal tool with low concurrency.

Choose application-proxied upload when compliance requires scanning or classification before storage accepts the object, or when the storage system cannot issue a suitably constrained upload capability. The trade is plain: the web tier now pays the bandwidth, timeout, and backpressure cost. Stream the body rather than buffering it, cap bytes at the edge, and isolate upload capacity from ordinary API traffic.

Neither runner-up changes the central rule. Tenant ownership is decided from authenticated server-side data, and image transformation consumes a trusted media ID. The transport can change later without reopening that boundary.

References