Issue with CSRF Token and API Calls in Frappe React SDK

Issue with CSRF Token and API Calls in Frappe React SDK

Problem Statement

I am trying to make an API call to my Frappe backend from a React frontend using frappe-react-sdk. However, I am constantly running into a CSRFTokenError when making POST requests.

Error Message:

{
    "exc_type": "CSRFTokenError",
    "_server_messages": "[\"{\\\"message\\\": \\\"Invalid Request\\\", \\\"title\\\": \\\"Message\\\", \\\"indicator\\\": \\\"red\\\", \\\"raise_exception\\\": 1, \\\"__frappe_exc_id\\\": \\\"0dc38def5b7bd90fe85286c5740ee6488eeb29da1ac2b05d45db14c6\\\"}\"]"
}

What I Have Tried

:one: Fetching CSRF Token from Cookies
I checked my document.cookie and found a csrf_token, so I extracted it like this:

const getCSRFToken = () => {
  const cookies = document.cookie.split("; ");
  const csrfCookie = cookies.find(row => row.startsWith("csrf_token="));
  return csrfCookie ? csrfCookie.split("=")[1] : null;
};

Then, I included it in my API request:

const postDataToFrappe = async () => {
  const csrfToken = getCSRFToken();

  if (!csrfToken) {
    console.error("CSRF Token not found!");
    return;
  }

  try {
    const response = await fetch("http://demo.localhost:8000/api/method/frappe.client.set_value", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-Frappe-CSRF-Token": csrfToken
      },
      body: JSON.stringify({
        doctype: "User",
        name: "Administrator",
        fieldname: "interest",
        value: "AI & ML"
      }),
      credentials: "include" 
    });

    const data = await response.json();
    console.log("Response:", data);
  } catch (error) {
    console.error("Error:", error);
  }
};

:red_circle: Still getting CSRFTokenError!


:two: Fetching CSRF Token via API (Alternative Method)
I also tried fetching the CSRF token using the following API:

const fetchCsrfToken = async () => {
  const response = await fetch("http://demo.localhost:8000/api/method/frappe.auth.get_logged_user", {
    credentials: "include"
  });

  const data = await response.json();
  console.log("CSRF Token Response:", data);
  return data.csrf_token; 
};

However, the response does not contain a CSRF token, only this:

{ "message": "admin@demo.localhost" }

My Setup

  • Backend: Frappe (v16.0.0)
  • Frontend: React with frappe-react-sdk
  • Issue: CSRF token validation fails on POST requests

Questions & Help Needed

:one: How do I properly retrieve and pass the CSRF token in frappe-react-sdk?
:two: Why is the API frappe.auth.get_logged_user not returning a CSRF token?
:three: Am I missing any settings in Frappe (e.g., frappe.conf.ignore_csrf)?
:four: And also I want to pass the files to the api form react app that I have created ?

Any guidance would be greatly appreciated! :rocket:

Hello, check the tutorial from the react sdk developers. Alternatively you might want try Frappe Doppio which does the hard work for you.

Thanks , but I have already followed the step and the video uses the frappe as the base application but in this case my custom made and it is working in the postman on the production server but the data we are sending doesn’t give any output. it constantly gives csrf token error (Bad request) or gives error code 500 constantly

solved the code by accessing the window.csrftoken in the index.html