How do you Set and Get Data from The Cookie and Customer Session in Magento 2.4?

Cookies are small files on a user’s computer that are usually used to identify a user. These are used to track users and provide a personalized experience. You can set, update, and retrieve cookies. In Magento 2, you can easily set and get data from the cookies and customer sessions in Magento 2.4. 

In Magento 2, cookies are crucial in managing user sessions, personalization, and tracking user behavior. Here’s a description of the various cookies used in Magento 2:

Frontend Cookies

The frontend cookie is used to maintain the user session on the front end of the website. It stores the session ID, allowing Magento to recognize a user as they navigate through the site. The cookie is typically set to expire after a certain period of inactivity.

Adminhtml Cookies

The adminhtml cookie is used to maintain the session of administrators logged into the Magento admin panel. It stores the session ID and allows administrators to perform various actions and manage the website’s backend.

Customer Cookies

The customer cookie stores the customer group ID of the logged-in customer. It helps Magento deliver personalized content and pricing based on the customer group to which the user belongs. We can store customer data and all information in the cookies. Below is how to set and get the data on the page below the module for cookies.

We can set the customer data while logging in and remove the customer data when logging out, and this is the module for that.

Steps to Create Cookies in Magento 2

Step 1: Create a “registration.php”:

app/code/Dckap/Cookiesandsession/registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
   \Magento\Framework\Component\ComponentRegistrar::MODULE,
   'Dckap_Cookiesandsession',
   __DIR__
);

Step 2: Create a “Module.xml” file and the file path: 

app/code/Dckap/Cookiesandsession/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
   <module name="Dckap_Cookiesandsession" setup_version="2.0.1">
   </module>
</config>

Step 3: Now, create one more file “event.xml” and a file path that has: 

app/code/Dckap/Cookiesandsession/etc/frontend/event.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
   <event name="customer_login">
       <observer name="Cookiesandsession_customer_login_observer" instance="Dckap\Cookiesandsession\Observer\CustomerLoginObserver" />
   </event>
   <event name="customer_logout">
       <observer name="logouts_observers" instance="Dckap\Cookiesandsession\Observer\CustomerLogoutObserver" />
   </event>
</config>

Step 4: Create the “CustomerLoginObserver.php” file and file path: 

app/code/Dckap/Cookiesandsession/Observer/CustomerLoginObserver.php

<?php
namespace Dckap\Cookiesandsession\Observer;


use Magento\Framework\Event\ObserverInterface;
use Magento\Customer\Model\Session;


class CustomerLoginObserver implements ObserverInterface
{
   protected $customerSession;


   public function __construct(
       Session $customerSession
   ) {
       $this->customerSession = $customerSession;
   }


   public function execute(\Magento\Framework\Event\Observer $observer)
   {
       if ($this->customerSession->isLoggedIn()) {
           $customer = $this->customerSession->getCustomer();
           $customerId = $this->customerSession->getCustomerId();
           $customerEmail = $this->customerSession->getCustomer()->getEmail();
           $customerFirstname = $this->customerSession->getCustomer()->getFirstname();
          
           // Additional customer information
           $customerLastname = $this->customerSession->getCustomer()->getLastname();
           $customerGroup = $this->customerSession->getCustomer()->getGroupId();


           $customerData = [
               'customer_id' => $customerId,
               'email' => $customerEmail,
               'customer_firstname' => $customerFirstname,
               'customer_lastname' => $customerLastname,
               'customer_group' => $customerGroup,
           ];
           $this->clearCustomerDataCookies();
           $this->setCustomerDataInCookies($customerData);
       }
   }


   protected function setCustomerDataInCookies($customerData)
   {
       foreach ($customerData as $key => $value) {
           setcookie($key, $value, time() + 3600, '/');
       }
   }


   protected function clearCustomerDataCookies()
   {
       $cookieNames = ['customer_id', 'email', 'customer_firstname', 'customer_lastname', 'customer_group'];


       foreach ($cookieNames as $cookieName) {
           setcookie($cookieName, '', time() - 3600, '/');
       }
   }
}

Step 5: The last step is to create “CustomerLogoutObserver.phtml”: 

app/code/Dckap/Cookiesandsession/Observer/CustomerLogoutObserver.php

<?php


namespace Dckap\Cookiesandsession\Observer;


use Magento\Framework\Event\ObserverInterface;


class CustomerLogoutObserver implements ObserverInterface
{
   public function execute(\Magento\Framework\Event\Observer $observer)
   {
       $cookieNames = ['customer_id', 'email', 'customer_firstname', 'customer_lastname', 'customer_group'];


       foreach ($cookieNames as $cookieName) {
           setcookie($cookieName, '', time() - 3600, '/');
       }
      
   }


}

Step 6: Now create a block or controller to get the value of cookies: 

   public function getCustomerDataFromCookiesUsertype()
   {


       $FromCookiescustomerId = $this->cookieManager->getCookie('customer_id');
       $FromCookiesemail = $this->cookieManager->getCookie('email');
       $FromCookiesfirstname = $this->cookieManager->getCookie('customer_firstname');
       $FromCookieslastname = $this->cookieManager->getCookie('customer_lastname');
 $FromCookiesgroup = $this->cookieManager->getCookie('customer_group');


       return $FromCookiesusertype;
   }

Output For cookies:

Below is the image for the customer login.


Below is the image for customer logout:

Steps to Create a Customer Session in Magento 2 

Step 1: Create a “registration.php”, “Module.xml” and “event.xml” file and you can see that file above steps

Step 2: Create the “CustomerLoginObserver.php” file and file path has and the file path: 

app/code/Dckap/Cookiesandsession/Observer/CustomerLoginObserver.php

<?php
namespace Dckap\Cookiesandsession\Observer;


use Magento\Framework\Event\ObserverInterface;
use Magento\Customer\Model\Session;


class CustomerLoginObserver implements ObserverInterface
{
   protected $customerSession;


   public function __construct(
       Session $customerSession
   ) {
       $this->customerSession = $customerSession;
   }


   public function execute(\Magento\Framework\Event\Observer $observer)
   {
       // Set customer data in session when customer logs in
       $customer = $observer->getEvent()->getCustomer();
       if ($customer) {
           $this->customerSession->setCustomerId($customer->getId());
           $this->customerSession->setCustomerEmail($customer->getEmail());
           $this->customerSession->setCustomerFirstname($customer->getFirstname());
           $this->customerSession->setCustomerLastname($customer->getLastname());
           $this->customerSession->setCustomerGroupId($customer->getGroupId());
       }         
    }


   // you can set and get any value by this
   public function setValue()
   {
       return $this->customerSession->setMyValue('YourValue'); //set value in customer session
   }


   public function getValue()
   {
       return $this->customerSession->getMyValue(); //Get value from customer session
   }
}

Step 3: The last step is to create CustomerLogoutObserver.phtml 

app/code/Dckap/Cookiesandsession/Observer/CustomerLogoutObserver.php

<?php


namespace Dckap\Cookiesandsession\Observer;




use Magento\Framework\Event\ObserverInterface;
use Magento\Customer\Model\Session;


class CustomerLogoutObserver implements ObserverInterface
{
   protected $customerSession;


   public function __construct(
       Session $customerSession
   ) {
       $this->customerSession = $customerSession;
   }
   public function execute(\Magento\Framework\Event\Observer $observer)
   {
       // Clear customer data from session
       $this->customerSession->unsCustomerId();
       $this->customerSession->unsCustomerEmail();
       $this->customerSession->unsCustomerFirstname();
       $this->customerSession->unsCustomerLastname();
       $this->customerSession->unsCustomerGroupId();
       $this->customerSession->unsMyValue();
   }
}

Step 4

Now we can create a block or controller to get the value of customer sessions like this

public function getCustomerData()
{
   // Get customer data from session
   $customerData = [
       'customer_id' => $this->customerSession->getCustomerId(),
       'email' => $this->customerSession->getCustomerEmail(),
       'firstname' => $this->customerSession->getCustomerFirstname(),
       'lastname' => $this->customerSession->getCustomerLastname(),
       'group_id' => $this->customerSession->getCustomerGroupId(),
   ];


   return $customerData;
}

Cookies and Customer Sessions Usage and Benefits 

No Cache

This cookie indicates whether caching is disabled or not for the current session. It helps Magento determine whether to serve cached content to the user or generate dynamic content.

Shopping Cart

This cookie is used to remember the user’s shopping cart between sessions. It allows users to add items to their cart and continue shopping even after they close the browser window.

Cart

This cookie stores the user’s cart ID and items. It helps Magento maintain the user’s shopping cart state across different pages and sessions.

Wishlist

This cookie stores the user’s wishlist items. It allows users to save products for later viewing or purchase.

Cookie Lifetime

This is all about how long Cookie files stay on the user’s browser. One hour is the default setting which is equivalent to 3600 seconds.

Cookie Path

You have to enter the cookie path here to make cookies available for some specific folders. You have to enter “/” if you want to make it available everywhere on your site.

Cookie Domain

This helps to enable cookies for specific subdomain. Enter “.domain.com” if you want to enable cookies for all the subdomains. (Verify that you should enter “.” before your domain name).

  • Customer sessions are used to manage user authentication. When a user logs in to the Magento 2 website, a session is initiated to keep track of their login status throughout their browsing session. This ensures that users can access their account information and perform actions such as viewing order history and managing their profile.
  • Customer sessions enable personalized experiences by storing user preferences and browsing history. This allows Magento 2 websites to tailor product recommendations, promotional offers, and content based on the user’s interests and behavior.
  • Customer sessions are essential for managing the shopping cart. When a user adds items to their cart, the session stores this information, allowing users to continue shopping and checkout seamlessly. It also enables features like saving the cart for future visits and displaying personalized product recommendations based on cart contents.
  • Customer sessions facilitate order tracking by associating orders with the user’s session. This allows users to view the status of their orders, track shipments, and access order details from their account dashboard.
  • By leveraging customer sessions, Magento 2 websites can deliver a smoother and more engaging user experience. Users can navigate the site seamlessly, access personalized content, and enjoy convenient features like saved preferences and order history.
  • Customer sessions enable targeted marketing efforts by providing insights into user behavior and preferences. Retailers can use session data to segment users, send personalized email campaigns, and retarget users with relevant advertisements.

Customer sessions can be used to maintain consistency across devices. If a user logs in on one device, their session information can be synchronized across other devices, ensuring a seamless experience regardless of the device used for accessing the Magento 2 website.

Advantages of Cookies and Customer sessions 

  • Cookies can store user preferences and shopping cart information, enabling a personalized shopping experience.
  • Cookies assist Magento 2 in managing user sessions, tracking logged-in users, and monitoring their activities on the website.
  • Cookies enable the tracking of user behavior, which is valuable for analyzing site performance, user engagement, and marketing effectiveness.
  • Cookies can be used to enable features such as remembering login credentials, saving shopping cart items, and customizing content based on user interests.
  • Customer sessions facilitate a personalized browsing experience by storing user preferences, past purchases, and browsing history.
  • Users can add items to their cart and return later to complete the purchase without losing their selections, leading to higher customer satisfaction and conversion rates.
  • Enabling secure access to account information, order history, and other personalized features enhances security by ensuring that only authorized users can access sensitive data.

Disadvantages of Cookies and Customer sessions

  • Cookies store user data, which can raise privacy concerns if not handled properly. Users may be wary of sharing personal information and browsing habits.
  • Cookies can be vulnerable to security threats such as cross-site scripting (XSS) and session hijacking if not implemented securely.
  • Cookie usage is subject to various regulations such as GDPR in Europe and CCPA in California. Failure to comply with these regulations can result in legal consequences.
  • Some users may disable cookies in their browsers, limiting the functionality of certain features on the Magento 2 website.
  • Storing user data in customer sessions raises privacy concerns, especially in light of regulations such as GDPR and CCPA. Users may be wary of sharing personal information and browsing history, leading to distrust and reluctance to engage with the platform.
  • Managing customer sessions requires server resources and adds complexity to the backend infrastructure. As the number of concurrent users increases, maintaining session data and ensuring scalability can become challenging, potentially leading to performance issues and downtime.

Cookies and Customer Sessions in Magento 2

Cookies and customer sessions play integral roles in shaping the user experience and functionality of ecommerce platforms like Magento 2. While cookies enable personalized interactions, track user behavior, and enhance website functionality, customer sessions facilitate user authentication, shopping cart management, and personalized content delivery. 

They also present some challenges such as privacy concerns, session management overhead, compatibility issues, and security risks. By carefully considering the advantages and disadvantages of cookies and customer sessions, businesses can implement strategies to optimize user engagement, ensure compliance with regulations, and mitigate risks. 

To overcome ecommerce challenges, get in touch with Klizer. Our developers are skilled and have more than a decade of expertise in Magento 2.

About The Author

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