Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Media Library
Status: Implemented
Target: Spree 6.0
Depends on: 5.4-6.0-product-media-system.md (shipped data model: Spree::Media, spree_variant_media, media types, focal point, external video)
Author: Damian Legawiec
Last updated: 2026-08-24
Summary
Give merchants a store-wide media library in the dashboard: browse and search every uploaded image and video in one place, upload files before deciding where they go, reuse a file on another product without re-uploading it, and see where a file is used before deleting it. On top of the library, the rich text editor gains image embedding — images in product, category and collection descriptions come from the library instead of not existing at all.
This is deliberately the small version of a media library. Spree::Media
keeps its current shape — one row owned by one viewable (product or variant),
with per-row position, alt text, focal point and variant links. Reuse is
implemented by duplicating the row while sharing the underlying
ActiveStorage::Blob: a copy is a new Media row plus a new attachment row
pointing at the same blob, so there is no second file in storage, every
already-processed rendition is reused, and the copy still gets its own alt text
and position in its new context. A shared-asset model with attachment join
tables (one asset row referenced from many products) was considered and
rejected — it would rework everything that hangs off the polymorphic
viewable (list scoping, counter caches, thumbnail denormalization, the
variant-link security boundary) for a benefit blob sharing already provides at
the storage level.
Key Decisions (do not deviate without discussion)
- Blob sharing is the reuse mechanism, not a shared asset entity. "Use this
file on another product" creates a new
Spree::Mediarow and attaches the existing blob. Deletion safety comes from the standard Rails foreign key fromactive_storage_attachmentstoactive_storage_blobs: purging a copy's blob raises a foreign-key violation while other attachments reference it, andActiveStorage::PurgeJobdiscards on exactly that error, so the file survives until the last reference is gone. That FK is load-bearing — the "no foreign key constraints" rule covers Spree's own tables, and this Rails table must keep its constraint. spree_mediagains astore_idcolumn (2026-08-24). An unattached library upload has noviewableto derive tenancy from, so the library cannot be scoped through products.belongs_to :storebecomes required on new rows; existing rows are backfilled from their viewable's product store by an upgrade task in the 5.6→6.0 manifest. Store-owned means theStoreScopeGuardtripwires apply to every new media query.- The library lists every
Spree::Mediarow in the store, attached or not. "In the library" is not a flag — an unattached row is simplyviewable_id: nil(already legal today; session uploads rely on it). No second bucket, no folders. Organization is search and filters (type, attachment state, filename); anything richer waits for demonstrated need. - Reuse rides the existing nested create (2026-08-24).
POST /products/:id/media(and the variant twin) acceptssource_media_idas a third transport shape besidesigned_idandurl— "create this product's media from that library row". Copies attachment blob, poster blob, alt and focal point; position and variant links are the new context's own. No separate duplicate endpoint. - Media is its own permission resource (2026-08-24).
Spree::Mediaused to be a subject ofproducts, which was right while a file belonged to one product. Now that a row can be placed on a category or collection, the library lists, traces and deletes across all three — soread_productsalone could name a category andwrite_productscould strip its image. Media is registered asread_media/write_mediain the catalog group, and the split follows Shopify's: reaching a file through a product staysproducts(the nested gallery is that product's own media, reached through a product the caller can already see), while enumerating the library, asking where a file is used, or deleting one everywhere needsmedia. A groupedread_catalogwas considered and rejected — it would have removed the boundary rather than fixed it, and cost the ability to grant categories without products. Constraint: every path that creates an attachment must check the media key, not just the endpoints — WooCommerce ships this bug today, where its URL-ingest helper creates attachments under the product capability while the media endpoint requires the upload one. - The library picker serves every attachment field, not just product media
(2026-08-24). Picking an existing file yields the blob's
signed_id, which anyhas_one_attachedwriter accepts — so category, collection, store and seller image fields get "choose from library" through their existing endpoints, with the same blob-sharing economics. - Category and Collection are real Media viewables (2026-08-24, supersedes
the "those fields stay bare attachments" clause above for these two models;
implemented same day). A file uploaded to a category or collection image slot
was invisible to the library — no
Mediarow meant no grid entry, no search, no reuse. Rather than mirror it as an unplaced row (which would have made the placement filter lie: "not used yet" about a file on a category), the slots reconcile into actual placements:Spree::HasLibraryMedia(has_library_media :image, :square_imageon both models) createsMediarows withviewable: categorysharing the slot blobs on save, and clearing a slot unplaces the row (back to the library pool) rather than destroying it — destroying would take the file with it.Spree.media_viewable_typesis now a registry (Product, Variant, Category, Collection);ensure_storereads the viewable's own store first. The namedimage/square_imageattachments remain the operational storage every existing serializer and storefront reads; the placements are the library's view of them, and the future category gallery is additive rows on the samehas_many :mediaassociation (dependent: :nullify— deleting the category returns its files to the library). Until that gallery exists, reconciliation owns every placement on these records — do not create Media rows on a category by another path, they will be unplaced on the next slot change. Sellers and stores stay bare — logos are branding, not merchandising media. Existing images backfill viaspree:upgrade:backfill_library_media_placementsin the 5.6→6.0 manifest. - Library delete detaches on confirmation (2026-08-24, revised the same day
from "refuse until the merchant clears each use").
DELETE /admin/media/:idon a file in use returns 422 with the usage list; passingdetach=true— which the dashboard sends after a confirmation naming the count — runsSpree::Media::Destroy, removing the file from every placement and plain attachment in its store, then deleting the row so the blob purges. Clearing each use by hand was busywork the usage list already knew how to do; the refusal survives as the default so an API client cannot pull a file out from under a catalog by accident. Rich text embeds are plain URLs with nothing to detach, so those descriptions lose the image — the confirmation says so. The product-nested destroy is untouched: removing a file from one gallery is not deleting the file. - Rich text embeds are plain
<img>URLs, not tracked references (2026-08-24). The editor inserts a URL to a non-cropping rendition of a library file. No join rows track which descriptions use which media; "where used" for rich text is a best-effort blob-key search and deletion warns generically. Tracked content references are a follow-up if merchants hit broken images in practice. - The sanitizer widens in the same change that gives the editor the image
node — per the doctrine written into
Spree::RichTextSanitizer:imgjoinsallowed_tagsandsrc,alt,width,heightjoinallowed_attributesexactly when the Tiptap Image extension lands.srcmust survive only withhttpsor relative URLs —data:andjavascript:URIs are stripped (add an explicit scrubber if the stock protocol filtering proves not to cover it). - Deleting a library row that is in use requires seeing the usage. The dashboard delete flow shows where the row and its blob are referenced (products, variants, and other attachments sharing the blob) before the destructive confirm.
- A copy takes the target's store, never the source's (2026-08-24, found in
implementation).
duplicate_forleavesstore_idunset soSingleStoreResourceresolves it from the new owner's product — media follows the thing it is a picture of. Copying the source's store instead would have written a row into the wrong tenant whenever a placement crossed stores; the controller's scoped lookup hides that, but the model has to be right on its own. - Reuse works on both product write paths (2026-08-24).
source_media_idis accepted by the nested media create and by the inlinemedia:list on the product itself — the dashboard's product Save uses the latter, so supporting only the endpoint would have left the picker silently dropping its files. acts_as_listis scoped bystore_idtoo (2026-08-24, review). An unplaced row has no viewable, so with only[viewable_id, viewable_type]in the scope every store's library uploads shared one list — positions bleeding across tenants, and a store-less position query that the store-scope guard rightly refuses.- The library lists files, not placements (2026-08-24). Reuse shares a blob
across rows, so one picture on three products is three rows — listing them
all showed the same image repeatedly. The index groups by blob
(
Media.distinct_by_file), but only the index: a hidden row is still a real record a client holds the id of, so member actions resolve any row. - Usage includes the row's own placement (2026-08-24). Excluding it — on the reasoning that "its own placement is not news" — meant a file sitting on a product reported "not used anywhere", which is worst in the case the panel exists for. A video's file and poster are two blobs on one row, so the result is deduplicated by owner.
- One preview component, two surfaces (2026-08-24).
MediaPreviewrenders a file by kind — external video as its provider embed, uploaded video as a player, image with its focal point marker — and is used by both the product gallery's edit sheet and the library's detail panel, so a file looks and behaves the same in both. It lives indashboard-ui(ui/media-preview.tsx) and is headless per that package's rule: everything arrives as props, so the same component serves a saved record and a form row that has only blob URLs because it is not saved yet. Provider links are parsed by the caller — it takes a readyembedUrl, which keeps the app'sparseVideoUrlout of the design system and matches the server being the authority on embeddability (the library passes the serializer'svideo_embed_url; the product form passes what it already parsed for its own validation). The grid keeps its own still-only tile — dozens of video players in one view is not a gallery. Poster upload now appears in both places too; the library saves it immediately (no surrounding form), the product sheet carries it on the form. Without it the picker had nothing to hand a plain attachment field, and the "generic image fields adopt library files" decision below was unimplementable. - Usage is scoped to the file's own store (2026-08-24, review). A shared
blob can reach another tenant's records; reporting them named that tenant's
data to a merchant who cannot see it anywhere else. All three sources filter
by the media's
store_id, and the rich text search covers content models only — order and customer internal notes are staff correspondence on the two largest tables, and no merchant embeds a library image in one.
Design Details
Model
Spree::Media changes are additive:
store_idcolumn,belongs_to :store, required on create for new rows (validation, not a DBnull: false, until the 6.1 cleanup — legacy rows backfill first). Uniqueness/scoping and the library index key off it.- A
libraryscope is unnecessary — the library ISstore.media. New scopes:attached/unattached(onviewable_idpresence), filename search via a join to the attachment blob. - Duplication:
Spree::Media#duplicate_for(viewable)builds the copy — attachesattachment.bloband (when present)poster.blob, copiesmedia_type,alt,focal_point_x/y,external_video_url; leavespositiontoacts_as_listin the new scope and copies no variant links. Counter caches and thumbnail denormalization fire through the existing callbacks because the copy is an ordinary create.
Blob-level usage lookup (for the delete flow and the media detail panel): given
a row, find all active_storage_attachments sharing its blob ids, resolve to
owner records, and present them grouped. This is a read-side service —
Spree::Media::Usage — not columns.
Admin API
GET /api/v3/admin/media— new top-level, store-scoped index (the library). Filters:media_type, attached/unattached, filenameq, product. Existing nested indexes stay for the product/variant galleries.POST /api/v3/admin/media— top-level create for upload-first: accepts the samesigned_id/url/ external-video shapes as the nested create but builds an unattached, store-owned row.PATCH /api/v3/admin/media/:id,DELETE /api/v3/admin/media/:id— manage library rows (rename alt, delete). Delete responds with usage info on the serializer so the dashboard confirm can show it.POST /api/v3/admin/products/:id/mediagainssource_media_id(and the variant-nested twin) — the reuse path. The source must resolve throughcurrent_store.media, same IDOR rule as every other lookup.- Scopes: rides the existing
read_products/write_productspair — media is product imagery, not a new sensitive resource. - Serializer: admin media serializer gains
attached?/owner summary and usage counts where cheap; the event serializer is unchanged.
Dashboard
- New Media page (nav: under Products) — grid of thumbnails with type badges, filters, search, upload dropzone (direct upload → top-level create), bulk delete with usage-aware confirm, detail side panel (preview, alt, file facts, usage list, "add to product…").
- Library picker sheet (
dashboard-core-level component): browse/search the library, multi-select, returns either media ids (product media reuse) or blob signed ids (generic attachment fields). Product media card gains "Add from library" beside upload; category/collection/store/seller image fields gain "Choose from library". - Rich text editor: Tiptap Image extension + toolbar button opening the
picker (upload tab included — uploads land in the library as unattached rows,
then embed). Inserted
srcis the non-croppingembedrendition URL.
Renditions
Product image variants are resize_to_fill — cropped to exact dimensions,
wrong for editorial images inside descriptions. Add one embed rendition
(resize_to_limit, WebP, same saver options) used by rich text embeds; the
grid reuses the existing small/thumbnail renditions.
Migration Path
- Migration: add
store_idtospree_media(nullable, indexed). Schema only — the data step is a rake task, per the repo's migration rules. - Upgrade task
spree:upgrade:backfill_media_store_ids, in the 5.6→6.0 manifest aftermigrate_master_images_to_product_media(that step moves media between viewables, and a row re-homed afterwards would keep the wrong store). Resumable bywhere(store_id: nil); rows whose viewable is gone fall to the default store rather than staying unreachable. - Model changes + top-level API +
source_media_idon both product write paths. - Dashboard library page + picker; wire picker into product media card and generic attachment fields.
- Tiptap Image + sanitizer widening +
embedrendition, in one change. - 6.1 cleanup:
null: falseonspree_media.store_id.
Constraints on Current Work
- Never strip or "align" the
active_storage_attachments→ blobs foreign key with the no-FK convention — blob-sharing deletion safety depends on it. Spree::Media::Usagemust stay store-scoped on every one of its three sources (attachments, placements, rich text) — a blob can be shared, but a file's reported uses are its own store's rows.- Which editors can embed a file is a dashboard decision:
MediaRichTextEditoris opt-in per call site and only product, category and collection descriptions use it. The usage search covers every model declaring rich text rather than restating that list on the server. - A controller action outside
index/showneeds its CanCanCan action mapped as well as its key scope declared:read_actionssettles the API-key gate, but the:readalias covers only those two, so a custom read action refuses JWT staff until it is mapped. Test it with a JWT alone — the shared spec headers also carry a full-scope secret key, which authorizes on its own and hides the refusal. - New media queries must scope through
current_store.mediaoncestore_idlands; until then, keep scoping through the product as today. - Do not add an
imgtag toRichTextSanitizer.allowed_tagsahead of the editor gaining the image node — the allowlist and the editor move together. - Do not build attachment-style join tables between
Spree::Mediaand new owners; a new context that needs a file gets its own row sharing the blob. attachment.purge/blob.purgemust never be called directly on media paths — alwayspurge_later, so the foreign-key discard path can do its job.
Open Questions
None — resolved 2026-08-24 (see Key Decisions).
References
docs/plans/5.4-6.0-product-media-system.md— the shipped media data modeldocs/plans/6.0-rich-text-descriptions.md— sanitizer doctrine this plan extendsspree/core/app/models/spree/rich_text_sanitizer.rb— allowlist + widening notespree/core/app/models/spree/media.rb,spree/core/app/models/spree/variant_media.rb