CsrfToken only valid after page refresh - Django
I got confused with a strange issue with Jango CSRF tokens in my SPA.
When rendering my application, I make sure the token is set with ensure_csrf_cookie
. When I check my cookies I can see what csrftoken
is being stored correctly and I also send it as part of the request using:
headers: {
โX-CSRFTokenโ: getCsrfTokenFromCookie(),
}
When I delete the cookie csrftoken
and refresh the page a new one is set csrftoken
, but when I try to submit my request I get the error
message: "CSRF Failed: CSRF token is missing or invalid."
But if I refresh the page again, the request is sent with the same csrfToken cookie!
I'm not sure what is causing this inconsistency. Any thoughts?
source to share