A Lesson in Credentials and Server Requests

less than 1 minute read

Maybe this will help someone else in the future. I’m prototyping a new feature on GameDev.net that requires AJAX calls to fetch JSON data for asynchronous processing and display. I’m using the Javascript fetch() API to make the request.

I’ve been wrestling with a problem where the CSRF token check was failing for the AJAX request. When generating the page, I save the CSRF token in a Javascript object so it can be used when making the AJAX requests.

I narrowed the problem down to a new session being generated independent from the original page load. Basically the server was thinking the AJAX request was a new “session”.

After a few hours of diving into the PHP code and web searches I found the solution.

Turns out the credentials parameter needs to be set to same-origin so the server knows to treat the AJAX request as the same session.

A very simple, one-line fix:

fetch(url, {
    headers: {
    credentials: 'same-origin'
.then(response => response.json()) {