Search code examples
djangofetchcsrfdjango-csrfjs-cookie

How to pass CSRF token in POST data to Django?


I am developing an application with Django backend and Next.js frontend. I am trying to POST data from the frontend to the backend using the fetch API. I am having problems passing a valid CSRF token in my POST data to Django.

I am trying to do it by including an X-CSRFToken header in my POST request and getting its value using the JavaScript Cookie Library recommended on Django's documentation.

Here is my fetch request:

import Cookies from 'js-cookie';

// POST data
fetch('http://127.0.0.1:8000/dictionary/define', {     
  method: 'POST',     
  headers: {'X-CSRFToken': Cookies.get('csrftoken')},     
  body: JSON.stringify(data)})    
.then(response => response.json())   
.then(data => console.log(data))
.catch(error => console.log(error));

The error I get from Django is of course one saying that the CSRF cookie was not set:

Forbidden (CSRF cookie not set.): /...

Can anybody tell me what I am missing here?


Solution

  • I solved this issue by including credentials in my request:

    import Cookies from 'js-cookie';
    
    // POST data
    fetch('http://127.0.0.1:8000/dictionary/define', {     
      method: 'POST',
      credentials: 'include',     
      headers: {'X-CSRFToken': Cookies.get('csrftoken')},     
      body: JSON.stringify(data)})    
    .then(response => response.json())   
    .then(data => console.log(data))
    .catch(error => console.log(error));