Media Library Asset Replace#
Overview#
Replacing an asset in Strapi's Media Library swaps a file's binary content while deliberately keeping its URL unchanged. The stored hash and ext are never regenerated ā this keeps all content-type relations stable across the replace. The flow is triggered via POST /upload?id=<id> (the "Replace Media" button in the asset details UI).
The server-side orchestration entry point is replace() in upload.ts.
Replace Flow (Server)#
replace() runs these steps in order:
- Size validation ā
provider.checkFileSize()runs before any write . - Hash & extension freeze ā The incoming file is force-assigned the original DB record's
hashandext, keeping the public URL constant . - Folder preservation ā If
fileInfo.folderis not sent,folderPathis copied from the DB record to prevent orphaning on folder-deletion queries . - Format reset ā
formatsis cleared to{}before any provider call; the provider repopulates it with fresh thumbnails and responsive variants . - Provider dispatch ā branching on same vs. cross provider, and image vs. non-image :
- Same provider + image:
replaceImage()pairs each format (thumbnail, responsive sizes) with its old counterpart and routes throughprovider.replace(). Formats present on the old file but absent from the new image are deleted. - Same provider + non-image: calls
provider.replace()for the main file, then deletes any leftover image formats. - Cross-provider: falls back to a fresh upload on the new provider without touching the old one.
- Same provider + image:
After a successful replace, update() is called and a media.update webhook is emitted .
Provider Service Dispatch#
provider.ts ā replace() implements a tiered dispatch, introduced in PR #26582:
provider.replaceStream(newFile, oldFile)ā preferred (stream-based) .provider.replace(newFile, oldFile)ā buffer-based fallback .delete(oldFile)+upload(newFile)ā silent fallback for providers that implement neither .
Before PR #26582, every replace was always the delete + upload sequence, giving providers no signal that the two operations were a single replacement .
First-party provider behaviors after PR #26582:
| Provider | Replace behavior |
|---|---|
| local | Writes new file in place; unlinks old file only if path changed |
| aws-s3 | PutObject on the same key; old key deleted only if different |
| cloudinary | When public_id is preserved: uploads with overwrite: true + invalidate: true; otherwise uploads then destroys old asset |
Cloudinary Folder Configuration Ignored on Replace#
Status: Open bug (as of Strapi 5.51.0)
When actionOptions.upload.folder is set, new uploads land in the correct Cloudinary folder. That same setting is silently ignored during a replace.
Root cause: In register.ts ā createProvider(), every provider method is wrapped as:
async (file: File, options = actionOptions[methodName]) =>
providerInstance[methodName](file, options);
This wrapper assumes a 2-argument (file, options) signature. It works for upload(file) because options acts as a defaulted second argument. But replace(newFile, oldFile) takes two required arguments ā the service calls provider.replace(newFile, oldFile) with both positional slots already filled , so the wrapper's options = actionOptions['replace'] default is never reached. The Cloudinary replace() function accepts a customConfig third argument that would inject the folder , but no config is ever forwarded.
Effect: Files replaced via Cloudinary land in the root of the account rather than the configured folder.
Workaround (unofficial): Upload the replacement as a new asset (which respects folder config), update content-type relations, and delete the old asset. Alternatively, extend the provider in a custom plugin to inject folder settings into the replace call path.
CDN & Browser Caching Side Effects#
Because the URL never changes after a replace, CDNs and browsers can serve the old file:
Admin panel cache-busting:
- The legacy
PreviewBoxcomponent appends?updatedAt=<timestamp>for the crop URL but switches to ablob:object URL when a local replacement is staged . Theblob:URL cannot carry a cache-buster query param, so it is not affected by signed-URL guards. - The new
AssetPreviewcomponent (new ML, feature-flag gated) appends?v=<timestamp>derived fromupdatedAtfor all non-signed URLs. Signed URLs are explicitly excluded because appending a parameter invalidates the SigV4 signature . - The new
AssetCropEditoruses?updatedAt=<timestamp>(a different key fromAssetPreview'sv=) so that the crop image and display image get distinct HTTP cache entries. This prevents the crop'scrossOrigin="anonymous"request from reusing the display image's non-CORS cached response and tainting the canvas .
Atomic replace & CDN invalidation (PR #26582, merged Strapi 5.49.0): The atomic replace method gives providers a hook to perform cache invalidation in the same API call. Cloudinary uses invalidate: true alongside overwrite: true when the public_id is preserved .
Diagnosing stale content after a replace:
- Check for a CDN (CloudFront, Cloudflare, nginx) in front of storage and clear it manually.
- Hard-refresh or open the URL in a private window to rule out local browser cache.
- Confirm the admin preview URL includes a
?v=or?updatedAt=param ā its absence in the modal before Strapi 5.42.1 was the primary cause of stale previews .
Known Bugs & Regression History#
| Issue | Root cause | Fixed in |
|---|---|---|
| File content unchanged, only metadata updated (no client error) | Frontend sent replacement as single-element files array; controller rejected it with Cannot replace a file with multiple ones | #26405 |
| Stale content served after replace | CDN/browser cache; URL unchanged by design | Mitigated by ?updatedAt= in 5.42.1; atomic replace in 5.49.0 |
| Cloudinary folder ignored on replace | actionOptions wrapper uses 2-arg signature; replace needs 3 args | Open as of 5.51.0 |
| CORS canvas taint in crop editor | Crop image URL and thumbnail URL had same HTTP cache entry; different crossOrigin policies collided | Fixed in PR #26901 |
Key Source Files#
| File | Purpose |
|---|---|
upload.ts | Replace orchestration: replace(), replaceImage() |
provider.ts | Tiered provider dispatch: replaceStream ā replace ā delete+upload fallback |
register.ts | createProvider wrapper that injects actionOptions (source of the folder bug) |
upload-cloudinary/src/index.ts | Cloudinary replace/replaceStream with overwrite + invalidate |
Legacy PreviewBox.tsx | Legacy asset preview; blob: URL swap + ?updatedAt= cache-buster for crop |
New AssetPreview.tsx | New ML asset preview; ?v= cache-buster, signed URL guard |
New AssetCropEditor.tsx | New ML crop editor; ?updatedAt= cache-buster with distinct key from display image |
| PR #26582 | Atomic replace refactor ā design rationale, per-provider behavior |