Search code examples
astrojs

How can I check if a cookie existis in client-side with Astro?


I'm trying to display a cookies banner if user didn't accept it yet using <script>. So, how can I access Astro.cookies.has() on client-side?

My current code is something like this (also using tailwind):

if (!userAcceptsCookies && !sessionStorage.getItem("cookies-denied")) {
    cookiesConsentBanner?.classList.remove("hidden");
  }

Solution

  • You can read the cookie in client-side javascript only if it's not a HttpOnly cookie. If it's not, you can use document.cookie, e.g.:

    const getCookies = () =>
      document.cookie.split(";")
        .map(str => str.trim().split(/=(.+)/))
        .reduce((acc, curr) => {
            acc[curr[0]] = curr[1];
            return acc;
        }, {})
    
    const userAcceptsCookies = !!getCookies()['nameOfYourCookie']
    

    Alternatively, in Astro componeents, you can pass the info from the server to your client-side script like this:

    ---
    const userCookie = !!Astro.cookies.get('nameOfYourCookie')
    ---
    
    <script data-userCookie={userCookie}>
      const userAcceptsCookies = !!document.currentScript.dataset.userCookie
    </script>