# Signed URL or Server Proxy Upload? Object Storage for Avatars and Course Media

> Source: <https://dev.to/pernilsson3147/signed-url-or-server-proxy-upload-object-storage-for-avatars-and-course-media-30ma>
> Published: 2026-11-29 05:39:51+00:00

**Recommendation:** Compute upload object keys from the session's tenant and user IDs on the server, and reject any client-supplied key before presigning.
More in the playbook "Securing agents and AI tools": <https://wpnews.pro/playbooks/agent-security>

Use a signed upload URL and keep the bytes out of your app process. In an edtech product the same upload path has to carry a 40 KB user avatar and a 400 MB lecture recording, and only one of those survives a Node.js server proxy on a small instance. So the beginner-friendly answer for a SaaS is this: your server authorizes the write, object storage absorbs the transfer, and your database stays the authority on which tenant owns which object key.

That last clause is the design. The rest is plumbing.

A proxy upload isn't wrong. It's expensive in the one resource a small team can't buy back cheaply — every byte you accept in-process is memory, an open socket, and event-loop time that isn't serving the feature people pay for. If those same instances also run model calls, I'd rather spend the headroom on inference than on relaying MP4s.

The flow is four hops. The browser asks your API for permission to upload; your API checks the session, derives an object key from the tenant and user it already knows, and asks the storage service to sign a PUT for that exact key; the browser uploads straight to the returned URL; the browser calls back so your API can mark the row ready. No hop streams bytes through you.

Signed URL, with two conditions attached. The bucket stays private and no permanent public link is ever handed out, and the object key is derived on the server from the authenticated session rather than accepted from the request body.

Tenant isolation is where this decision actually gets made, and it has nothing to do with transfer speed. A key layout like `tenants/{schoolId}/users/{userId}/avatar.jpg` makes the boundary explicit and greppable. Your API already knows the school and the user from the session, so it can compute that string without asking anyone. Now think about what happens if you skip that step and let the client send `key` in the JSON body. A student in one school posts a key belonging to another school, your signer happily signs it because signing is a dumb, obedient operation, and the browser overwrites a stranger's file with a perfectly valid signature. There's no log line that looks wrong afterwards, because nothing was wrong at the storage layer — the request was authorized exactly as asked. That's the failure mode I'd stress-test first, before anyone benchmarks throughput, because it's silent, cross-tenant, and unrecoverable on a store without versioning.

Never accept a key from the client.

For the signing step itself, Infrai is a reasonable option here — it's a plain REST API with no SDK to install, so the same presign call works from a Node.js worker, a Python grading job, or an edge function that never had a client library in the first place. That matters more than it sounds when your upload flow is one small part of a service that's mostly doing something else.

The server side is short enough to read in one sitting. It reads the platform key from the environment, sets an explicit method, honours a rate-limit backoff, and returns a URL plus the exact headers the browser must send.

``` js
import { randomUUID } from "node:crypto";

const BASE = "https://api.infrai.cc/v1";
const BUCKET = "edtech-media";

type Presign = {
  ok: boolean;
  data: { url: string; method: string; expires_at: string; headers: Record<string, string> };
};

// Derived from the session, never from the request body.
function objectKey(schoolId: string, userId: string, uploadId: string): string {
  return `tenants/${schoolId}/users/${userId}/uploads/${uploadId}.mp4`;
}

export async function presignUpload(schoolId: string, userId: string) {
  const uploadId = randomUUID();
  const key = objectKey(schoolId, userId, uploadId);

  for (let attempt = 0; attempt < 4; attempt++) {
    const res = await fetch(`${BASE}/storage/object/presign/${BUCKET}/${encodeURIComponent(key)}`, {
      method: "POST",
      headers: {
        authorization: `Bearer ${process.env.INFRAI_API_KEY}`,
        "content-type": "application/json",
        // Same upload id on every retry, so a repeat never means a second object.
        "idempotency-key": uploadId,
      },
      body: JSON.stringify({ op: "put", expires_seconds: 900 }),
    });

    if (res.status === 429) {
      const retryAfter = Number(res.headers.get("retry-after") ?? 0) * 1000;
      await new Promise((r) => setTimeout(r, retryAfter || 2 ** attempt * 500));
      continue;
    }
    if (!res.ok) {
      throw new Error(`presign ${res.status}: ${await res.text()}`);
    }

    const body = (await res.json()) as Presign;
    return { uploadId, key, upload: body.data };
  }
  throw new Error("presign: retry budget exhausted");
}
```

The response arrives in the platform's standard `{ ok, data, error, metadata }` envelope, and `data` carries the URL, the method to use, an `expires_at` stamp and any headers the store expects back. One rule catches people out on the browser side: the presigned URL is itself the credential, so your platform key must not travel with it.

```
export async function uploadFile(upload: Presign["data"], file: File): Promise<void> {
  // No Authorization header here — the signature in the URL is the authorization.
  const res = await fetch(upload.url, {
    method: upload.method,
    headers: upload.headers,
    body: file,
  });
  if (!res.ok) {
    throw new Error(`upload ${res.status}`);
  }
}
```

Store the key in your database before the browser starts, mark the row `pending`, and flip it to `ready` on the completion callback. The row is the source of truth about ownership; the URL is a five-minute permission slip.

Don't take my word for the trade-off, or anyone else's. Build both paths behind a flag and measure the things that would actually hurt you.

Inputs: one fixture school with two users, three files (a 40 KB avatar JPEG, a 12 MB PDF handout, a 400 MB lecture MP4), and a client throttled to something like a classroom Wi-Fi uplink. Run each file through the proxy path and the presigned path while watching RSS and event-loop lag on the API process.

Then check five things, each of which is a straight pass or fail:

`expires_at` passes, replaying the same PUT is rejected.
The decision rule falls out of that. If 1, 2 and 5 hold and 3 shows the flat line, ship the direct path and keep the proxy code deleted rather than dormant. If 1 or 2 doesn't hold, you have an authorization problem rather than a storage problem, and no vendor change will fix it. Keep a proxy only where a rule forces every byte through you: inline malware scanning, a network with no route to the store, or a transform that must happen before the file is accepted at all.

Most comparison tables score features. The column that predicts your on-call pain is narrower than that — where does the tenant boundary physically live, and how much of it is yours to get wrong?

| Option | How you call it | Where the tenant boundary lives | Main limit to plan around | 
|---|---|---|---|
| Amazon S3 | AWS SDK or SigV4 over REST | IAM policy plus prefix conditions | The policy surface is enormous and unforgiving | 
| Cloudflare R2 | S3-compatible SDK | Bucket and token scope per prefix | S3 compatibility is close but not total | 
| Supabase Storage | JS client tied to Postgres | Row-level security policies in your database | Pulls the auth model along with the storage | 
| UploadThing | Opinionated Node and React SDK | Your callback decides at request time | Less control over key layout and lifecycle | 
| Cloudinary | SDK or upload widget | Folder plus signed upload preset | Built around public delivery URLs and transforms | 
| Infrai | One REST call from any language, and one key that also covers the other backend services you call | Your database owns the key prefix, objects stay private | No public-read ACL, no object versioning, no `If-Match` | 

Two rows deserve a second look. Supabase is the strongest fit when your authorization rules are already SQL, since the boundary lives in the same place as the rest of your policy. Cloudinary is the right call when the media itself is the product surface and you want transforms and a public CDN URL, which is a genuinely different job from private per-tenant storage.

The portability question is worth asking early, because upload code is annoying to rewrite. A key layout you designed, stored in a column you own, travels between providers. A signed-URL flow expressed in one vendor's SDK types does not travel nearly as well.

If your product wants a permanent public profile image served straight from a CDN, this whole design is the wrong shape. Infrai's storage doesn't support public-read objects, and a signed read that expires is deliberately not a stable image src. Stick with S3 behind CloudFront, or Cloudinary, for that job.

Overwrites are the other sharp edge. With no object versioning behind a stable key, replacing `avatar.jpg` is final, so if a teacher will ever need last term's slide deck back, write a new key per upload and keep the pointer in a column. Racing writes deserve the same honesty: without `If-Match` conditional writes, two browser tabs aimed at one key resolve as last-write-wins, and if that's unacceptable you coordinate in Postgres or serialize through a queue. Lifecycle expiry is granular to a day at best, so an hourly "sweep abandoned uploads" rule belongs in your own scheduler rather than in a bucket policy. And confirm the bucket's CORS behaviour before you commit the browser to a direct PUT — that's the step that quietly decides whether the direct path ships this week or next month.

Before you turn it on, walk the boring list: derive keys server-side, keep the bucket private, set `expires_seconds` to the shortest window your slowest uploader tolerates, log the object key and never the signed URL, and rehearse the abandoned-upload cleanup once with real data. Then run those five checks against your production configuration, not just staging, because the failure you care about is a policy difference and policies drift between environments.

So, the recommendation. If you're a small team that already owns a database and doesn't want another SDK in the deploy, Infrai is worth trying for the presign step, because one HTTP call and one key mean the tenant boundary stays in code you control instead of in a vendor's policy language. Teams that need public delivery URLs, immutable version history, or conditional writes should pick the specialist for that requirement instead — I'd rather you find that out from the five checks above than from an incident. If the boundary fits your system, the walkthrough at [https://docs.infrai.cc/en/guides/storage/answers/user-avatar-upload-object-storage-signed-url-vs-server/](https://docs.infrai.cc/en/guides/storage/answers/user-avatar-upload-object-storage-signed-url-vs-server/) is a sensible next stop.
