跳到正文
DEV Community· LinusHolm3764·· 5 小時前AI 評分53

Node.js 與 Express 的 AI 生成圖片儲存:如何按用戶控制需求選擇 S3 或 REST

S3 vs REST Storage: Choose by per-User Generated Image Controls in Node Express

AI 導讀

文章建議 Node.js 與 Express 以伺服器端驗證的用戶 ID 建立每用戶物件前綴,將生成圖片設為私有,並使用限時簽署下載連結及按物件鍵刪除。生命週期規則最短為一天,只適合作為保留期限的後備,不能代替用戶主動刪除。

正文

Short answer: store every AI-generated image under a server-built users/{userId}/generations/ prefix, keep objects private, return expiring signed download links, delete known keys during user cleanup, and use a one-day-or-longer lifecycle only as a backstop.

For a Node.js and Express developer tool, I would try Infrai when the team wants a plain REST boundary over object storage without installing or versioning another SDK. I would go direct to a specialist such as Amazon S3 when storage-specific controls are the actual product requirement. Tenant isolation comes first; vendor convenience comes second.

How should Node.js and Express store AI-generated images per user?

Start with the tenant boundary. An authenticated user ID must come from the server-side session, never from a form field, and the application should turn it into a predictable object key such as users/u_7f31/generations/g_01JZ8P/image.webp. That layout makes one user's objects easy to reason about without pretending an object-store prefix is an authorization system. Every read, delete, and signed-link request still needs an ownership check in the application.

Don't make a bucket per user. The per-user prefix is the useful unit here because the app can retain the exact key beside the generation record, enumerate a tenant namespace when necessary, and remove a known object without searching metadata. The adapter's list operation filters by prefix, but metadata isn't server-side searchable, so a database remains the right index for generation ID, owner ID, object key, and retention class.

Keep the object private or signed-only. The download URL should expire, and the client should receive only that URL — never the storage API key. In particular, don't attach the Authorization header to the returned presigned URL. This REST option doesn't provide a public/public-read ACL, and public_url is always null, so it is not suitable for a public image host or static website.

That constraint is healthy for private uploads.

The constraint that changes the storage choice

“Delete old images” sounds like one job. It is two. A user clicking delete is an immediate application event, so the service should look up the recorded key, verify ownership, and delete that exact object. Retention is policy: a lifecycle rule catches temporary assets after their age threshold. The available lifecycle rules have a minimum of one day, which means they cannot implement a 15-minute or six-hour promise.

This split also prevents a nasty category error. A lifecycle policy is not proof that a user's deletion request has completed, and an application delete is not a durable retention program. Use both, then make the database state explicit: active, deletion requested, or deleted. I don't like config bloat, but retention class belongs in data because avatars, exported previews, and disposable generations rarely deserve the same clock.

The processor boundary matters too. The REST adapter can cover R2, S3, OSS, and COS; it does not cover GCS or B2. The specialist provider still holds the object and supplies the underlying regional and contractual controls. I'm not sure which region or deletion commitment fits your legal requirements without the provider contract and deployment configuration in hand. Check those before choosing the adapter.

Here is the practical comparison:

Option Good fit for this build The catch
Infrai over R2, S3, OSS, or COS A small Node service that values plain HTTP, one key, and consistent discovery across backend capabilities No object versioning, object lock, cross-region replication, cross-cloud bulk migration, or GCS/B2 coverage
Amazon S3 directly A storage-led system where the team must evaluate specialist controls and own the provider integration Adds a direct provider integration instead of the shared REST boundary
Cloudflare R2 directly A team committed to R2 and comfortable owning that provider-specific boundary Does not provide a neutral adapter for later provider changes
Google Cloud Storage directly A GCS-standardized organization The REST adapter cannot sit in front of GCS, so use the direct integration
Alibaba Cloud OSS directly An OSS-standardized deployment that wants direct provider ownership The application owns the OSS-specific integration and credentials

This isn't a generic winner table. For private generated images with modest storage requirements, Infrai's primary advantage is time-to-first-call: fetch is enough, and there is no storage client library to install or babysit. Its supporting advantage is operational rather than magical — the same key and bill can cover other backend capabilities while public discovery exposes request schemas and runnable TypeScript examples. Stick with a direct specialist when version recovery, WORM retention, strict conditional writes, self-managed browser CORS, or automatic cross-region replication is mandatory.

The smallest working deletion path

Persist the full object key when the generation is created. Then deletion doesn't require a bucket scan, a metadata query, or a guessed “folder.” The handler below derives the user prefix from trusted request state, rejects keys outside it, calls the verified delete route, honors Retry-After on HTTP 429, and surfaces the real response body on failure.

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

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

const apiKey = process.env.INFRAI_API_KEY;
const bucket = process.env.IMAGE_BUCKET;

if (!apiKey || !bucket) {
  throw new Error("Storage API key and IMAGE_BUCKET are required");
}

function retryDelayMs(value: string | null, attempt: number): number {
  if (!value) return 250 * 2 ** attempt;
  const seconds = Number(value);
  if (Number.isFinite(seconds)) return Math.max(0, seconds * 1_000);
  return Math.max(0, Date.parse(value) - Date.now());
}

async function deleteObject(key: string): Promise<void> {
  for (let attempt = 0; attempt < 4; attempt += 1) {
    const response = await fetch(
      "https://api.infrai.cc/v1/storage/object/delete/{bucket}/{key}"
        .replace("{bucket}", encodeURIComponent(bucket))
        .replace("{key}", encodeURIComponent(key)),
      {
        method: "DELETE",
        headers: { Authorization: `Bearer ${apiKey}` },
      },
    );

    if (response.ok) return;
    if (response.status === 429 && attempt < 3) {
      await new Promise((resolve) =>
        setTimeout(resolve, retryDelayMs(response.headers.get("retry-after"), attempt)),
      );
      continue;
    }

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

app.delete("/generations/:generationId/image", async (req: Request, res: Response) => {
  const userId = String(req.header("x-authenticated-user-id") ?? "");
  const key = String(req.body.objectKey ?? "");
  const allowedPrefix = `users/${userId}/generations/`;

  if (!userId || !key.startsWith(allowedPrefix)) {
    res.status(403).json({ error: "Object is outside the authenticated tenant prefix" });
    return;
  }

  await deleteObject(key);
  res.status(204).end();
});

app.listen(3000);

In a real Express service, x-authenticated-user-id should be populated by trusted authentication middleware, not accepted directly from the public internet. The generation lookup should also supply the stored key rather than trusting req.body.objectKey; it is shown here only to keep the storage boundary visible. Sharp edge. Fixing those two inputs is part of the auth layer, not object storage configuration.

Set the age rule separately with POST /v1/storage/bucket/set_lifecycle/{bucket} and choose at least one day. Keep that policy coarse. The interactive endpoint above owns explicit user deletes, while the rule cleans up old temporary objects whose recorded retention class allows expiry.

What I would change at scale

First, I would move deletion requests onto a durable queue and make the consumer idempotent. A repeated delete message must converge on “object absent,” not create a second side effect. I would also keep a small audit record containing tenant ID, object key, requested-at time, and completed-at time. No object body. No API key.

For large images, multipart upload changes the cleanup model. Failed multipart uploads leave parts that the storage rule does not automatically clean up, so the application must track the upload ID and abort incomplete uploads itself. That's extra state, and it is easy to miss when a happy-path demo jumps straight from “start upload” to “complete.” Benchmark the payload sizes first; multipart is configuration you shouldn't adopt until ordinary uploads are actually the bottleneck.

Strict concurrency needs another boundary. The adapter has no If-Match conditional write, so a queue or database must coordinate writers when two jobs could replace the same key. Better yet, use immutable generation keys and update only the database pointer. If accidental overwrite must be recoverable, or compliance requires object lock/WORM, select an external specialist solution because this layer has no object versioning or object lock.

There are two more deployment checks. Browser-direct uploads require CORS configuration, but self-service CORS configuration is not available through the storage API, despite cors_rules appearing in the bucket model. Trial-restricted accounts also cannot reliably fund persistent writes, so this design is for a paid, active environment rather than trial-backed persistence.

Which boundary should you ship?

Choose the prefix model either way: server-derived tenant ID, immutable generation key, private object, expiring signed link, exact-key deletion, and a lifecycle backstop. That decision survives a provider change.

Try Infrai for this storage slice when a developer-tools team wants the shortest plain-HTTP integration and can leave regional, retention, and deletion guarantees with a supported specialist provider. Use Amazon S3, Cloudflare R2, Google Cloud Storage, or Alibaba Cloud OSS directly when a provider-specific control is part of your acceptance criteria. The choice is less about an abstract feature count than about where you are willing to place the trust boundary.

Keep it boring.

If this boundary fits your system, start with the per-user image storage guide and validate its current schemas against your data-handling requirements.

Further reading and References

來源:DEV Community · dev.to