I've spent an hour debugging XSRF error because of ... fetch

Photo by Tim Gouw from Pexels

Yesterday we were working on a new subpage with a form. Let's use the new fetch API to make POST requests seemed like a good idea but we started getting errors from the server:

HTTP 403: Forbidden (XSRF cookie does not match POST argument)

Header X-XSRFToken was set, we tried passing value in the body, setting token in the template, setting it in the backend only in certain cases but nothing helped. Finally my coworker found out that we're not sending _xsrf cookie with the request at all so it generates a new one every time...

Turns out fetch doesn't send cookies by default. It's by design: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

The fix is incredibly simple: tell fetch to include credentials in the options:

_fetch("/someURL/", {  
method: "post",
headers: {
"X-CSRFToken": token
},
credentials: "include"
});


Share on Hacker News
Share on LinkedIn


← Home


Want to learn more?

Sign up to get a digest of my articles and interesting links via email every month.

* indicates required

Please select all the ways you would like to hear from Krzysztof Kula:

You can unsubscribe at any time by clicking the link in the footer of my emails.

I use Mailchimp as a marketing platform. By clicking below to subscribe, you acknowledge that your information will be transferred to Mailchimp for processing. Learn more about Mailchimp's privacy practices here.