nystudio107 / craft-cookies

A simple plugin for setting and getting cookies from within Craft CMS templates.

Home Page:https://nystudio107.com/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

getCookie works with this plugin but not cannot get a cookie with native craft code - what is the difference?

terryupton opened this issue · comments

Hey Andrew.
This is more of a question and trying to get an understanding. So I have a cookie that set with Javascript https://github.com/js-cookie/js-cookie when a button is clicked. When I started out I tried to use native Craft cookies to get the cookie value as per your article here https://nystudio107.com/blog/cutting-the-cord-removing-plugins#plugin-2-cookies. However, it seems that the cookie is not returned using the native get method. So after someone recommended on Discord they used your plugin to get the JS cookie I tried it and it works! Great 🎉

However, I wondered what the plugin is doing differently to the native approach that allows the get method to work?
For clarity I have added some code below.

<button
        @click="showNotice = false; Cookies.set('{{ cookie.name }}', '{{ cookie.content }}', { expires: {{ cookie.expires }} })"
        class="js-bannerNotice hover:bg-white hover:text-red-600 focus:outline-none"
      >
        {{ svg('@icon/bx-line/bx-x.svg')|attr({ class:" w-10 h-10 flex-shrink-0 fill-current
      " }) }}
        <span class="sr-only">Close</span>
</button>

Using the plugin I can check the cookie exists like this:

{% if not getCookie(cookie.name) %}
Banner notice here
{% endif %}

However, using the native approach this does not return anything:

{% set requestCookies = craft.app.request.cookies %}
{% set cookieName = requestCookies.get(cookie.name) %}
{{ dump(cookieName) }}

Came across this question when I was experiencing the same thing and thought I’d share that I found I could see the cookie I was setting with JS using:

{% set requestCookies = craft.app.request.rawCookies %}