New blog domain: kula.blog

It's still work in progress but new posts will be published on  https://kula.blog/ Thanks to 11ty base blog RSS is working from the start so it should be easy to add to your reader if you still use any :) If now then I hope you can sign up to the newsletter where I'll be publishing new posts and interesting articles to it from time to time. Please use  kula.blog  from now on.

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"
});

```


Comments

Popular posts from this blog

How to simulate slow connection (developer proxy in Node.js)

Safari Mobile CSS VW and VH units bug.