Skip to main content
Add link to Craft's own docs about this
Source Link
Jeremy Daalder
  • 7.6k
  • 14
  • 26

So normally in your main layout twig template, you'd have something like this to set some JS variables to hold the current CSRF token:

    {# Super preliminary JS Stuff #}
    <script type="text/javascript">
        window.csrfTokenName = "{{ craft.app.config.general.csrfTokenName|e('js') }}";
        window.csrfTokenValue = "{{ craft.app.request.csrfToken|e('js') }}";
        window.cartId = "{{ cart.id }}";
    </script>

Then, in your add-to-cart JS, you do something along the lines of this to add those variables to the form data:

   formData.push({
     name: window.csrfTokenName,
     value: window.csrfTokenValue
   })

Craft's own documentation for this is here:

https://craftcms.com/knowledge-base/enabling-csrf-protection#updating-your-javascript

So normally in your main layout twig template, you'd have something like this to set some JS variables to hold the current CSRF token:

    {# Super preliminary JS Stuff #}
    <script type="text/javascript">
        window.csrfTokenName = "{{ craft.app.config.general.csrfTokenName|e('js') }}";
        window.csrfTokenValue = "{{ craft.app.request.csrfToken|e('js') }}";
        window.cartId = "{{ cart.id }}";
    </script>

Then, in your add-to-cart JS, you do something along the lines of this to add those variables to the form data:

   formData.push({
     name: window.csrfTokenName,
     value: window.csrfTokenValue
   })

So normally in your main layout twig template, you'd have something like this to set some JS variables to hold the current CSRF token:

    {# Super preliminary JS Stuff #}
    <script type="text/javascript">
        window.csrfTokenName = "{{ craft.app.config.general.csrfTokenName|e('js') }}";
        window.csrfTokenValue = "{{ craft.app.request.csrfToken|e('js') }}";
        window.cartId = "{{ cart.id }}";
    </script>

Then, in your add-to-cart JS, you do something along the lines of this to add those variables to the form data:

   formData.push({
     name: window.csrfTokenName,
     value: window.csrfTokenValue
   })

Craft's own documentation for this is here:

https://craftcms.com/knowledge-base/enabling-csrf-protection#updating-your-javascript

Source Link
Jeremy Daalder
  • 7.6k
  • 14
  • 26

So normally in your main layout twig template, you'd have something like this to set some JS variables to hold the current CSRF token:

    {# Super preliminary JS Stuff #}
    <script type="text/javascript">
        window.csrfTokenName = "{{ craft.app.config.general.csrfTokenName|e('js') }}";
        window.csrfTokenValue = "{{ craft.app.request.csrfToken|e('js') }}";
        window.cartId = "{{ cart.id }}";
    </script>

Then, in your add-to-cart JS, you do something along the lines of this to add those variables to the form data:

   formData.push({
     name: window.csrfTokenName,
     value: window.csrfTokenValue
   })