Showing posts from May, 2018

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

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:

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

fetch("/someURL/", {
    method: "post",
    headers: {
       "X-CSRFToken": token
    credentials: "include"