javascriptcookiesjs-cookie

How to make Cookies.get find a cookie that was set on domain with or without WWW prefix respectively


I use js-cookie for an age gate. All works fine except that when I first visit the site with www prefix and pass the age gate (cookie is correctly recorded), and then visit the site again but without WWW, the cookie is not found and age gate pops up again. Is there a way to fix it?

Here is my current code:

<!-- Age Gate -->
<script src = "https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.2.1/js.cookie.js"></script>

<script>
    
    // if no validAge cookie then show the age gate
    if (!Cookies.get('validAge')) {
        $('.age-gate__modal').show();
    }

    // when button is clicked, check if the birthday is above 18 years old
    $(".age-enter").on('click', function(e) {

        // get year, month & day values
        const year = $('#verify-year').val();
        const month = $('#verify-month').val();
        const day = $('#verify-day').val();

        // make date string
        const date = year + '/' + month + '/' + day;

        // if user's age >= 18
        if (getAge(date) >= 18) {

            // give the user a validAge cookie
            Cookies.set('validAge', true, {
                expires: 90
            });
            // hide the age gate popup
            $('.age-gate__modal').hide();

        } else { // if user's age < 18
            
            // hide for form and show the error
            $('.age-gate__error').show();
            
        }
    });

    // getAge function
    function getAge(dateString) {
        const today = new Date();
        const birthDate = new Date(dateString);
        let age = today.getFullYear() - birthDate.getFullYear();
        const month = today.getMonth() - birthDate.getMonth();
        if (month < 0 || (month === 0 && today.getDate() < birthDate.getDate())) {
            age--;
        }
        return age;
    }

</script>

<!-- Age Gate END -->

Solution

  • You can use the domain option to set the cookie for the whole domain.

    Cookies.set('validAge', true, {
        expires: 90,
        domain: '.example.com'
    });