How to Store AI-Generated Images per User Folder — Object Lifecycle Checks
Decision note Short answer: use private object storage with tenant-scoped keys, short-lived download URLs, and a lifecycle rule as the backstop. Keep deletion authorization in your Node/Express service. That combinatio
Decision note
Short answer: use private object storage with tenant-scoped keys, short-lived download URLs, and a lifecycle rule as the backstop. Keep deletion authorization in your Node/Express service. That combination keeps a logistics SaaS simple to ship while preserving an audit trail for each customer's generated image.
| Option | Access control | Delivery simplicity | Best fit |
|---|---|---|---|
| Public bucket and signed-looking filenames | Weak | High | Prototypes only |
| Private bucket, app-mediated reads | Strong | Medium | Multi-tenant production |
| Private bucket with direct browser uploads | Strong if policy is right | High at scale | Large files and busy clients |
I run a one-person SaaS, so my test is revenue per hour: outsource the undifferentiated storage mechanics, but keep the policy decision in code I can review. For a logistics customer, an image might be a pallet label, a damage photo, or a generated route diagram. A leaked key can expose more than pixels; it can reveal a tenant's shipment identifiers.
Why tenant keys are a security boundary
Object storage has a flat namespace wearing folder-shaped clothes. The string tenant_42/images/2026/09/03/8f2c.png is not an authorization rule. The service must derive that prefix from the authenticated tenant, then verify the object belongs to that tenant before every read, delete, or restore operation.
I first thought a random UUID in the filename was enough. It wasn't. UUIDs stop guessing; they do not stop a confused-deputy bug where tenant A asks the API to fetch tenant B's known key. The API should accept an image ID, load its database row, compare tenantId, and only then touch storage.
Use immutable metadata for the ownership link. Store tenantId, objectKey, contentType, bytes, createdAt, and deletedAt in a database. Keep the object key opaque to clients. A soft-delete row gives support a trace and lets a retention worker perform the physical delete later.
How should Node and Express store AI generated images per user folder?
The following example keeps the storage adapter deliberately boring. It assumes an S3-compatible client, but the same interface can wrap a self-hosted service or a cloud provider. The important part is the authorization sequence, not the brand.
import express from "express";
import crypto from "node:crypto";
const app = express();
app.use(express.json({ limit: "1mb" }));
interface ImageRow {
id: string;
tenantId: string;
objectKey: string;
contentType: string;
createdAt: Date;
deletedAt: Date | null;
}
const images = new Map<string, ImageRow>();
function keyFor(tenantId: string, id: string): string {
const day = new Date().toISOString().slice(0, 10);
return `tenants/${tenantId}/images/${day}/${id}.bin`;
}
app.post("/images", async (req, res) => {
const tenantId = String(req.header("x-tenant-id") ?? "");
const contentType = String(req.body.contentType ?? "image/png");
const data = String(req.body.base64 ?? "");
if (!tenantId || !data.startsWith("data:")) return res.status(400).json({ error: "invalid image" });
const id = crypto.randomUUID();
const objectKey = keyFor(tenantId, id);
const row: ImageRow = { id, tenantId, objectKey, contentType, createdAt: new Date(), deletedAt: null };
await storage.put(objectKey, Buffer.from(data.split(",")[1], "base64"), contentType);
images.set(id, row);
return res.status(201).json({ id });
});
app.get("/images/:id", async (req, res) => {
const tenantId = String(req.header("x-tenant-id") ?? "");
const row = images.get(req.params.id);
if (!row || row.tenantId !== tenantId || row.deletedAt) return res.sendStatus(404);
const url = await storage.presignGet(row.objectKey, 300);
return res.json({ url, expiresInSeconds: 300 });
});
In real code, x-tenant-id comes from a verified session or token, never from an untrusted client field. Validate MIME type and decoded byte length before upload. Reject path separators in user-controlled IDs; here the ID is generated server-side. The five-minute URL is a delivery choice: browsers get direct bytes, while the bucket remains private.
Do not base64 large images through JSON in production. Multipart upload is designed for large objects and lets you retry parts instead of restarting the whole transfer. AWS documents the multipart flow and its requirement to complete or abort uploads; that operational detail matters even when your backend is provider-neutral.
How do I delete old images from per-user object storage safely?
Application deletion and lifecycle expiration solve different problems. An authenticated delete endpoint can remove one image now. A lifecycle policy can expire objects after, say, 30 days when a job is late or a row was lost. The policy should target a tenant prefix only if your storage system supports prefix filters with the semantics you have tested.
The delete worker should be idempotent. Mark rows first, delete by the stored key, then record the completion timestamp. A retry seeing the same row must produce the same final state. Never construct a delete key from a request's tenantId and filename; use the database value that passed authorization.
Here is the failure drill I use before enabling a retention rule. Create two tenants, upload the same-sized image for each, and capture both database rows. Revoke tenant A's session, then replay its old delete request with tenant B's image ID. The handler must return the same not-found response it would return for any object outside A's scope, and the worker queue must contain no delete command for B. Next, stop the worker after it marks A's row and restart it with the same message. The second pass should observe deletedAt, verify the object key still belongs to A, and finish without a duplicate alert. Finally, advance the staging clock beyond the lifecycle cutoff and compare the bucket inventory with the database reconciliation report. This sequence catches authorization drift, non-idempotent retries, and lifecycle rules that match a broader prefix than intended. It takes minutes and saves a late-night incident.
No shortcuts.
async function deleteImage(tenantId: string, id: string): Promise<void> {
const row = images.get(id);
if (!row || row.tenantId !== tenantId || row.deletedAt) return;
row.deletedAt = new Date();
images.set(id, row);
await storage.delete(row.objectKey);
}
async function expireOldImages(cutoff: Date): Promise<number> {
let count = 0;
for (const row of images.values()) {
if (!row.deletedAt && row.createdAt < cutoff) {
await deleteImage(row.tenantId, row.id);
count++;
}
}
return count;
}
There is a trade-off here. A database-first mark can briefly point at an object that still exists, while an object-first delete can leave a row that points nowhere if the process stops. Pick one ordering, document it, and expose a reconciliation metric. I prefer database-first for tenant privacy, then a retryable physical delete. Your mileage may vary if legal hold requires retrieval until a separate approval clears it.
What should you test before shipping per-user object storage?
Write tests around boundaries, not just happy-path uploads:
- Tenant A cannot read, restore, or delete tenant B's object, even with B's object ID.
- A deleted row never produces a new download URL.
- A retry of the deletion worker does not fail the batch or resurrect metadata.
- An aborted multipart upload is cleaned up and does not accumulate storage charges.
- Lifecycle expiry is observed in a staging bucket with a short rule before production rollout.
Log an event ID, tenant ID, image ID, operation, byte count, and result. Do not log the image bytes or long-lived credentials. OWASP's Secrets Management Cheat Sheet recommends limiting secret exposure, rotating credentials, and keeping secrets out of source control. Give the worker a role that can delete only the bucket and prefixes it needs.
Measure restore latency and deletion lag separately. A green API response does not prove the object disappeared; a lifecycle rule may be asynchronous. Alert on old rows with deletedAt set but no completion timestamp, and on incomplete multipart uploads. These are the signals that protect a solo founder's weekends.
Private, app-mediated reads are not suitable when clients upload multi-gigabyte assets over unreliable links and your API would become a bandwidth bottleneck. In that case, issue a scoped upload policy, let the browser upload directly, and require a callback or polling step that verifies the final object size and checksum before publishing it to the tenant.
Public objects can be acceptable for deliberately public marketing images. They are a poor default for shipment evidence or per-user AI output. Stick with a public CDN path only when the data classification says disclosure is harmless and revocation is unnecessary.
The least complex production design is therefore conditional: private keys, tenant checks, short-lived reads, and lifecycle expiry for sensitive logistics data; direct multipart delivery when file size makes proxying expensive. Ship that baseline weekly, then add versioning, legal holds, or a queue when the workload proves you need them. The boring path is the one I can maintain between customer calls, and that matters more than a clever abstraction when one person owns the pager.
Ship weekly.
References
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.