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 - This type of content has long life span and can be available to multiple users at multiple places like category, product and cms pages. (Learn more about Magento 2 public content - https://developer.adobe.com/commerce/php/development/cache/page/public-content/)
Private content - This type of content has shorter life span and must not be sharable. Different users must receive individual content like customer cart details, payment details, etc. (Learn more about Magento 2 public content - https://developer.adobe.com/commerce/php/development/cache/page/private-content/)
**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 :)
Comments