DEV Community

DorianReed2186
DorianReed2186

Posted on

Node.js Avatar Uploads: 3 Access Controls for Marketplace Object Storage

Short answer: keep the browser away from permanent storage credentials. A Node.js service should validate the avatar request, create a short-lived presigned PUT URL for one server-selected object key, and make the object private by default. Store the retention decision with the avatar record, then let a worker delete or transition the object from that record rather than guessing from filenames.

For a marketplace, this is the least complex design that still gives you control. The upload path is direct, so the application does not proxy image bytes. The authorization path stays on your server, where you can check the marketplace account, file type, size, and retention class before issuing a URL.

The storage layer should never decide ownership.

What should the upload flow protect?

An avatar upload has two separate jobs: deliver bytes and decide who may later read them. Combining those jobs in a public object URL is convenient until a deleted account still has a cacheable image, or a copied URL outlives the marketplace relationship that justified access.

The data flow is short. The client asks Node.js for an upload session. Node.js authenticates the caller, generates an opaque key, and signs a request for the S3-compatible endpoint. The client uploads directly with that URL. Node.js records the key and its retention class only after the upload has completed, or marks the session incomplete for cleanup. Avatar reads use a separate authorization decision; they do not reuse the upload URL.

The awkward case is an interrupted upload. A mobile client can receive the signed URL, lose its connection after sending some bytes, and never call the completion endpoint. Treating the URL response as proof that an avatar exists leaves an orphaned object and a false database record. Treating the client callback as proof is also weak: the callback says what the client observed, not what the storage endpoint committed. Keeping the session pending until the server checks the expected key gives the cleanup worker something concrete to handle. It also makes retries boring. A repeated completion request can look up the same session, see that it is already ready, and return the stored result instead of creating a second policy decision.

The three controls that matter are scope, time, and lifecycle. Scope means one key and one method. Time means an expiry measured in minutes, not days. Lifecycle means the database record says when the object should stop being available and when storage cleanup should run.

Five minutes is a boundary, not a guarantee.

A Node.js presigned upload example

The following TypeScript sketch uses the AWS SDK v3 interfaces because they are widely implemented by S3-compatible services. The endpoint, bucket, and credentials come from the server environment. A client never receives them.

import { randomUUID } from "node:crypto";
import {
  PutObjectCommand,
  S3Client,
} from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";

const bucket = process.env.OBJECT_BUCKET;
const endpoint = process.env.OBJECT_ENDPOINT;

if (!bucket || !endpoint) {
  throw new Error("OBJECT_BUCKET and OBJECT_ENDPOINT are required");
}

const storage = new S3Client({
  endpoint,
  region: process.env.OBJECT_REGION ?? "us-east-1",
  forcePathStyle: process.env.OBJECT_PATH_STYLE === "true",
});

const allowedTypes = new Set(["image/jpeg", "image/png", "image/webp"]);
const maxBytes = 5 * 1024 * 1024;

export async function createAvatarUpload(input: {
  marketplaceUserId: string;
  contentType: string;
  contentLength: number;
}) {
  if (!allowedTypes.has(input.contentType)) {
    throw new Error("unsupported avatar type");
  }
  if (!Number.isInteger(input.contentLength) || input.contentLength <= 0 || input.contentLength > maxBytes) {
    throw new Error("invalid avatar size");
  }

  const objectKey = `avatars/${input.marketplaceUserId}/${randomUUID()}`;
  const command = new PutObjectCommand({
    Bucket: bucket,
    Key: objectKey,
    ContentType: input.contentType,
    ContentLength: input.contentLength,
  });

  const uploadUrl = await getSignedUrl(storage, command, { expiresIn: 300 });

  return {
    objectKey,
    uploadUrl,
    expiresInSeconds: 300,
  };
}

// The browser uses the URL once, with the same signed headers.
export async function uploadAvatar(uploadUrl: string, file: File) {
  const response = await fetch(uploadUrl, {
    method: "PUT",
    headers: {
      "Content-Type": file.type,
      "Content-Length": String(file.size),
    },
    body: file,
  });

  if (!response.ok) {
    throw new Error(`avatar upload failed: ${response.status}`);
  }
}
Enter fullscreen mode Exit fullscreen mode

The exact headers are part of the signed request. If the server signs ContentType and ContentLength, the client must send matching values. That is a useful constraint: a caller cannot request a small PNG URL and then use the same URL for an unrelated content type or size. The upload endpoint should also bind marketplaceUserId to the authenticated session; accepting an arbitrary user ID from the request body creates an object ownership bug.

The example deliberately uses a random suffix. Reusing avatars/user-123/current makes replacement easy, but it creates race conditions between an old upload and a new one. An immutable key lets the database choose which completed object is current and gives cleanup a precise target.

How do access control and delivery simplicity trade off?

A public object is the simplest delivery mechanism. It is also a poor default for user avatars when account deletion, moderation, or seller visibility matters. A private object plus a short-lived read URL adds one authorization step, but it keeps the storage policy aligned with the marketplace policy.

There is a practical middle ground. Keep objects private, expose an application endpoint such as /users/me/avatar, authorize the request, then redirect or proxy according to your delivery requirements. A redirect to a short-lived read URL is usually less work for the application than streaming every image, while a proxy gives tighter control over headers and response behavior. Choose deliberately; do not let a storage setting make the decision for you.

Caching needs its own policy. Cache-Control controls how a response may be stored and reused, but it does not grant permission to read an object. For a private avatar, a response policy such as private, max-age=300 can limit browser reuse while preserving a small amount of responsiveness. If an avatar changes under the same public URL, cache invalidation becomes another problem; immutable keys avoid that collision.

This is where delivery simplicity loses to access control. A marketplace can tolerate a few more lines of authorization code. It has a harder time explaining why an ex-user's image remains reachable through an old, long-lived URL.

Keep the read decision separate.

Retention is a record, not a filename

A reproducible retention policy needs explicit state. Store the object key, owner ID, upload status, content type, byte count, created time, retention class, expiration time, and deletion time in a database row. The retention class might be account-active, moderation-hold, or delete-after-account-closure; those names are examples of policy labels, not storage features.

The upload session begins as pending. After the client reports success, the server should verify that the expected object exists and that its metadata matches the request before marking it ready. A failed or abandoned session remains eligible for cleanup. Account closure records the policy event and lets a worker delete the exact keys selected by that event.

Do not rely on a prefix alone. Prefix cleanup is hard to audit when a user has multiple attempts, and it can delete a replacement uploaded during a race. A database query that selects status = 'ready' and expires_at <= now() gives operators a reviewable explanation for every deletion. The storage provider's lifecycle rules can still remove stale pending objects as a backstop, but application policy should remain visible in application data.

The main cost is not the five-minute signing window. It is the operational discipline around incomplete uploads, retries, and deletion. A small table and one idempotent cleanup worker buy more predictability than a clever key naming convention.

This pattern has limits. It is a poor fit for very large uploads that need multipart coordination, for files that require server-side transformation before they become visible, or for a product that cannot operate a cleanup worker. In those cases, proxying or a managed ingestion pipeline may be the simpler choice, even though it adds infrastructure and delivery latency. The right boundary depends on file size, inspection requirements, and how much policy the team can operate reliably.

The limitation is deliberate: direct upload gives the application fewer opportunities to inspect bytes before storage. If moderation must happen before any object is readable, the extra inspection stage is part of the design, not an optional refinement. That is a real trade-off against the simpler delivery path.

Testing the failure paths before launch

Test authorization separately from upload delivery. A user must not be able to create a URL for another marketplace account, change the object key, extend the expiry, or use an avatar URL after the account policy says it is no longer valid. Test an expired upload, a mismatched content type, an oversized body, a duplicate completion callback, and a worker retry after a transient delete failure.

Observability should answer three questions: which user requested the session, which object key was issued, and whether the object reached a terminal state. Log identifiers and outcomes, not signed URLs. A presigned URL is a bearer credential during its validity window, so putting it in request logs, analytics events, or error messages expands the exposure surface.

I would also keep a small compatibility test against the actual S3-compatible endpoint. SDK configuration differences around endpoint style, region handling, checksum behavior, and signed headers are integration concerns; a local mock can prove your application flow while missing one of them. Keep the test focused on the request shapes your application uses.

The operational checklist is straightforward prose: make the bucket private, set an explicit five-minute signing limit, validate size and MIME type on the server, use an opaque immutable key, persist a pending record before returning the URL, verify completion, authorize reads independently, and run an idempotent cleanup job. Review the policy whenever account deletion or moderation rules change.

Conclusion

For marketplace avatars, direct browser upload with a short-lived presigned URL is a good default when the server owns authorization and retention state. It keeps image bytes off the Node.js request path without turning object storage into the policy engine.

The boundary is clear: the presigned URL handles temporary upload permission; the database and application handle ownership, visibility, and retention. Keep those responsibilities separate, and the design remains portable across S3-compatible storage systems without making a vendor choice the center of the architecture.

Further reading

Top comments (0)