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
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);
}
};
Still getting CSRFTokenError!
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
How do I properly retrieve and pass the CSRF token in
frappe-react-sdk
?
Why is the API
frappe.auth.get_logged_user
not returning a CSRF token?
Am I missing any settings in Frappe (e.g.,
frappe.conf.ignore_csrf
)?
And also I want to pass the files to the api form react app that I have created ?
Any guidance would be greatly appreciated!