I have this working code for setting the cookie for a visitor:
$metadata = $cookieMetadataFactory
->createPublicCookieMetadata()
->setDuration(86400 * 90)
->setPath('/');
$cookieManager->setPublicCookie(
'cookie_name',
'cookie_value',
$metadata
);
But, since I enabled full page cache for the website, this code stopped working. Disabling cache is not a option, using javascript is not a option...
I noticed that other extensions that use cookies (like Amasty Affiliate), also don't work. Is this default Magento behaviour?
CodePudding user response:
It seems like the Full Page Cache (FPC) is interfering together with your cookie putting capability. When FPC is enabled, the page content material is cached, so your server-aspect code for setting the cookie isn't always being carried out on every page load. Here are some steps you could observe to solve this difficulty:
Utilize AJAX: Use an AJAX call to a server-aspect action to set the cookie, thereby isolating the cookie putting from page rendering.
// AJAX example using jQuery
$.ajax({
url: 'your/server/side/action',
method: 'POST',
success: function(response) {
// success handling
},
error: function(error) {
// error handling
}
});
On the server-facet, you will take care of cookie putting as regular.
HTTP Cookies:
Set cookies via HTTP headers through web server configuration or a reverse proxy. Custom Cache Contexts:
Establish a custom cache context or a cacheable block in Magento to manipulate cookies at the same time as maintaining FPC enabled. Extension Configurations:
Check configurations of any third-party extensions installed, some might have solutions for managing cookies with FPC.
CodePudding user response:
In Magento 2, when a full-page cache is enabled, you may encounter issues setting cookies. Full-page caching saves complete HTML pages and serves them to users, making it challenging to set dynamic cookies for personalized user experiences. To work around this, you can use client-side JavaScript to set cookies after the page loads. This ensures that cookies are still effective while benefiting from full-page caching.