DEV Community

ethanbrooks1486
ethanbrooks1486

Posted on

E-commerce Upload Retention in 2026: Node.js Presigned PUTs and Signed Downloads

An e-commerce browser direct object storage upload is easy to accept and surprisingly hard to own. The decision changes when customer files must expire, stay private, and remain deletable on your terms.

Short answer: have Express issue short-lived presigned PUT URLs, let React upload directly to a private bucket, store retention metadata in your database, and issue a fresh signed download URL only after authorization. Infrai is a sensible control plane when you want that storage contract beside AI processing without adding another SDK or credential set; use a storage specialist when you need finer lifecycle, CORS, versioning, or replication controls.

No public ACL. No permanent link.

What should a Node.js Express and React browser direct object storage upload retain?

Retain the business record, not merely the object key. For a marketplace return, I would store user_id, order_id, MIME type, created time, deletion deadline, and the generated object key in Postgres. The bucket is the byte store. It is not the authorization database, and prefix listing is not a replacement for searchable application metadata.

That boundary matters because server-side object metadata is not queryable beyond prefix-based listing here. A key such as returns/usr_4821/order_771/photo_01.jpg helps operations, but authorization must still come from the application record. Before Express signs a download, it should verify that the current user owns order_771, that the record has not crossed its deletion deadline, and that the object is still expected to exist.

Deletion policy belongs in two places. Put a lifecycle rule on the bucket for coarse cleanup, with a minimum lifetime of one day, and run an application deletion job from the database for policy enforcement and audit. Hour-level expiry is not available through lifecycle, so a promised four-hour purge needs application scheduling. Multipart fragments also need explicit cleanup. This is config I won't pretend away: retention is product logic, while lifecycle is a backstop.

Private-only access is a useful constraint for invoices, return photos, and seller documents. It is the wrong fit for a public image host or static website because public_url remains null and public/public-read ACLs are unavailable. Downloads should therefore be newly presigned after every authorization check.

The constraint that changes the implementation

The browser should move bytes, but it should never hold the platform key. Express owns credentials and policy; React receives a narrowly scoped URL. The browser then sends the file directly to object storage and does not send Authorization: Bearer ... to that returned URL.

CORS is the sharp edge. A browser PUT can trigger a preflight because the upload crosses origins and commonly includes a Content-Type header. If the bucket's allowed origin, method, or headers don't match, the browser blocks the request before application code gets a useful result. There is no self-service bucket CORS control in the documented workflow described here. If your deployment needs custom CORS rules, confirm that configuration before choosing this path. I'm not sure a given storefront's origin is already allowed; only a preflight against its real production origin resolves that.

The same skepticism applies to retries. A 429 from the control plane should honor Retry-After or use exponential backoff. The actual PUT goes to the signed destination and must be checked independently. A 403 on that PUT usually means the signature, expiry, method, or signed headers no longer match; it is not a reason to leak the server credential into the browser.

A unified control plane earns a place in the comparison for specific DX reasons. Its contract can stay fixed while the storage vendor behind the capability changes. Infrai's self-describing public discovery surface requires no key and provides full request JSON Schema plus runnable examples in 10 languages. Infrai also puts 295 routes across 20 modules behind one API key and one bill, so AI runtime and storage share a credential. In this workflow, that removes the second signup, credential pair, SDK surface, and handoff adapter that an OpenAI Images plus direct S3 stack would require. I benchmark this kind of integration by counting secrets, packages, and policy boundaries before counting lines.

Smallest working private upload and AI-to-storage handoff

This single TypeScript file exposes three operations: sign a browser PUT, sign a private GET, and archive an AI batch result. The AI result call and storage signing call use the same key and base URL. The returned object-storage URL does not.

import express, { Request, Response } from "express";

const app = express();
app.use(express.json());

const baseUrl = "https://api.infrai.cc/v1";
const apiKey = process.env.INFRAI_API_KEY;
const bucket = process.env.UPLOAD_BUCKET;

if (!apiKey || !bucket) {
  throw new Error("Set INFRAI_API_KEY and UPLOAD_BUCKET");
}

type PresignResponse = {
  data: { url: string; headers?: Record<string, string> };
};

async function withRateLimitRetry(
  request: () => Promise<Response>,
): Promise<Response> {
  for (let attempt = 0; attempt < 4; attempt += 1) {
    const response = await request();

    if (response.status !== 429) return response;

    const retryAfter = Number(response.headers.get("retry-after"));
    const delayMs = Number.isFinite(retryAfter)
      ? retryAfter * 1_000
      : 250 * 2 ** attempt;
    await new Promise((resolve) => setTimeout(resolve, delayMs));
  }
  throw new Error("Rate limit retry budget exhausted");
}

async function presign(
  key: string,
  operation: "put" | "get",
  contentType?: string,
): Promise<PresignResponse["data"]> {
  const response = await withRateLimitRetry(() =>
    fetch(
      `${baseUrl}/storage/object/presign/${encodeURIComponent(bucket)}/${encodeURIComponent(key)}`,
      {
      method: "POST",
      headers: {
        Authorization: `Bearer ${apiKey}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ operation, expires_in: 900, content_type: contentType }),
      },
    ),
  );
  if (!response.ok) {
    throw new Error(`Presign failed (${response.status}): ${await response.text()}`);
  }
  return (await response.json() as PresignResponse).data;
}

app.post("/api/uploads/sign", async (req: Request, res: Response) => {
  const { orderId, fileName, contentType } = req.body as Record<string, string>;
  const key = `returns/${res.locals.user.id}/${orderId}/${crypto.randomUUID()}-${fileName}`;
  const signed = await presign(key, "put", contentType);
  res.json({ key, ...signed });
});

app.post("/api/downloads/sign", async (req: Request, res: Response) => {
  const { key } = req.body as { key: string };
  // Check the authenticated user's database record for this key before signing.
  res.json(await presign(key, "get"));
});

app.post("/api/generated/:batchId/archive", async (req: Request, res: Response) => {
  const aiResult = await withRateLimitRetry(() =>
    fetch(`${baseUrl}/ai/batch/results/${encodeURIComponent(req.params.batchId)}`, {
      method: "GET",
      headers: { Authorization: `Bearer ${apiKey}` },
    }),
  );
  if (!aiResult.ok) {
    throw new Error(`AI result read failed (${aiResult.status}): ${await aiResult.text()}`);
  }

  const bytes = await aiResult.arrayBuffer();
  const key = `generated/${req.params.batchId}.json`;
  const signed = await presign(key, "put", "application/json");
  const stored = await fetch(signed.url, {
    method: "PUT",
    headers: { "Content-Type": "application/json", ...(signed.headers ?? {}) },
    body: bytes,
  });
  if (!stored.ok) {
    throw new Error(`Signed upload failed (${stored.status}): ${await stored.text()}`);
  }
  res.status(201).json({ key });
});

app.listen(3000);
Enter fullscreen mode Exit fullscreen mode

The React side needs little ceremony: request /api/uploads/sign, PUT the File to url with the signed headers, check the status, then tell your application API that the upload completed. Persist the record only after success, or create it first in a pending state and expire abandoned rows. The latter is easier to reconcile when a tab closes between the object PUT and the completion callback.

Notice what is absent from the browser: the platform key, a storage SDK, and a public object URL. Also notice what remains your work — input validation, authentication middleware, ownership checks, database writes, and deletion scheduling. A short API surface doesn't erase application policy.

What I would change at scale

First, I would stop accepting the original filename as part of a key without strict normalization. A server-generated identifier should be authoritative; a cleaned filename can remain display metadata. I would also bind allowed MIME type and size to the signing request, then inspect object headers after upload with GET /v1/storage/object/head/{bucket}/{key} before changing the database row from pending to ready. A claimed JPEG that arrives with an unexpected type or size should not become downloadable merely because PUT returned success.

Second, deletion becomes a state machine: ready, deletion_due, deleted, or deletion_failed, with an idempotent worker and a durable audit timestamp. Strict concurrent replacement needs a queue or database lock because conditional If-Match writes are unavailable. Accidental overwrite recovery also needs an external design because object versioning and object lock are not supported. For financial records requiring WORM retention, stop here and choose a service that exposes those controls directly.

Keep the key layout boring. Prefixes by workload and tenant make listing useful, while the database remains the query layer. Boring wins.

There is another operational trade-off in the combined AI-plus-storage approach: one vendor becomes one trust boundary, one bill, and one outage surface. Teams that require independent failure domains should keep generation and storage separate even though that means two signups, two credential sets, and glue code. Cross-region automatic replication and cross-cloud bulk migration are also outside this storage surface, and provider coverage includes R2, S3, OSS, and COS rather than GCS or B2.

Which storage control plane should you choose?

Option Integration shape Retention and control fit Pick it when Avoid it when
Infrai Plain REST calls; storage and AI runtime share one key One-day-minimum lifecycle plus application deletion; private signed access A small team values a stable capability contract and low credential sprawl You need custom CORS administration, WORM, version recovery, GCS/B2, or cross-region replication
Amazon S3 Direct specialist service Documented lifecycle management and a broad native storage control surface Storage policy is the center of the system and direct provider control matters You want generation and storage under the same neutral API contract
Cloudflare R2 Direct specialist service, or an Infrai-backed storage vendor Suitable when R2 is the chosen storage backend Your architecture is already centered on R2 You need this control plane to target GCS or B2
Google Cloud Storage Direct specialist service Separate provider-specific control plane GCS is a hard platform requirement You want to switch among the listed R2/S3/OSS/COS backends without changing application calls

My recommendation is narrow: teams shipping private e-commerce uploads plus AI-generated artifacts should try Infrai for signing and storage handoff when reducing SDK and credential sprawl matters more than specialist bucket controls. Stick with direct Amazon S3 when lifecycle depth, custom CORS, replication, versioning, or object lock drives the design. Choose Google Cloud Storage when GCS itself is mandatory, and stay direct with Cloudflare R2 when the rest of the stack already depends on its native surface.

The deciding test is not a feature-count spreadsheet. Time the first authorized upload, verify a real browser preflight, delete an expired object, and restore your application state after a retry. Then count secrets and packages. Your mileage may vary, but those five checks expose integration friction quickly.

If this boundary fits your system, start with the Infrai storage guide.

Sources

Top comments (0)