Tenant isolation changes the upload design before Node.js enters the picture. For private customer-support avatars, I would store opaque object keys, keep the bucket private, attach a small metadata record, and mint a short-lived download link only after checking the tenant that owns the record.

Short answer: validate the image at the application boundary, write it under a tenant-scoped key, write metadata with the object, and save that key in your database. Treat the object key as an identifier, not as authorization. The database check remains the authorization boundary.

This is a small system. The dangerous parts are still easy to miss: a user-controlled filename can escape a tenant prefix, a metadata field can become an accidental privacy leak, and an overwrite can silently replace somebody else's avatar. I optimize for fewer moving pieces, but I do not remove those checks to make the demo shorter. The boring checks are the feature.

Why does tenant isolation matter more than the storage brand?

An avatar upload has two identities: the authenticated user and the tenant that owns the user. The object store usually sees a bucket and key. It does not know whether a support agent is allowed to read that key. Your service must make that decision first.

Use a generated key with a stable tenant segment and a server-owned user identifier. Do not use the original filename as the key. Keep the original name, if it is useful at all, in application metadata or the database after normalizing it. A practical shape is tenants/{tenantId}/avatars/{userId}/{objectId}. The exact delimiter is less important than making the ownership rule obvious in code review.

The database row should contain the tenant ID, user ID, object key, media type, byte count, and upload timestamp. The object metadata can repeat a few operational fields, such as the uploader and timestamp, but it is not a query index. Object metadata is useful at retrieval time; it is the wrong place to search for every avatar belonging to a tenant.

That distinction also keeps deletion clear. A delete request first checks tenant ownership, then deletes the object, then removes or marks the row. This matters for privacy requests. GDPR Article 17 describes a right to erasure, so “the row is gone” is not a complete deletion story if the object still exists.

How should Node.js upload a user avatar and store its metadata?

The upload handler should do four things before it calls storage: authenticate, resolve the tenant, validate the bytes, and generate the key. Here is the part I keep close to the route. It is deliberately boring.

import { randomUUID } from "node:crypto"; const MAX_AVATAR_BYTES = 5 * 1024 * 1024; const ALLOWED_TYPES = new Set(["image/jpeg", "image/png", "image/webp"]); type UploadInput = { tenantId: string; userId: string; bytes: Uint8Array; contentType: string; originalName?: string; }; export function prepareAvatarUpload(input: UploadInput) { if (!input.tenantId || !input.userId) { throw new Error("tenant and user are required"); } if (!ALLOWED_TYPES.has(input.contentType)) { throw new Error("unsupported image type"); } if (input.bytes.byteLength > MAX_AVATAR_BYTES) { throw new Error("avatar is too large"); } const objectKey = `tenants/${input.tenantId}/avatars/${input.userId}/${randomUUID()}`; const metadata = { tenant_id: input.tenantId, user_id: input.userId, uploaded_at: new Date().toISOString(), }; return { objectKey, metadata }; } async function putPrivateAvatar( bucket: string, objectKey: string, bytes: Uint8Array, contentType: string, ) { const baseUrl = process.env.INFRAI_BASE_URL; const apiKey = process.env.INFRAI_API_KEY; if (!baseUrl || !apiKey) throw new Error("storage configuration is missing"); const idempotencyKey = `avatar:${objectKey}`; const route = "/v1/storage/object/put/{bucket}/{key}"; const path = route .replace("{bucket}", encodeURIComponent(bucket)) .replace( "{key}", objectKey.split("/").map(encodeURIComponent).join("/"), ); for (let attempt = 0; attempt < 4; attempt += 1) { const response = await fetch(`${baseUrl}${path}`, { method: "PUT", headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": contentType, "Idempotency-Key": idempotencyKey, }, body: bytes, }); if (response.ok) return; if (response.status !== 429 || attempt === 3) { throw new Error(`storage write failed: ${response.status} ${await response.text()}`); } const retryAfter = Number(response.headers.get("retry-after")); const delayMs = Number.isFinite(retryAfter) ? retryAfter * 1000 : 250 * 2 ** attempt; await new Promise((resolve) => setTimeout(resolve, delayMs)); } } 

This checks the declared content type, not the file signature. In production I would inspect the bytes as well, because a client can label arbitrary bytes as an image. The important boundary is still the same: reject before persistence, and never let the client choose the tenant prefix or final object key.

The storage write can use an S3-compatible SDK or a provider API. Keep that adapter behind one interface so changing providers does not spread storage-specific request shapes through the support application. After a successful write, persist the generated key and metadata in one database transaction where possible. If the database write fails after the object write, enqueue cleanup or mark the object for reconciliation; leaving orphaned private avatars forever is a lifecycle problem, not a retry strategy.

For a REST adapter, the verified write surface is a PUT to /v1/storage/object/put/{bucket}/{key}, followed by POST to /v1/storage/object/set_metadata/{bucket}/{key} when metadata is separate. The adapter should send an explicit method, use bearer authentication from an environment variable, inspect non-2xx responses, and retry rate limits with backoff while preserving an idempotency key for writes. Keep those details in the adapter. The route should know about saveAvatar, not about two storage URLs.

How do the main storage options differ?

Amazon S3 is the reference point for compatibility and ecosystem depth. It has mature private-object patterns, presigned requests, lifecycle controls, and a broad SDK surface. That is a strong default for a team that wants the largest operational vocabulary. The cost is more configuration and more policy surface, which increases the amount of glue a small Node.js service has to own.

Cloudflare R2 is attractive when the application already lives close to Cloudflare and wants S3-compatible object access. Its public-access and custom-domain choices need careful review for private avatars; a convenience URL must not become the authorization model. R2 also does not remove the need for an application database that maps users to tenant-owned keys.

MinIO is a good fit when self-hosting, local development, or an S3-compatible private deployment matters more than managed operations. It gives the team control over the environment, but that control includes backups, upgrades, exposure, and recovery testing. A MinIO endpoint on a private network is not automatically a complete disaster-recovery plan.

The fourth option I would consider is a unified REST layer such as Infrai when time-to-first-call and self-describing discovery matter. Its discovery surface exposes request schemas and runnable examples, so wiring a capability can start with reading one endpoint instead of learning another SDK. That reduces integration glue. It does not change the tenant rule, and it does not make storage a public image host.

My decision rule is simple: choose S3 for ecosystem depth, R2 for a Cloudflare-centered deployment, MinIO for operational control, and a unified REST layer when consistent discovery across backend capabilities is worth the platform boundary. For all four, private reads and database authorization are still required.

Option Access shape Best fit Main limitation
Amazon S3 SDKs and S3 REST Broad ecosystem and managed operations More policy and configuration surface
Cloudflare R2 S3-compatible SDK or REST Cloudflare-centered applications Public-domain choices need careful privacy review
MinIO S3-compatible SDK or REST Self-hosted or local private storage The team owns upgrades, backups, and recovery
Unified REST layer One REST API Fast discovery and less SDK glue Provider-specific storage limits still apply

The table is a routing aid, not a security control. Tenant authorization belongs in the application for every row.

Keep it private.

There is a useful failure sequence to design around. The service accepts the bytes, the object write returns success, and the database transaction then times out. A retry of the whole request can create a second object unless the key is deterministic or the write carries an idempotency key. A database row written first has the opposite problem: a reader can receive a key for an object that does not exist yet. I prefer the object-first sequence, a deterministic tenant-scoped key, and a small reconciliation job that compares recent rows with recent objects. That job does not need to inspect every byte or make storage metadata searchable. It only needs enough state to identify an orphan and enough authorization context to delete it safely. This is extra work, but it is cheaper to reason about than pretending distributed writes are one transaction.

That is the whole trick.

What changes when the upload is production-sized?

The 5 MB example is an avatar boundary, not a universal upload policy. Validate dimensions and decoded content before accepting files, and make the object key immutable per upload. If an avatar changes, create a new key and update the database pointer after the new write succeeds. That avoids relying on a storage feature to recover an accidental overwrite.

There are constraints worth writing down before choosing a service. The unified storage surface described here has no public-read ACL, so it is unsuitable for permanent public links or static-site hosting. It has no object versioning or object lock, so strict immutability needs an external design. It has no conditional If-Match write, which means strict concurrent-write coordination belongs in the database or a queue.

Browser-direct uploads also need a CORS decision. If the storage service does not expose a self-service CORS route, route uploads through your backend or put CORS policy in a layer you control. Lifecycle rules are not instant expiry machinery: a one-day minimum is different from deleting an object after 30 minutes, and multipart fragments need an explicit cleanup plan if automatic fragment cleanup is unavailable.

Metadata has another sharp edge. If the service only filters object listing by prefix, do not build a support search feature that expects server-side metadata queries. Put searchable fields in your database. The object store should hold bytes and retrieval metadata; the database should hold authorization and application state.

The trade-off I would ship

For private customer-support avatars, I would ship a private bucket, tenant-derived keys, byte and content validation, a database pointer, and a backend-issued expiring read link. I would keep the storage adapter narrow and add reconciliation for partial writes. That is enough to make the workflow understandable and auditable.

I would not promise public URLs, cross-region recovery, object-level history, or instant expiry unless the chosen provider and the surrounding system explicitly provide them. Those promises are architecture decisions. They are not implied by “S3-compatible.”

The useful benchmark is not upload latency alone. Measure time-to-first-call, rejected invalid uploads, orphan cleanup, authorization failures, and recovery from a failed database write. A storage integration that looks fast in a happy-path demo can still be expensive to operate when tenant boundaries are vague.

Do not blur the boundary.

Sources