How to Create Private Content/Sections in Magento 2?

Magento 2 has improved response time by implementing sections and storing customer data in the browser’s local storage as key-value pairs. As you can see, Magento 2 private content refers to flexible but non-shareable data with a short lifespan. It includes various customer data, such as payment information, selected product options, private deals, and checkout information, among other types of data.

CustomerData

Handles private content on the client side (e.g., a web browser) because it is specific to individual users. A piece of customer information (private data) forms a section, each represented by the key used for accessing and managing the data itself.

Magento uses AJAX requests to `/customer/section/load/` to load sections. Next, it caches loaded data in the local storage of a browser using the following key: `mage-cache-storage’. The system monitors section changes and loads updated data automatically.

This approach allows you to reload a part of a web page without reloading its entire content and breaking the whole Magento 2-page cache. However, there is a better way to treat private content. The customer-data JS library provides the ability to store private data in local storage most efficiently. Besides, you can create custom rules to invalidate private data and synchronize everything with the backend.

Sections and CustomerData in Magento 2?

In Magento 2, local storage plays a significant role, and developers added a new entity called CustomerData to ensure the smooth functioning of attributes.

Sections are merged parts of customer data, facilitating the maintenance of up-to-date data through synchronization with the web server. Each section is a key in Magento-cache-storage, with Magento-cache-storage serving as the key in localStorage.

Additional Information on Sections

The entire page content is cached, so sections help us dynamically manage the page components when caching is enabled. All section data is fetched in a single Ajax call, greatly reducing the number of Ajax requests.

Magento assumes that section data changes when a customer sends a state modification request (POST, PUT, DELETE). To minimize the load on the server, developers should specify which action (or request) updates which customer data section in the etc/frontend/sections.xml file.

To add private content, you must first define a section source. 

Read Also: Secure a Magento Store from Card Payment Attacks

Step-by-Step Guide to Private Content in Magento 2

Here are the steps to Create private content in Magento 2: 

Step 1

Create a “registration.php”

app/code/Dckap/Quote/registration.php

<?php
/**
* @package    DCKAP_Quote
* @copyright  Copyright (c) 2023 DCKAP Inc (http://www.dckap.com)
* @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
*/
\Magento\Framework\Component\ComponentRegistrar::register(
   \Magento\Framework\Component\ComponentRegistrar::MODULE,
   'Dckap_Quote',
   __DIR__
);

Step 2

Create a “Module.xml” file and the file path app/code/Dckap/Quote/etc/module.xml

<?xml version="1.0"?>
<!-- /**
* @package    DCKAP_Quote
* @copyright  Copyright (c) 2023 DCKAP Inc (http://www.dckap.com)
* @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
*/ -->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
   <module name="Dckap_Quote" setup_version="1.0.0">
   </module>
</config>

Step 3

Now, create one more file “di.xml” and a file path that has

app/code/Dckap/Quote/etc/frontend/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
   <type name="Magento\Customer\CustomerData\SectionPoolInterface">
       <arguments>
           <argument name="sectionSourceMap" xsi:type="array">
               <item name="custom_section" xsi:type="string">Dckap\Quote\CustomerData\CustomSection</item>
           </argument>
       </arguments>
   </type>
</config>

Step 4

Create the “CustomSection.php” file and file path has and the file path: 

app/code/Dckap/Quote/CustomerData/CustomSection.php

<?php
namespace Dckap\Quote\CustomerData;
use Magento\Customer\CustomerData\SectionSourceInterface;


class CustomSection implements SectionSourceInterface
{
   protected $checkoutSession;


   public function __construct(
       \Magento\Checkout\Model\Session $checkoutSession,   
   ) {
       $this->checkoutSession = $checkoutSession;
   }
   public function getSectionData()
   {
       $val = $this->checkoutSession->getMyValue();
       return [
           'customdata' => "Quote",
           'value' => $val,
       ];
   }
}

Step 5

Next, we will create catalog_product_view.xml in 

app/code/Dckap/Quote/view/frontend/layout

<?xml version="1.0"?>
<!-- /**
* @package    DCKAP_Quote
* @copyright  Copyright (c) 2023 DCKAP Inc (http://www.dckap.com)
* @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
*/ -->
<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
   <body>
       <referenceContainer name="page.messages">
           <block class="Dckap\Quote\Block\SessionData" name="custom.message" template="Dckap_Quote::quotemessages.phtml" after="-"/>
       </referenceContainer>
   </body>
</page>

Step 6

The last step is to create quotemessages.phtml got show the data

app/code/Dckap/Quote/view/frontend/templates/quotemessages.phtml

<?php
/**
* @package    DCKAP_Quote
* @copyright  Copyright (c) 2023 DCKAP Inc (http://www.dckap.com)
* @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
*/




?>
<script>
   require(['jquery', 'jquery/ui'], function($) {
       $( document ).ready(function() {
           var section = localStorage.getItem('mage-cache-storage');
           section = section ? JSON.parse(section).custom_section : null;
           var valueCount = section.value ? Object.keys(section.value).length : 0;
          
           if (valueCount > 0) {
               <?php $escapedUrl = $escaper->escapeHtmlAttr($block->getControllerUrl()); ?>
               section.controllerUrl = '<?= $escapedUrl ?>';
                   var message = '<div class="quote-massega"><h4>' + valueCount + ' items on your quote <a href="' + section.controllerUrl + '">Review quote</a></h4></div>';
                   $('.page.messages').append(message);
           }
       });
      
   });
</script>

Output

In Magento 2, you can use Private Content or Sections to enhance the performance and security of your website. Here’s how you can utilize them along with their advantages and disadvantages:

1. Private Content

Private content refers to data specific to a user session and is not cached. This content is personalized for each user and includes items like shopping cart contents, customer information, and session-specific data.

Advantages:

  • Use Experience: Private content allows you to personalize user experiences by displaying relevant information tailored to each user’s session.
  • Dynamic Updates: Since private content is not cached, it can update dynamically without affecting other users’ experiences. It is useful for real-time updates such as changes to the shopping cart.
  • Enhanced Security: Private content ensures that sensitive user data, such as account details or shopping cart contents, is not cached or shared with other users, enhancing the security of your website.

Disadvantages:

  • Performance Overhead: Since private content is not cached, it can lead to increased server load and slower page load times, especially on websites with high traffic or complex personalization requirements.
  • Resource Intensive: Managing and serving private content requires additional server resources and database queries, impacting overall website performance and scalability.
  • Cache Invalidation: Private content complicates cache management since it cannot be cached. Ensure that caching mechanisms are appropriately configured to avoid caching private content inadvertently.

2. Private Sections

Private sections are portions of a web page including user-specific data and are managed separately from the rest of the page content. These sections can be dynamically updated without refreshing the entire page, providing a smoother and more responsive user experience.

Advantages

  • Improved User Experience: Private sections enable dynamic content updates without reloading the entire page, resulting in a smoother and more responsive user experience.
  • Reduced Server Load: By updating only specific sections of the page, private sections help reduce server load and bandwidth consumption, leading to faster page load times and improved performance.
  • Private sections allow you to scale your website more efficiently by minimizing the need for server resources and optimizing the delivery of user-specific content.

Disadvantages

  • Implementing private sections requires careful planning and development to ensure seamless integration with existing website functionalities and compatibility with caching mechanisms.
  • Private sections might not be supported by all browsers or devices, potentially leading to inconsistencies in user experiences across different platforms.
  • Development Overhead: Developing and maintaining private sections can be resource-intensive, requiring ongoing updates and optimizations to ensure compatibility and performance.

Also Read: Latest in Magento 2 Migration

Usage for the Private Content 

In Magento 2, Private Content or Sections display dynamic and user-specific data without affecting the overall page caching mechanism. This ensures that sensitive information such as shopping cart contents or customer details is personalized for each user session and not cached or shared with other users. Here’s how you can use Private Content or Sections in Magento 2:

Private Content

First, define the content that should be considered private and not cached. This typically includes user-specific data such as shopping cart contents, customer information, or session-specific messages.

Identify Sections

Identify the sections of your Magento 2 website where private content will be displayed. It could include areas such as the mini cart, checkout page, or customer account dashboard.

Implement Private Content

Magento 2 provides mechanisms for managing private content through JavaScript and AJAX requests. Here’s a basic outline of how to implement private content:

JavaScript Initialization: Use JavaScript to initialize private content sections on the front end of your Magento 2 website. Utilize Magento’s JavaScript libraries and custom APIs to manage private content loading and updating.

AJAX Requests: Utilize AJAX requests to fetch user-specific data from the server without refreshing the entire page. Trigger these requests based on user interactions or page events, such as adding items to the shopping cart or logging in.

Update Content Dynamically: After the server processes the AJAX request and retrieves data, dynamically update the private content sections on the front end, ensuring that user-specific information is displayed in real-time without the need for page reloads.

Cache Management: Configure Magento 2’s caching mechanisms to exclude private content sections from being cached. It ensures that user-specific data is not stored in the cache and remains dynamic for each user session.

Test Implementation: Thoroughly test the implementation to ensure that private content sections function correctly across different user scenarios and devices. Monitor performance metrics and optimize the implementation for speed and efficiency.

Conclusion

In Magento 2, leveraging Private Content or Sections can significantly enhance performance, security, and user experience of your website. By effectively implementing these features, you can personalize user interactions, minimize server load, and ensure the security of sensitive data.

You’ve learned how to utilize Private Content or Sections in Magento 2 to deliver dynamic, user-specific content while maintaining optimal performance and security standards. Your dedication to mastering Magento’s functionalities and implementing best practices will undoubtedly benefit your projects and clients.

About The Author

We take the guesswork out of ecommerce.
Schedule a consultation call today