top of page
Writer's pictureVishesh Dwivedi

Sections (sections.xml) in Magento 2

Magento 2 uses customer sections to store customer private data to local storage.



Basically, there are two types of content on a website -

**Public content can be cached but private content must not be cached.


Magento uses caching techniques to make storefront faster but problem arises when storefront page consists both public and private content. When whole page is cached and we need to update some dynamic components, the first thing comes to our mind is ajax request.


Magento 2 uses customer-data.js for such task. It stores and updates customer private data to local storage. Sections data is stored in mage-cache-storage key.


It sends an ajax request to customer/section/load action on the server, collects all the required customer private data and update the invalidated sections on local storage. Invalidated section names are stored in mage-cache-storage-section-invalidation key.


To update a customer section, we need to define our action name and the customer section name in sections.xml configuration file.

etc/sections.xml


<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Customer:etc/sections.xsd">
    <action name="checkout/cart/index">
        <section name="cart"/>
    </action>
</config>

Whenever a request is made to checkout/cart/index action, cart section will get updated. customer-data.js is responsible for this task.

We can also create our custom section using di.xml . We just need to inject our section name and class to sectionSourceMap array in \Magento\Customer\CustomerData\SectionPoolInterface::class


To create custom customer section, you can go through the blog - https://developer.adobe.com/commerce/php/development/cache/page/private-content/


Thank you. Happy caching :)


2,113 views0 comments

Recent Posts

See All

Comments


bottom of page