Magento – Magento 2 : Unable to save data in Sessions with Cache enabled

customer-sessionfull-page-cachemagento-2.1sessions

I am trying to save some temporary data into the customer session object ( \Magento\Customer\Model\Session ), which I need to retain until a quote is generated. I have tried two methods to save data in session, $session->setData('Att',$value); and $session->setAttValue($value); on a temporary bases. These getter and setter methods reside in a class which I created to handle session related operations and are called from observers.

The problem is : Once I store the value in the session and try to get it back, I am getting NULL value when Full Page Cache is enabled; however if the FPC is not enabled, the accessor method returns expected value from session.

PS: I found an issue which might be similar to what I am facing here, but in the issue, the solution suggested was hole-punching the block, but in my situation, I am not using any block, I am using observers only and I could not find a way to hole-punch function for observer. Any help appreciated.

Thanks in Advance,

Best Answer

Use Session factory instead.

public function __construct(
       \Magento\Customer\Model\SessionFactory $sessionFactory)
        {
           $this->sessionFactory = $sessionFactory;
        }

Now you can use customer session with FPC enabled.

$customerSession = $this->sessionFactory->create();

if ($customerSession->isLoggedIn()) {
    // customer is logged in;
}
Related Topic