With each ajax request, a new session is created on the server (in the storage/sessions/ folder)
I am writing a token to the session, then I insert it like this
<meta name="csrf" content="<?= $_getToken ?>">
so that js could pull it out and send ajax request om '

That's how I pull and send token

 let formData = new FormData(); formData.append('_token', document.querySelector('#csrf').content) fetch('/cart/add', { method: 'POST', headers: { PHPSESSID: token }, body: formData }) .then(function (response) { return response.json() }).then(function (json) { console.log('parsed json', json) }).catch(function (ex) { console.log('parsing failed', ex) }) 

Class session
Class FileSessionHandler

  • one
    And if you add credentials: 'include' to the fetch parameters? - andreymal
  • it worked, thank you so much, you can offer as an answer - jashka

1 answer 1

fetch bit paranoid and by default does not send cookies from the site to which the request is sent (and the session ID is stored in the PHPSESSID PHPSESSID ). The credentials option is responsible for the transfer of cookies and authorization headers, which can have one of the following values:

  • 'omit' (default) - do not pass cookies and authorization headers;

  • 'same-origin' only if the domain to which the request is sent matches the domain of the current site (more precisely, origin; difficult case, but does not concern the current question, so I will not describe it in detail);

  • 'include' - transmit.

Actually, in this case, simply write 'include' :

 fetch('/cart/add', { method: 'POST', credentials: 'include', body: formData }) 

PS PHPSESSID is not a header, but a cookie, you don’t need to push it into the headers , the browser will transmit all the necessary cookies