A share image for your page
Give the pages of your module an og:image: an image source for your page kind, your own card, a new card kind and the Share image field in your editor.
When a merchant shares a page on Facebook, LinkedIn or WhatsApp, the platform fetches the page's og:image. Light writes the og: tags of every storefront page and picks the image from the pool share_image_sources: the first source that has an image for the page wins. A page with no image of its own gets a card that Light draws on the fly, with the shop's logo and the page's title, through the pool share_card_renderers. This recipe adds a share image to the story page of an imaginary module, then draws that story's own card. It follows Acme_ShareExample in docs/magerex-light/examples, which is written by hand and has a README.
When to use it
- Your module has storefront pages of its own that a merchant shares (a story, a landing page, a location page), and Light's generic card is not the image you want on them.
- Your module stores an image per entity and the merchant should choose it in your editor, in a Share image field like the one in the product, category and page editors.
- A shop wants every card in its own layout: your module replaces Light's renderer for the kind
pageorproduct. - Light already covers the product page, category pages, CMS pages, the home page and search.
Mrx_CatalogandMrx_Contentadd the merchant's upload to them, so none of this needs code of yours. - Keep the field to one image: Light adds no title, description or tag of your own. The editor stays as small as the other three (Built for Light, rule 2).
How og:image is chosen
Light asks each source in order of sort_order until one answers. Light ships three sources, and the merchant's uploads come from the modules that own the field:
| Sort order | Code | Answers |
|---|---|---|
| 10 | catalog_share_image, content_share_image | The merchant's upload for a product, a category, a CMS page or the home page (Mrx_Catalog, Mrx_Content, upload true). |
| 50 | page_image | The category's own image, the first image in a CMS page's content, and for a product its main photo on a product card. |
| 70 | store_default | The store view's Share Image: design/head/share_image, set in Content > Design > Configuration > HTML Head or in Settings > Branding. |
| 90 | title_card | A page card with the shop's logo and the page's title. |
The numbers leave gaps: your source at 40 sits between the uploads and the page's own image, one at 60 between the page's own image and the store view's Share Image. The page tells the pool what it is with a kind:
| Kind | Set by | ShareContext::$entity |
|---|---|---|
product | the template Mrx_Light::product/open-graph.phtml, which Light swaps into Magento's opengraph.general block | the product |
category | catalog_category_view | the category |
cms | cms_page_view | the CMS page |
home | cms_index_index, over the kind cms | the CMS page |
search | catalogsearch_result_index | none |
other | the default, in default.xml | none |
| your own | the layout argument kind of the block mrx.light.open_graph | none |
A source that has nothing for the page returns null and the next one is asked. A source that throws is logged (Light share image source "<code>" failed: ..., a warning) and the next one is asked too. Light checks every answer before it uses it: a URL must be http or https, or a path from the web root that Light makes absolute (anything else is logged and skipped), and a card needs a renderer for its kind that can draw on this PHP (otherwise it is skipped without a log line, since a PHP without GD is no error). Light writes og:image:width and og:image:height when the answer carries both: a card is always 1200 × 630.
A card's URL is signed, and the platform fetches it later:
Steps
Acme_ShareExample in full:
1. Name the page kind
The module's PHP names Light classes, so it carries the range guard and extra.mrx-light-api (Range guard). It loads after Mrx_Light:
if (class_exists(\Mrx\Light\Api\ExtensionApi::class) && \Mrx\Light\Api\ExtensionApi::satisfies('^0.18')) {The layout handle of your story page sets the argument kind on Light's block. Light then writes og:title, og:description and og:url from the page's own title, description and address, and asks the pool for your kind:
<referenceBlock name="mrx.light.open_graph">
<arguments>
<argument name="kind" xsi:type="string">acme_story</argument>
</arguments>
</referenceBlock>A kind is lower case letters, digits and _, starts with a letter and has at most 32 characters. Anything else counts as other. The file is a storefront layout file, so the compatibility gate leaves it alone, and on a shop without Light the block doesn't exist and Magento ignores the reference.
2. Write the sources
A source implements ImageSourceInterface: one method, and null for every page it knows nothing about. Light loads no entity for a kind of your own on the storefront, so a source finds its own. CurrentStory takes the story from the page's registry entry, and from share_entity when the editor's preview asks:
if ($context->kind !== Story::KIND) {
return null;
}
$story = $context->entity ?? $this->registry->registry(Story::REGISTRY_KEY);Two sources, because the editor's preview treats them differently. The first answers the merchant's upload, through ShareUploadInterface, which checks the stored path and builds the media URL:
$story = $this->currentStory->get($context);
return $story !== null ? $this->upload->toImage($story->shareImage, $context->storeId) : null;The second answers what the story shares without an upload: its hero image, else a card of your own kind:
return $story->heroUrl !== ''
? ShareImage::fromUrl($story->heroUrl)
: ShareImage::card(Story::KIND, $story->title);ShareImage::fromUrl() takes a finished image. ShareImage::card() asks Light for a card: your source passes the card kind, the text and, for a product, the photo, and Light checks all three, cuts the title to 160 characters and signs the URL. A source can neither build nor sign a card URL. A card's photo is a product photo, catalog/product/x/y/<file>; share any other image with fromUrl().
A source runs on every uncached storefront render of a page of its kind, and in the editor's preview, so keep it cheap: read what the context carries and load your own entity only for your own kind.
3. Register them
Both pools are global: the storefront reads them for the tags and the card, the admin for the preview. The items go in etc/di.xml, and the object is always a \Proxy, because the pool is built on every page and your class may need services a page doesn't. module names the module the item belongs to, so the item disappears when it is off or hidden by the compatibility gate:
<item name="acme_story_upload" xsi:type="array">
<item name="source" xsi:type="object">Acme\ShareExample\Model\SharePreview\StoryUploadSource\Proxy</item>
<item name="sort_order" xsi:type="number">10</item>
<item name="upload" xsi:type="boolean">true</item>
<item name="module" xsi:type="string">Acme_ShareExample</item>
</item>
<item name="acme_story_page" xsi:type="array">
<item name="source" xsi:type="object">Acme\ShareExample\Model\SharePreview\StorySource\Proxy</item>
<item name="sort_order" xsi:type="number">40</item>
<item name="module" xsi:type="string">Acme_ShareExample</item>
</item>upload true marks the merchant's own upload. The editors' preview asks the pool twice, with and without the uploaded sources, so it can show the upload and then what the page falls back to when the merchant removes it. A source that answers anything but an upload leaves upload off. Items are asked by sort_order (100 when missing, ties by code). To drop one of Light's sources for one shop, set its item to null in the pool, as Changing Light for one shop shows.
4. Draw your own card
A renderer implements CardRendererInterface, render() and version(). Light hands it a CardRequest: the card kind, the store view, the title (plain text, at most 160 characters), the absolute path of the photo and of the store view's header logo (each checked by Light, '' for none or refused) and the store view's frontend name, for a card without a logo. It returns a CardImage: the bytes of a JPEG or PNG of exactly 1200 × 630 pixels and at most 5 MB. Anything else gives a 404 and a warning in the log. The example draws with GD's built-in font so it needs no font file, but that font draws ASCII only: a title such as "Über uns" comes out garbled. A real card draws with imagettftext() and a font file of its own, as Light's cards do.
$card = imagescale($small, self::WIDTH, self::HEIGHT, IMG_BICUBIC);
if ($card === false) {
return null;
}
ob_start();
imagejpeg($card, null, 86);
$bytes = (string)ob_get_clean();
return $bytes !== '' ? new CardImage($bytes, CardImage::MIME_JPEG) : null;version() goes into every card URL. Return '' on a PHP that can't draw, and no page points at your cards. Change the string whenever the same request would draw differently: your layout, your fonts, a setting you read. Light adds the renderer's class, the store view's logo file and its time of change and the store view's name to the version itself.
public function version(): string
{
return function_exists('imagecreatetruecolor') && function_exists('imagejpeg') ? self::VERSION : '';
}To change how Light's own cards look, take over a key. A module that loads after Mrx_Light sets page (a page with its title) or product (a product on its photo) in the pool in its etc/di.xml, and the item is the object itself (xsi:type="object", still a \Proxy), not an array as in step 3. Its class and version go into the card URLs, so every page's og:image changes and no cache keeps an old card. A <preference> on Light's GdPageCard is private_api and not supported. A renderer that calls a service sets its own timeout of at most 3 seconds and returns null on a failure; Light never retries.
5. Add a card kind
A new key in the pool share_card_renderers is a new kind. It draws from the same kind, title and photo as every card: a kind adds no parameters and can't widen the photo to another folder. A kind that needs more reads it itself, from what the title and photo identify:
<item name="acme_story" xsi:type="object">Acme\ShareExample\Model\SharePreview\PlainCardRenderer\Proxy</item>The key is the card kind a source passes to ShareImage::card(). It follows the kind pattern of step 1.
6. The Share image field in your editor
The field is the @api block Mrx\Light\Block\ShareImageField: a thumbnail with Replace and Remove, and a hidden input that posts the path under media. The page editor of Mrx_Content embeds it in its SEO card:
<?= /* @noEscape */ $block->getLayout()->createBlock(\Mrx\Light\Block\ShareImageField::class, '', ['data' => [
'html_id' => 'mrx-page-share-image',
'value' => $viewModel->getShareImage(),
]])->toHtml() ?>| Argument | Default | Meaning |
|---|---|---|
name | share_image | Name of the posted input |
value | '' | The stored path under media |
html_id | mrx-share-image | Id of the input: a letter first, then letters, digits, - and _ |
default_value | '' | What "Use default" puts back |
use_default | false | The field follows the default: the input and the buttons are off |
preview | '' | A CSS selector (#id, .class or [data-*]) of the [data-mrx-search-preview] to update. Empty takes the nearest one around the field. A selector that matches nothing updates no preview |
The block shows the buttons only to an admin with the ACL Magento_Cms::media_gallery, the upload route's resource. Without it the image shows and the help says to ask an admin with access to the media gallery. Uploads go through light/media/upload, which answers path next to url, and accept JPEG and PNG.
Your editor does three more things:
-
It passes the page kind and the entity to the preview in the same card, so the preview picks the image as the storefront does. Without
share_kindthe preview treats the page asotherand shows a card with no title:app/code/Mrx/Content/ViewModel/PageForm.php 'share_kind' => $homeStoreId !== null ? ShareContext::KIND_HOME : ShareContext::KIND_CMS, 'share_entity' => $page, -
It validates the posted path with
ShareUploadInterface::isValid()and keeps the value apart from the other fields: not posted keeps what is stored, an empty string clears it:app/code/Mrx/Content/Model/Page/PageService.php $shareImage = array_key_exists(self::SHARE_IMAGE, $input) ? $this->text($input[self::SHARE_IMAGE]) : null; if ($shareImage !== null && !$this->shareUpload->isValid($shareImage)) { $errors[self::SHARE_IMAGE] = (string)__('Upload the share image again.'); } -
It stores the path in a field of its own: a column or an attribute. Light reads no
share_imagecolumn or attribute, so your source reads yours (step 2).Mrx_Contentkeeps it incms_page.share_image,Mrx_Catalogin the store-view attributeshare_imageof a product and a category.
The field fires mrx:share-image-change on its root after an upload, a Remove, a discard and a switch to "Use default", and a native change on the hidden input for the save bar (Events). The JS module behind it, Mrx_Light/js/share-image-field, is tier 2: only the block's own template binds it, so build on the block, its arguments and the event.
With Mage-OS SEO
Mage-OS 4.0 ships its own SEO module, MageOS_Seo, which prints Open Graph and Twitter tags. When it does, Light must not print a second set. Two things make that work: Light's own block steps back, and the bridge Mrx_SeoMageos hands Mage-OS SEO Light's image.
| Tag | Written by |
|---|---|
og:title, og:description, og:type, og:url, the Twitter tags | Mage-OS SEO, by its own rules |
og:image, og:image:width, og:image:height | Light: the pool decides, the bridge puts the answer into Mage-OS SEO's tags |
The block mrx.light.open_graph stands aside on catalog_product_view, catalog_category_view and cms_page_view when Mage-OS SEO is enabled and mageos_seo_general/og_tags/enabled is on for the store view. On every other page (the search page, a module's page) Light's block still prints all the tags. The pool works as before: sources, sort order and the card are unchanged, and the answer carries the sizes, so the page prints og:image:width and og:image:height next to it.
The editors' preview follows what the shop prints. For each store view it uses Mage-OS SEO's title and description rules when that store view prints Mage-OS SEO's tags, and says "Mage-OS SEO chooses the share image for this store view." when the bridge is not installed, because then the image is Mage-OS SEO's own. A form that sends the unsaved texts to the preview sends them under share_fields (per store view id, then field code), as the product, category and page editors do.
Module kinds. A kind of your own, set with the layout argument kind on your own handle, works as before. Mage-OS SEO covers only the product, category and CMS page handles, so a kind of yours never meets it.
The handle pitfall. Don't write og: tags in catalog_product_view, catalog_category_view or cms_page_view yourself. With Mage-OS SEO on, the page then has two sets again, and a platform reads whichever it finds first.
The entry point. The bridge calls ImageSourcePool::tags() with a ShareContext and gets the og:image tags, or none. Your source needs nothing from the bridge: register it in the pool.
What stays core
A module hands Light a kind, a title and a photo, and Light does the rest. None of this is a hook:
| What | Rule |
|---|---|
| The card URL | Only Light builds and signs it (mrx_light/share/card), with the store view, the kind, the version, the photo and the title in the signature. A module can't sign one. |
| The parameters | The query holds exactly k, t, p, s, v and h. The card controller draws only the one URL Light writes for a signed card: another key order, an empty pair, another encoding, a path parameter or index.php/ gives a 404. |
| The formats | The kind follows the kind pattern and has a renderer, the title is valid UTF-8 of at most 160 characters, the photo is catalog/product/x/y/<file> as JPEG, PNG, GIF or WebP. |
| The photo and the logo | Light resolves the file inside pub/media, refuses a file over 20 MB or 20,000,000 pixels or one that isn't an image, and passes '' to the renderer instead. |
| The answer | At most 5 MB, a JPEG or PNG, exactly 1200 × 630 pixels, else a 404 and a warning. |
| The headers | Content-Type from the card, Cache-Control: public, max-age=31536000, immutable, X-Robots-Tag: noindex, X-Content-Type-Options: nosniff. Every refusal is a 404 with an empty body and no-store. |
| The editor's preview | The admin route light/share/card draws the same card for the preview, with no signature, behind the admin session, for a store view that exists, and with Cache-Control: private, max-age=300. |
What the admin sees
In your editor: a Share image field with a thumbnail and Replace and Remove, and the preview under the SEO fields showing the card a platform will show: the upload, else what your sources say, else the store view's Share Image, else the drawn card. The preview redraws a moment after the title changes.

The page editor with an upload: the preview shows it, and the field has Replace and Remove.
ACL
None new. The upload needs Magento_Cms::media_gallery; the store view's Share Image in Settings > Branding needs Magento_Config::config_design.
Check it
-
bin/magento mrx:light:doctor:api_constraintfor a missing range guard,private_apifor a preference on a Light class,wrong_areafor a pool item registered inetc/adminhtml/di.xml. -
Open a story page, read its
og:imagein the page source, then fetch it. The card answers 200 asimage/jpeg:curl -s -o /dev/null -w '%{http_code} %{content_type}\n' 'https://shop.test/mrx_light/share/card?k=acme_story&t=Hello&s=1&v=...&h=...' -
Change one character of
h, add a parameter or send an unknownk: each gives a 404. -
var/lognames a source that threw (Light share image source "<code>" failed) and a renderer whose answer failed a check. -
In the editor, type a title: the preview's card redraws.
Pitfalls
- The wrong area. Both pools are global. An item in
etc/adminhtml/di.xmlreplaces the whole pool in the admin and leaves the storefront without it: the doctor reportswrong_areaandtwo_areas. - No
\Proxy. The pool builds every item on every page. Register your classes as\Proxy. - A kind that doesn't match the pattern.
Acme-Storyis read asother, and the card shows no title. - A
version()that never changes. The version is part of every card URL, so a platform that fetched the old card keeps it. Return a new string whenever the drawing changes, and put every setting your drawing reads into it. - Visitor text on a card. A card puts its title under the shop's logo, on the shop's own domain. A search query, a customer's name or anything else a visitor can type must never reach
ShareImage::card(). Light draws no title forsearchandotherfor this reason. A module that sets a kind of its own gets its title on the card, so set a kind only for pages whose title the merchant wrote. - A photo that isn't a product photo. A card carries a product photo, nothing else.
wysiwyg/holds whatever any admin uploaded, so Light never draws it under the logo. Share any other image withfromUrl(). - A second
og:image. Don't write your own tag on a page of your kind: Light already does, and a page with two tags shares whichever the platform reads first. - A card that is not 1200 × 630. A renderer that draws another size gives a 404 and a warning, and the page's
og:imagepoints at it until the version changes. - A source that does real work. It runs for every uncached page of its kind and in the preview. Read what the context carries.
Caching
A card is drawn on every fetch and never written to disk. Its URL carries everything the card shows and changes with it, so Light answers the 200 with Cache-Control: public, max-age=31536000, immutable, and a cache may keep it for a year. The card controller draws only its one canonical URL, so a signed card has one cache object. Behind Magento's own Varnish configuration the year-long copy lives in Varnish only: its vcl_deliver replaces the header with no-store, no-cache, must-revalidate for the platform and the browser. That VCL also hashes the Host header and the X-Magento-Vary cookie, as for every page, so those give a new cache object per value. Without Varnish or a CDN every fetch draws again, which takes about 50 to 150 ms; platforms fetch a URL once and keep it. A key rotation changes every signed URL, and the pages carry the new ones after their cache clears.
Last updated on