React: How to get a Django CSRF Token if CSRF_TOKEN_HTTPONLY is true?

351 Views Asked by At

I'm building a React application for a Django backend. In the backend the security setting CSRF_TOKEN_HTTPONLY is set to True. How can I obtain this csrf token in a React app? The documentation only describes how to do that using jquery. I'm usin the fetch API for my http requests.

1

There are 1 best solutions below

0
On

If you include the csrf token in your HTML like the documentation says:

{% csrf_token %}

Then you can simply get the token like this:

var csrftoken = document.querySelector("[name=csrfmiddlewaretoken]").value

And do your requests with the Fetch API this way:

fetch(url, {
    credentials: 'include',
    method: 'POST',
    mode: 'same-origin',
    headers: {
      'X-CSRFToken': csrftoken
    },
    body: {}
})