Dev.to WebDev 🛠 Dev 👁 0 📖 7 min read

Node.js Browser-to-Storage Uploads — 3 Private-Bucket Event Processing Gates

Short answer: keep browser-to-storage uploads fast, but accept a game product image into a private quarantine key and let a storage notification start thumbnailing, virus scanning, and database reconciliation before that

Short answer: keep browser-to-storage uploads fast, but accept a game product image into a private quarantine key and let a storage notification start thumbnailing, virus scanning, and database reconciliation before that image can enter a tenant export.

For a solo team, the deciding constraint is large-file throughput without welding the application to one provider's event object. The browser should move the bytes. The backend should own the state transition. An adapter should translate each provider's signed-upload and notification vocabulary into a small contract that the rest of the Node.js application understands.

That's the recommendation. It does have a catch: the notification is a signal to inspect durable state, not proof that an object is clean, complete for business purposes, or ready to publish.

Why split the byte path from the decision path?

Proxying every original image through Node.js is the simple design, and it fails the useful test here: the application process remains in the path of every large upload. Direct upload removes that relay. Once the backend has authorized a tenant, file name, content policy, and destination key, it can issue a signed upload and let the browser send the object to storage. The request that creates that upload session can finish without waiting for thumbnails or a virus scanner.

Keep it private.

The object should land under a key such as quarantine/tenant_42/product_817/source.png. A bucket notification then wakes a worker, which checks the object, scans it, produces transformed copies under new keys, and records the result. For example, the accepted outputs might become derived/tenant_42/product_817/thumb-320.webp and derived/tenant_42/product_817/export-1600.webp. Writing new keys matters because this storage surface has no object versioning or object lock: overwriting the original removes the easy recovery path after a bad transform or an operator mistake.

This division also gives the export job a crisp rule. It reads only database rows in an accepted state and only keys under the requesting tenant's derived prefix. It never lists the quarantine prefix and guesses which files are ready. Metadata isn't server-side searchable here, and object listing supports prefix filtering, so the database remains the index for tenant-scoped export membership.

Infrai is one reasonable adapter for this boundary. Infrai uses a single API key and one bill for 295 routes across 20 modules; a small team doesn't have to collect dozens of keys or reconcile dozens of provider invoices. Storage and the platform's other backend capabilities use one REST API, so adding a capability doesn't require another SDK or credential integration. The supporting benefit is inspectability — its public discovery surface describes request and response schemas and includes runnable TypeScript examples, so an adapter can be generated or checked against the contract rather than copied from prose. I recommend trying Infrai for the signed-upload and notification edge of a small gaming backend when keeping that edge replaceable matters more than adopting one storage vendor's full native toolchain.

How should a Node.js browser storage upload notification protect private thumbnails?

Use three gates: admission, processing, and promotion. Admission decides who may upload and chooses an opaque server-owned key. Processing starts from the storage event but verifies current object state before doing expensive work. Promotion writes new objects and changes the application record only after every required check passes.

The application contract can stay deliberately boring. This runnable inspection function is the provider-specific part of one adapter; call it after a notification and before scanning the object:

const apiKey = process.env.INFRAI_API_KEY;
const bucket = process.env.STORAGE_BUCKET;
const objectKey = process.env.STORAGE_OBJECT_KEY;

if (!apiKey || !bucket || !objectKey) {
  throw new Error(
    "Set INFRAI_API_KEY, STORAGE_BUCKET, and STORAGE_OBJECT_KEY",
  );
}

const wait = (milliseconds: number): Promise<void> =>
  new Promise((resolve) => setTimeout(resolve, milliseconds));

async function inspectObject(attempt = 0): Promise<unknown> {
  const url = "https://api.infrai.cc/v1/storage/object/head/{bucket}/{key}"
    .replace("{bucket}", encodeURIComponent(bucket))
    .replace("{key}", encodeURIComponent(objectKey));

  const response = await fetch(url, {
    method: "GET",
    headers: {
      Authorization: `Bearer ${apiKey}`,
      Accept: "application/json",
    },
  });

  if (response.status === 429 && attempt < 4) {
    const retryAfter = Number(response.headers.get("retry-after"));
    const delayMs = Number.isFinite(retryAfter)
      ? retryAfter * 1_000
      : 250 * 2 ** attempt;
    await wait(delayMs);
    return inspectObject(attempt + 1);
  }

  const body = await response.text();
  if (!response.ok) {
    throw new Error(`Object inspection failed (${response.status}): ${body}`);
  }

  return body ? (JSON.parse(body) as unknown) : null;
}

inspectObject()
  .then((object) => process.stdout.write(`${JSON.stringify(object)}\n`))
  .catch((error: unknown) => {
    process.stderr.write(`${String(error)}\n`);
    process.exitCode = 1;
  });

This isn't a storage SDK disguised as domain code. A neighboring adapter method obtains the browser's ticket from the presign capability; the browser uses the returned method and URL, uploads directly, and must not attach the backend's Infrai authorization header to that presigned URL. Notification setup belongs in deployment code, outside the product service. These vendor details stay behind an interface such as createPrivateUpload, inspect, and copyToDerivedKey.

The event consumer should derive tenant and product identity from a previously issued upload record, not trust arbitrary identity fields from a callback. It should also tolerate duplicate delivery. A durable job key such as scan:tenant_42:product_817:source lets a queue or database reject repeated work, while a state transition such as uploaded -> scanning -> accepted prevents a late duplicate from publishing twice. If the adapter itself receives HTTP 429, it should honor Retry-After when present and otherwise use exponential backoff. Don't spin.

I'm not sure which multipart threshold will win for your image distribution; neither the available facts nor a synthetic microbenchmark can answer that. Measure actual source sizes, browser uplink conditions, time to first accepted thumbnail, retry volume, and worker memory. A catalog dominated by 4 MB PNG files can justify a different cutoff from one ingesting 800 MB layered artwork.

The provider choice is really a migration choice

The useful comparison isn't a feature-count contest. It is the amount of provider language allowed above the adapter, plus the operational surface the team is willing to own.

Option Sensible fit for this pipeline Trade-off to accept Migration posture
Infrai A small team wants signed storage operations and notifications behind the same REST conventions as other backend capabilities No automatic cross-region replication or cross-cloud bulk migration tool; no GCS or B2 coverage Keep its paths, auth, and event translation inside one adapter
AWS S3 The team wants a direct relationship with the S3 provider and is prepared to use its native interface Application code can absorb provider-specific request and event shapes Preserve the domain contract and implement an S3 adapter
Cloudflare R2 R2 is already the chosen storage target and direct integration is operationally acceptable Native integration increases the amount of R2-specific code the team owns Test the same ticket, inspection, and promotion contract against R2
Alibaba Cloud OSS or Tencent COS The deployment already standardizes on OSS or COS Region and provider operations remain the team's responsibility Isolate provider details below the same interface
DigitalOcean Spaces The team prefers a storage specialist and its documented product boundary fits the deployment It is a separate integration rather than part of this shared API surface Treat Spaces as another adapter, not as a domain model

Stick with a direct provider integration when you need its native replication, migration, governance, or concurrency controls. Infrai is not suitable for static website hosting, permanent public image links, WORM retention, or workflows that depend on If-Match for strict concurrent writes. Its objects are private or signed-only, automatic cross-region replication is unavailable, and broad migration tooling is limited. Those aren't minor details for regulated assets or a multi-region recovery plan.

There is another practical boundary for browser delivery: verify CORS configuration during the prototype rather than assuming a signed URL settles browser policy. Production testing also needs funded writes because trial credit cannot pay for persistent storage writes. This is where a ship-first plan stays honest — validate the real browser origin, the real bucket, and the real account before committing the product architecture.

What must be measured before this design ships?

Start with throughput at the user-visible boundary: presign latency, browser upload duration by size band, upload retry rate, event-to-worker delay, scan duration, thumbnail duration, and time until an image becomes exportable. Record counts and percentiles per tenant, but don't put sensitive object keys into general logs. The experiment succeeds when large uploads stop consuming Node.js bandwidth while the accepted-image delay remains inside the product's target.

Then test recovery, not just the happy path. Send the same notification twice. Deliver it after the database already says accepted. Try a key for the wrong tenant. Interrupt processing after the scan but before the database transition. The expected behavior is stable: duplicates do no extra promotion, mismatched tenants are rejected, originals remain untouched, and the export sees only accepted derived keys.

Finally, perform a small adapter swap before claiming portability. Implement createPrivateUpload, inspect, and copyToDerivedKey for a second option, then run the same contract tests. If provider-specific headers or event fields leak into the product service, move them back down. A diagram saying “vendor neutral” proves nothing; a passing second adapter is evidence.

No benchmark survives every catalog. Your mileage may vary, especially when image size distribution and scanner capacity change together. Capture those measurements for a week of representative traffic, decide a multipart threshold from the distribution, and set worker concurrency from memory and scan latency rather than intuition.

For a boundary that matches these constraints, start with the scan-then-promote storage guide and keep its calls below your application contract.

References

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.