CSRF token from Cookie

I have integrated Svelte with PHP they are running on the same server but running in different directories. It easier this way for development.

It is working well and the client loves it but I cannot get the csrf token working on posts from Svelte so I have disabled csrf middleware which is not ideal.

In this section of the docs

it says
" The CSRF Token can be obtained in JavaScript via the Cookie csrfToken"

To this end I have tried

csrf_cookieValue = document.cookie
    .split('; ')
    .find(row => row.startsWith('csrfToken'))

xhr.setRequestHeader('X-CSRF-Token', csrf_cookieValue);

But the cookie value does not match when I try to do a POST.

Any Suggestions?

Javascript? I wonder if that’s a config option. My CSRF cookie is server-only.

I have a view where I need to post ajax data to the server and that fails without the CSRF. Since I have a form on the page, the CSRF is written to a hidden input. I just grab it (jquery) thus:


I guess you could do something like that and write your own javascript cookie.

You are putting the wrong half of the csrf token in the headers. Instead of putting the cookie value in, you need to output the csrfToken request attribute into an html element that you can read from svelte.

Cake’s csrf tokens require both the cookie and request data to work. In new releases these values are different.

Thanks for clarifying that.

What is the best way to suggest that statement is removed from the Docs.

There should be an ‘pencil’ button that expands to ‘improve this doc’ on the right side of the page. That will go to Github where you can edit the page and submit a pull request.

1 Like