e-Zest members share technology ideas to foster digital transformation.

Custom Sessions in Magento 2

Written by Pooja Pardeshi | Nov 15, 2018 11:49:00 AM
Sessions play an important role in enhancing the user experience and they also help gather vital stats about the user visits. In simplistic language, the session is nothing but the storage of interaction related information at server side, persist for throughout user interaction. As Magento is an e-commerce website platform, it provides multiple sessions to store customer data throughout its interaction with website or web application.

Magento1 uses core session (core/session), whereas Magento 2 is no longer using core session like earlier.

Magento2 provides five types of sessions:

  • Magento\Backend\Model\Session– This session is used for Magento backend.
  • Magento\Catalog\Model\Session– Catalog session is used for the frontend for product filters.
  • Magento\Checkout\Model\Session– Checkout session is used to store checkout related information.
  • Magento\Customer\Model\Session– Customer session is used for customer, frontend login and all other activities.
  • Magento\Newsletter\Model\Session– For newsletter data.
Though Magento is giving a different kind of sessions to store respective data, as a developer during customization we need some custom sessions to store specific functionality or module related data. Sometimes user sets session data using default sessions provided by Magento and wants it on another request and then they came to know that value is reset or not persisting. This usually happens because one of these three primarily when the browser loses session cookies or there might be some browser plugin issue or Magento extension is misbehaving.

In such situations, custom session functionality comes handy. In a custom session, data will not be lost until developer forcefully reset it or session reaches timeout condition. So here are the following steps to create a custom session:

Directory Structure:


- app/code/MyModule/MySession/registration.php


- app/code/MyModule/MySession/etc/module.xml


- app/code/MyModule/MySession/etc/di.xml


- app/code/MyModule/MySession/Model/Session.php


- app/code/MyModule/MySession/Model/Session/Storage.php


To access your custom session in any block,model you can use it in following way:


To access custom session data in checkout related JS, you can mention it in CheckoutConfigProvider and use it in JS file.

You can use custom session all over website’s scope and maintain your data for further action.

Hope this will help you!