Private Avatar Thumbnails in Node.js: Sharp Crops, Originals, and Multiple Sizes
Short answer: keep the original upload in private object storage, create a small fixed set of square Sharp derivatives, and publish the new set only after every object has been verified.
For a logistics application, serve each derivative through a short-lived authorized download link. That decision keeps image delivery predictable. It also avoids making arbitrary resize requests part of the read path, where authorization, caching, and abuse controls become harder to reason about.
| Choice | Best fit | Main trade-off |
|---|---|---|
| Fixed derivatives at upload | Known UI slots such as 32, 64, 128, and 256 pixels | New display sizes require another processing job |
| Resize on request | Many unpredictable dimensions | More read-path work and a wider abuse surface |
| Application-mediated download | Authorization must be checked on every read | Adds an application hop |
| Short-lived signed link | An already-authorized user needs temporary access | Revocation is tied to link lifetime |
For user-uploaded delivery labels or driver avatars, fixed derivatives are usually the easier contract. Keep the original too. It is the recovery asset when the crop rule changes, the UI gains a new slot, or an operator needs to inspect what was uploaded.
Predictability wins.
How should Node.js Sharp store private avatar originals and multiple sizes?
Give every upload an immutable revision, then make the database point to a complete revision. A key layout like avatars/user-123/rev-8/original with 32.jpg, 64.jpg, 128.jpg, and 256.jpg is easy to inspect and test.
The exact sizes should come from rendered product slots, not habit. I'm not sure four sizes fit every fleet dashboard; measuring the actual slots and device density would settle that.
The write sequence matters:
- Create a new revision identifier.
- Decode the image and normalize its orientation.
- Apply the crop policy and generate the fixed derivatives.
- Upload the original and every derivative under that revision.
- Verify object metadata, dimensions, and content type.
- In one database operation, replace the active revision pointer.
Keep the pointer unchanged until step five succeeds. A failed derivative must not leave the application serving a half-complete avatar set. A worker retry should be safe because the revision and object keys are explicit rather than hidden in one mutable filename.
For example, if the original and the 32-pixel file exist but the 128-pixel transform fails, the record still points at the previous revision; a later retry can inspect or replace the incomplete new revision without changing what current readers see. If the retry succeeds, metadata checks can confirm all four derivatives before the pointer moves. If it fails again, the incomplete revision remains an unreferenced staging set for cleanup, while the last complete avatar remains available to the dispatch workflow.
That small distinction prevents a storage event from becoming a user-facing authorization or delivery incident.
Here is the transformation boundary in TypeScript. The storage adapter is intentionally generic; its job is to keep private-object semantics separate from Sharp's image work.
import sharp from "sharp";
const SIZES = [32, 64, 128, 256] as const;
type ObjectWriter = (key: string, body: Buffer, contentType: string) => Promise<void>;
export async function buildAvatarSet(
input: Buffer,
userId: string,
revision: string,
putObject: ObjectWriter,
) {
const prefix = `avatars/${userId}/${revision}`;
const source = sharp(input).rotate();
const metadata = await source.metadata();
if (!metadata.width || !metadata.height) {
throw new Error("The upload has no readable image dimensions");
}
await putObject(`${prefix}/original`, input, "application/octet-stream");
for (const size of SIZES) {
const derivative = await sharp(input)
.rotate()
.resize(size, size, { fit: "cover", position: "centre" })
.jpeg({ quality: 85 })
.toBuffer();
await putObject(`${prefix}/${size}.jpg`, derivative, "image/jpeg");
}
return { revision, prefix, sizes: [...SIZES] };
}
The example uses a center crop because it is deterministic. If a dispatcher or driver can choose a focal point, store that point with the revision and make it part of the processing input. Do not silently overwrite old bytes when the crop policy changes. A new revision makes a visual change auditable and reversible.
Where do access control and delivery simplicity diverge?
Private storage is only half the policy. The download endpoint also needs to decide who may read an object, for how long, and whether the response should display or download it.
A short-lived signed link works when the application has already authorized the user and temporary access is enough. Stream the bytes through the application when every request needs a fresh tenant check, role check, or audit decision. Treat an object key as an identifier, never as a permanent public URL.
The application can create the response after checking the stored content type and size. For browser behavior, set Content-Disposition deliberately: inline suits an avatar preview, while attachment asks the browser to download it. The header's filename value also deserves careful handling; a client-supplied filename should not become an unchecked response header.
This is where delivery simplicity stops being the same thing as good access control. A signed link reduces application work, but it is a bearer token for its lifetime. A proxied response gives tighter policy control, but it consumes application bandwidth and adds latency. Pick the boundary from the threat model, not from the convenience of the storage SDK.
Failure modes worth testing before publication
The most damaging bug is often a valid-looking record that names missing derivatives. Test the complete manifest, not only a successful upload response.
A useful fixture set includes portrait and landscape inputs, EXIF-rotated images, transparent images, and an input smaller than the largest requested size. Assert the output dimensions, media type, key layout, and active revision. Also test retries.
A transient upload failure should leave the old revision active. A repeated job should not publish until all required objects are present. An upload with an invalid or unsupported image should be rejected before the database pointer moves.
Keep old revisions until the retention policy says they can go; deletion immediately after publication makes investigation and rollback needlessly difficult.
There is an operational cost to every extra derivative. More objects mean more metadata, cleanup, and monitoring. Resize on request may be the better choice when dimensions are genuinely user-defined and the service has strong caching and rate limits. Keep fixed sizes when the product has a small, stable set of slots.
Comments
No comments yet. Start the discussion.