Private content

Since private content is specific to individual users, it’s reasonable to handle it on the client (i.e., web browser).

Use our customer-data JS library to store private data in local storage, invalidate private data using customizable rules, and synchronize data with the backend.

This example shows a customer’s name on a cacheable page.

Create a section source

The section source class is responsible for retrieving data for the section. As a best practice, we recommend you put your code under the Vendor/ModuleName/CustomerData namespace. Your classes must implement the Magento\Customer\CustomerData\SectionSourceInterface interface.

The public method getSectionData must return an array with data for private block.

Create a block and template

To render private content, create a block and a template to display user-agnostic data; this data is replaced with user-specific data by the UI component
.

Do not use the $_isScopePrivate property in your blocks. This property is obsolete and won’t work properly.

Replace private data in blocks with placeholders (using Knockout syntax). The init scope on the root element is data-bind="scope: 'compareProducts'", where you define the scope name (compareProducts in this example) in your layout
.

Invalidate private content

Specify actions that trigger cache invalidation for private content blocks in a sections.xml configuration file in the Vendor/ModuleName/etc/frontend directory. Magento invalidates the cache on a POST or PUT request.

Use only HTTP POST or PUT methods to change state (e.g., adding to a shopping cart, adding to a wishlist, etc.) and don’t expect to see caching on these methods. Using GET or HEAD methods might trigger caching and prevent updates to private content. For more information about caching, see RFC-2616 section 13

Version private content

Private content, which is stored in the browser local storage, uses the private_content_version cookie to store the version.

Versioning works as follows:

The user performs some action, such as adding to a cart, that results in an POST or PUT request to the Magento application.

The server generates the private_content_version cookie for this user and returns the response to the browser.

JavaScript
interprets the presence of the private_content_version cookie to mean that private content is present on the page, so it sends an AJAX request to the Magento server to get the current private content.

The server’s reply is cached in the browser’s local storage.

Subsequent requests with the same data version are retrieved from local storage.

Any future HTTP POST or PUT request changes the value of private_content_version and results in the updated content being cached by the browser.