Short answer: let the Next.js API route authorize the upload, keep the original and the Sharp-generated thumbnail private, and assign one deletion deadline to the whole object graph. A worker enforces that deadline. The browser does not decide when a signed document or its image derivative disappears.
The image is easy. Retention is the product.
This example is a media workflow for signed documents and private images. A user uploads a source image, a worker creates a preview with Sharp, and the application serves a short-lived signed URL only after checking authorization. The original and preview share a deadline. The code is Go to show the state contract; Sharp remains in the Node.js worker.
What retention rule should govern private thumbnails and signed documents?
Store an application media ID, the original object key, every derivative key, the owner, the status, and delete_at in a database row. Do not derive the deadline from a filename or from a URL. Validate it when the upload is created, then copy the same policy to each derivative job.
The object graph is the unit of retention.
The lifecycle can stay small: pending, uploaded, processing, ready, and expired. A retry may revisit processing, but it must use a deterministic thumbnail key and an idempotency key. Duplicate queue delivery should find the existing derivative, not invent thumb-2 or a second logical asset.
A signed URL is temporary authorization, not the document identity. Keep storage private. On every read, the API route checks the current owner or access policy and then mints a short-lived URL for the requested key. A copied URL should not become a substitute for application authorization, although an already-issued URL cannot be revoked before its expiry.
Here is the awkward handoff this model is meant to cover: a producer signs a release, uploads a scan, and closes the browser while a worker is decoding a large image. The database has a source key and a deadline, the object store has bytes, and the queue has a message that may be delivered twice. If the worker writes a derivative with a fresh timestamp, the derivative can outlive the source. If cleanup deletes only the source key, a private preview remains. If confirmation marks the row ready before the source is verified, an empty preview can be cached as complete. The fix is to make the policy a field, inventory every key, and make the sweep a reconciler rather than a best-effort cron task.
How should a Next.js API route create Sharp thumbnails after a user upload to private object storage?
Use two requests. The first Next.js API route creates the database record and returns an upload target. The browser sends bytes directly to object storage. The second route confirms the upload and enqueues thumbnail work. This keeps large bodies out of the request handler and creates a clear point for ownership, content-type, and deadline checks.
The browser should not choose an arbitrary key. Generate one from a server-side media ID, such as media/{id}/original, and keep it in the database. Presigned upload URLs are bearer capabilities with a limited lifetime, so do not log them as if they were harmless identifiers. Direct browser upload also requires the storage CORS policy to allow the actual origin, method, and headers; a valid signature does not bypass browser CORS.
A worker adapter can expose a narrow contract:
type MediaAsset struct {
ID string
Original string
Thumb string
Status string
DeleteAt time.Time
}
func thumbnailJob(asset MediaAsset, now time.Time) error {
if !now.Before(asset.DeleteAt) {
return deleteObjects(asset.Original, asset.Thumb)
}
if asset.Status == "ready" {
return nil
}
source, err := readPrivateObject(asset.Original)
if err != nil {
return err
}
thumbnail, err := transformThumbnail(source)
if err != nil {
return err
}
if err := putPrivateObject(asset.Thumb, thumbnail); err != nil {
return err
}
return markReady(asset.ID, asset.Thumb)
}
In the Node.js service, transformThumbnail is the Sharp call. Restrict accepted formats, cap image dimensions before decoding, and run the transform in a bounded worker process. Write the derivative under its deterministic key. Check the deadline immediately before writing and again before marking the row ready; a long transform can cross the boundary.
readPrivateObject, putPrivateObject, and deleteObjects belong in a storage adapter. The retention state machine should not know whether the adapter talks to one object-store API or another. That separation keeps a provider change from changing deletion behavior.
How should the upload and thumbnail state machine guarantee a safe deletion rollout?
Create pending before returning the upload target. The confirmation route verifies that the expected object exists, records size and content type, and changes the row to uploaded. Only then does it enqueue work. Repeating confirmation must be safe.
The worker claims the row with a lease or compare-and-set operation. It reads the private original, runs Sharp, writes the thumbnail, and commits ready only after the write succeeds. If the process stops after the write but before the database update, a retry finds the same key and the status update remains idempotent.
That ordering prevents four distinct mistakes:
- An upload callback cannot declare an object ready before bytes exist.
- A duplicate queue delivery cannot create a second derivative identity.
- A late worker cannot extend
delete_at. - A deletion sweep can remove both keys while the thumbnail is still
processing.
The sweep claims rows where delete_at <= now, deletes the original and every derivative, and marks the row expired. If one key is already absent, continue with the others. Log the keys, policy version, attempt number, and result. A missing object during an already-authorized deletion is an idempotent outcome, not a reason to leave the remaining objects behind.
How can you verify retention, private images, and deletion behavior before rollout?
Test transitions rather than only the happy-path preview. One fixture should contain a signed document, an original image, and a thumbnail with one shared deadline. Run duplicate confirmation, duplicate queue delivery, a worker stop after the object write, and the deletion sweep twice. The expected result is one logical asset and no readable object after expiry.
For the browser path, use the real origin and headers in the CORS test. Verify that an unauthenticated private read is rejected, that an authorized read receives a temporary URL, and that the URL expires on schedule. These checks catch configuration drift before release.
Alert on pending uploads older than their upload window, processing leases beyond the transform timeout, and expired rows whose object count is nonzero. Track the age of the oldest deletion backlog, not only the count of successful jobs. A zero-error queue can still be late.
I am not sure one thumbnail size or worker timeout fits every newsroom and archive. Your mileage may vary. Measure decode memory and duration by input format, then set limits from those observations. Sharp can be fast, but an unbounded image is still an availability risk.
When is this architecture the wrong fit?
The catch is operational weight: direct upload plus asynchronous transforms adds a queue, a worker, a state machine, and a cleanup sweep. It is not suitable for tiny images with no private access requirement and no retention policy; one synchronous request may be easier to run. It is also a poor fit when the storage layer cannot keep objects private, mint temporary access, or delete every derivative.
Proxy uploads through the Next.js service when every byte must be inspected before storage or browser CORS cannot be configured. Accept the extra bandwidth and connection management deliberately. A managed image pipeline can reduce transform ownership, but confirm that it propagates deletion deadlines to all derivatives.
For signed media documents, keep identity and authorization in the application, keep bytes private, make derivative keys deterministic, and enforce one explicit deadline across the graph. The thumbnail is complete only when its retention story is complete.
Top comments (0)