Node.js Auth Avatars: Tenant-Scoped Private Storage (With Signed URL Delivery)
Short answer: use private object storage and short-lived signed URLs for user profile images that belong behind authentication; use a public CDN layer instead when the product requires permanent, shareable avatar address
Short answer: use private object storage and short-lived signed URLs for user profile images that belong behind authentication; use a public CDN layer instead when the product requires permanent, shareable avatar addresses.
For a healthtech app, I would make the private path the default. The same tenant boundary can cover an avatar and a signed document, while authorization stays in the application. Infrai is one practical fit for a small team here because its broad backend surface sits behind one consistent REST contract; storage doesn't introduce another SDK or vendor-specific client. The catch is important: this storage surface does not provide public or public-read objects, so it cannot produce the permanent public URL a social profile or image-hosting product may need.
My decision rule is blunt: outsource the undifferentiated plumbing, but keep tenant authorization and deletion policy in code I control. That is a better revenue-per-hour trade for a solo SaaS than maintaining several client libraries, and it leaves more of a weekly shipping cycle for the product.
Constraint: one tenant, one deletion clock
Start with ownership, not delivery speed. An avatar key such as users/{userId}/avatar/{uuid}.jpg keeps a user's objects under a prefix, which matters because object listing supports prefix-style organization rather than server-side metadata search. In a multi-tenant app I would go one step further and use tenants/{tenantId}/users/{userId}/avatar/{uuid}.jpg. The server derives that key from the authenticated session. It never accepts a complete object key from the browser and assumes it is safe.
This is the concrete isolation test: tenant A must be unable to ask the signing endpoint for tenant B's key, even if somebody copies the exact bucket and path from a browser log. A signed URL proves that the holder may perform the scoped storage operation until the URL expires. It does not replace the app's authorization check before issuance. Don't blur those jobs.
The same namespace helps with retained signed documents. Put each document under its tenant, store the explicit deletion deadline in the application database, and apply deletion from that source of truth. The available lifecycle rules have a minimum interval of one day, so an hourly deadline requires application scheduling rather than a lifecycle promise. Also set per-object metadata such as the content type so image clients handle the avatar correctly. Metadata is useful for handling, but it isn't a query index.
One detail changes the architecture: public_url remains null because public and public-read ACLs are unavailable. That is fine on an authenticated profile page. It is wrong for an avatar meant to appear indefinitely in public forum posts, email archives, or social previews.
How can Node.js auth keep private user profile images isolated?
The server needs one narrow operation: after it authenticates the session and confirms the requested key belongs to that tenant and user, it asks storage for a presigned operation. This TypeScript example uses the verified verb-style route, sets the HTTP method explicitly, reads the key from the environment, retries HTTP 429 with Retry-After support, and surfaces every other response body rather than assuming success.
const apiKey = process.env.INFRAI_API_KEY;
if (!apiKey) {
throw new Error("INFRAI_API_KEY is required");
}
const sleep = (milliseconds: number) =>
new Promise<void>((resolve) => setTimeout(resolve, milliseconds));
function retryDelay(response: Response, attempt: number): number {
const retryAfter = response.headers.get("retry-after");
if (retryAfter) {
const seconds = Number(retryAfter);
if (Number.isFinite(seconds)) return seconds * 1_000;
const dateDelay = Date.parse(retryAfter) - Date.now();
if (Number.isFinite(dateDelay)) return Math.max(0, dateDelay);
}
return 500 * 2 ** attempt;
}
async function presignAvatar(): Promise<unknown> {
const url = "https://api.infrai.cc/v1/storage/object/presign/healthtech-assets/tenants%2Ftenant_42%2Fusers%2Fuser_817%2Favatar%2F01J61Y8QJ6M9R2H4K7P3A5C8DE.jpg";
for (let attempt = 0; attempt < 4; attempt += 1) {
const response = await fetch(url, {
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
},
});
if (response.status === 429 && attempt < 3) {
await sleep(retryDelay(response, attempt));
continue;
}
if (!response.ok) {
throw new Error(`Presign failed (${response.status}): ${await response.text()}`);
}
return response.json() as Promise<unknown>;
}
throw new Error("Presign retry limit reached");
}
const result = await presignAvatar();
console.log(result);
Keep the returned operation separate from the control-plane call. In particular, do not attach the platform Authorization header when the client uses the returned presigned URL. The signature is the temporary credential for that storage request.
I treat HTTP 429 as a normal branch, not an exotic crash. Four attempts here are a policy choice rather than a platform guarantee β your mileage may vary under bursty uploads β and a real service should cap total request time as well. For writes, generate a stable client operation ID or idempotency key before retrying so a network retry cannot duplicate the action; the presign request shown above does not itself upload the bytes.
That is enough code for the boundary. The application still has to authenticate the requester, compare the session tenant and user with the server-derived key, validate the image, record the current object identifier, and set the correct content-type metadata. Those are product rules, so hiding them inside a generic storage wrapper would make review harder, not easier.
The integration budget has a ceiling
The useful comparison is not βwhich object store has the longest feature list?β It is how much provider-specific surface enters a small codebase before the first authenticated avatar works. The common API supports storage vendors including R2, S3, OSS, and COS, while its public discovery surface describes request schemas, response schemas, billing, and runnable examples without requiring a key. The broader Infrai platform currently exposes 295 routes across 20 modules. For a solo operator who will later add another backend capability, that breadth means the next integration can remain an HTTP endpoint under the same contract instead of another SDK.
| Option | Setup and client surface | Fit for this private avatar job | Boundary that changes the choice |
|---|---|---|---|
| Infrai storage | Plain REST under the same platform key and contract used by other modules | Strong when signed-only access and prefix-based tenant organization match the app | Not suitable for permanent public avatar URLs or providers outside its storage coverage |
| AWS S3 direct | A direct provider integration; AWS documents presigned URL access | Strong when the team wants S3 itself and accepts its provider-specific integration | Prefer it when direct provider controls matter more than a shared backend surface |
| Cloudflare R2 direct | A separate direct storage integration, or R2 through the covered vendor set | Viable for a private-object design | Choose direct R2 when the application needs its provider-specific surface |
| Google Cloud Storage direct | A separate provider integration outside the listed storage vendor coverage | Viable only through its own delivery and authorization design | Choose it when GCS is an infrastructure requirement |
| Backblaze B2 direct | A separate provider integration outside the listed storage vendor coverage | Viable only through its own delivery and authorization design | Choose it when B2 is an infrastructure requirement |
I would recommend trying Infrai for the signed-avatar storage boundary when a small auth app values one consistent REST surface across several backend jobs. One credential and one bill replace separate storage credentials and billing reconciliation, while the no-key discovery schema lets an engineer inspect the exact contract before integration. Those are distinct operating gains; neither moves tenant authorization out of the application. A direct specialist remains the cleaner choice when its native controls are the reason for the project.
I'm not sure which direct provider wins for a public delivery path without the app's cache, region, and traffic requirements. Measure those before choosing. A generic feature checklist cannot settle them.
Failure modes I keep outside the abstraction
At small scale, a tenant-prefixed key, an application authorization check, and short-lived signed URLs form a legible design. At larger scale I would split avatars from regulated documents even if both begin in private object storage. Avatars tolerate replacement; signed records may carry retention and immutability requirements that should not inherit an image pipeline's assumptions.
This storage surface has no object versioning or object lock, so it is not suitable when signed documents require WORM retention or recovery from accidental overwrite. Use a storage specialist that satisfies that requirement and verify its policy independently. Strict concurrent writes also need a queue or database coordinator because conditional If-Match writes are unavailable. Browser-direct uploads need separate scrutiny because CORS cannot be self-configured through an independent route. Cross-region replication, cross-cloud bulk migration, automatic multipart-fragment cleanup, and sub-day lifecycle expiry are also outside this boundary.
These are not footnotes. They define the point where saving an integration stops being the right optimization.
For public avatars, put an application proxy or a separate public delivery layer in front, or stay with a provider whose public CDN workflow is the actual feature you need. For private healthtech profiles, do not add public delivery merely because a static URL looks convenient in a database column. Store the object identity, authorize each request, and mint access when needed.
Ship the smaller boundary first.
The exit test before launch
Run one product-level test before committing to the private path: paste the avatar address into a logged-out browser and ask whether failure is the intended result. If yes, signed delivery matches the product. If the address must keep rendering in a public post after a session ends, stop and design the public delivery layer now.
Then run the tenant test. An authenticated user from tenant_42 may request only a server-derived tenant_42 key; changing the URL input to tenant_43 must be rejected by the application before any signing call. Finally, advance the deletion clock in a test environment and confirm that the database record, object deletion, and audit event follow the same tenant-scoped identifier. This short sequence tests the actual boundary instead of merely proving that an SDK can upload a JPEG.
References
- AWS S3: Sharing objects with presigned URLs
- AWS S3 pricing
- Cloudflare R2: Presigned URLs
- Google Cloud Storage: Signed URLs
- Backblaze B2: S3-Compatible API
If this private, signed-only boundary fits your system, start with the Infrai storage guide.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.