2

I have an event triggered on all pages to set a cookie. However, the cookie is created only on uncached page and I don't understand why.

Here, my event :

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="controller_action_predispatch">
        <observer name="custom_cookie" instance="Namespace\Project\Observer\CreateCookie" />
    </event>
</config>

And I used this class to create my cookie:

\Magento\Framework\Stdlib\CookieManagerInterface::setPublicCookie

I already tried with layout_load_before or controller_front_send_response_before but the result is the same.

If I desactivate the cache on all pages, all is working (but, of course, it's not a solution).

Can I used another event (triggered on all pages)? Or is there another way?

1
  • Any update/resolution on this issue? Commented Oct 1, 2021 at 9:23

2 Answers 2

0

you can do using default.xml file just call phtml file from layout and

add below code in your phtml file

<script type="text/javascript">
    require([
        'jquery',
        'jquery/jquery.cookie'
    ], function ($) {
        $(document).ready(function () {
 
            var date = new Date();
            var minutes = 60;
            date.setTime(date.getTime() + (minutes * 60 * 1000));
            $.cookie('name', '', {path: '/', expires: -1}); // Expire Cookie
            $.cookie('name', 'name1', {expires: date}); // Set Cookie Expiry Time
            $.cookie('name', 'value'); // Set Cookie Value
        }
    });
</script>
1
  • I don't want to create a cookie in JS, I want to create a cookie server-sode by PHP. So I use this function : \Magento\Framework\Stdlib\CookieManagerInterface::setPublicCookie in an Observer
    – Kozame
    Commented Jul 26, 2021 at 7:19
0

I guess you want to read the cookie value inside a block. But with full page cache, this page (and block) is cached, therefore only the first pageview will actually try to read the cookie. So you need read up on FPC hole punching to ensure the block is never cached.

1
  • No, I want te create a new cookie, server-side. On an Observer, I use $this->cookieManager->setPublicCookie($cookieName, $cookieValue, $cookieMetadata); So it's not in a block
    – Kozame
    Commented Jul 26, 2021 at 7:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.