Django returns 403 for a fetch or AJAX POST because the CSRF token is not sent
POST http://localhost:8000/api/save/ 403 (Forbidden)Short answer
A JavaScript POST has no form field, so Django needs the token in the X-CSRFToken header. Read it from the csrftoken cookie, or from a {% csrf_token %} field in the page if CSRF_COOKIE_HTTPONLY or CSRF_USE_SESSIONS is on. Pages with no form must be served by a view with ensure_csrf_cookie so the cookie exists.
Fix it fast
1Find out which cause you have
In the browser's network tab open the failed POST. Check whether the request carries an X-CSRFToken header and a Cookie with csrftoken. What is missing decides the cause.
# same check from the shell, after copying the cookie value from the browser curl -i -X POST https://app.example.com/api/save/ \ -H "Cookie: csrftoken=PASTE_COOKIE" \ -H "X-CSRFToken: PASTE_COOKIE" \ -H "Referer: https://app.example.com/" \ -d "x=1"2Match what you see, then jump to its fix
- 1
Request headers show no X-CSRFToken (or whatever CSRF_HEADER_NAME maps to)The request has no X-CSRFToken headerFix - 2
getCookie returns undefined even though the Set-Cookie header was sentJavaScript cannot read the cookie, because it is HttpOnly or tokens live in the sessionFix - 3
The log says the CSRF cookie is missing, and the browser has no csrftoken cookie for the siteThe page has no form, so Django never set the CSRF cookieFix - 4
The request has X-XSRF-TOKEN or another name, and the token is correctThe client sends a different header name than Django expectsFix
- 1
What does the error look like?
POST http://localhost:8000/api/save/ 403 (Forbidden)403 Forbidden on an XMLHttpRequest or fetch POST to a Django view
Cause 1 of 4
The request has no X-CSRFToken header
1Check
Django reads the token for JavaScript requests from the header named by CSRF_HEADER_NAME, X-CSRFToken by default, unless it is in the POST data.
python manage.py shell -c "from django.conf import settings as s; print(s.CSRF_HEADER_NAME, s.CSRF_COOKIE_NAME)"2Fix
Set the header on every unsafe fetch request. mode same-origin keeps the token from being sent to another domain.
function getCookie(name) {
return document.cookie.split("; ")
.find(row => row.startsWith(name + "="))?.split("=")[1];
}
const csrftoken = getCookie("csrftoken");
await fetch("/api/save/", {
method: "POST",
headers: {"X-CSRFToken": csrftoken, "Content-Type": "application/json"},
mode: "same-origin",
body: JSON.stringify({x: 1}),
});3Verify
The POST now returns 200 and the request shows the X-CSRFToken header.
# Network tab: Request Headers contains X-CSRFTokenConfirmed by docs.djangoproject.com
Cause 2 of 4
JavaScript cannot read the cookie, because it is HttpOnly or tokens live in the session
1Check
Django documents that the cookie is only a usable token source when both CSRF_USE_SESSIONS and CSRF_COOKIE_HTTPONLY are False.
python manage.py shell -c "from django.conf import settings as s; print(s.CSRF_COOKIE_HTTPONLY, s.CSRF_USE_SESSIONS)"2Fix
Render the token into the page and read it from the DOM, instead of from the cookie.
{% csrf_token %}
<script>
const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
</script>3Verify
csrftoken in the console shows a long string and the POST succeeds.
# Browser console: console.log(csrftoken)Confirmed by docs.djangoproject.com
Cause 3 of 4
The page has no form, so Django never set the CSRF cookie
1Check
Django sets the cookie when a template with the csrf_token tag is rendered. A page that builds its forms in JavaScript may not contain the tag.
curl -s -D - -o /dev/null https://app.example.com/dashboard/ | grep -i 'set-cookie: csrftoken'2Fix
Decorate the view that serves the page with ensure_csrf_cookie.
from django.views.decorators.csrf import ensure_csrf_cookie
from django.shortcuts import render
@ensure_csrf_cookie
def dashboard(request):
return render(request, "dashboard.html")3Verify
The page response now carries a csrftoken Set-Cookie header.
curl -s -D - -o /dev/null https://app.example.com/dashboard/ | grep -i 'set-cookie: csrftoken'Confirmed by docs.djangoproject.com
Cause 4 of 4
The client sends a different header name than Django expects
1Check
Some JavaScript libraries send a different header by default. Django only accepts the name in CSRF_HEADER_NAME.
grep -R "XSRF\|xsrfHeaderName" frontend/src 2>/dev/null2Fix
Make the client send X-CSRFToken, or change the setting to the header the client sends.
# settings.py, for a client that sends X-XSRF-TOKEN
CSRF_HEADER_NAME = "HTTP_X_XSRF_TOKEN"3Verify
Restart Django and repeat the POST.
sudo systemctl restart gunicornConfirmed by docs.djangoproject.com
How do I stop it coming back?
- Wrap fetch in one small helper that always adds the X-CSRFToken header.
- Use ensure_csrf_cookie on every single-page entry view.
- Keep CSRF protection on; an exempt view that accepts cookie sessions is open to forged requests.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Related fixes
Back end
Django form POST returns 403 Forbidden: CSRF verification failed
CSRF verification failed. Request aborted.
Django rejects an unsafe request when the CSRF cookie or the form token is missing or wrong, or when the Origin or Referer check fails.
5 causes, each with a fixBack end
Airflow SSHOperator stops a long script with SSH command timed out
airflow.exceptions.AirflowException: SSH command timed out
SSHOperator waits only 10 seconds for a command by default.
3 causes, each with a fixBack end
Android gets HTML instead of JSON from a PHP API
org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
The response body is not JSON.
2 causes, each with a fixBack end
ng serve says it cannot determine the project or target
Cannot determine project for command.
The Angular CLI looked through angular.json for a project that defines the target you asked for (serve, build, test) and found none, or found several and could not pick one.
3 causes, each with a fixBack end
ng fails with Cannot find module @angular/cli/bin/ng
Cannot find module '@angular/cli/bin/ng'
The ng command is the entry point to the Angular CLI package.
2 causes, each with a fixBack end
Angular app shows 'Cannot GET /' when served by a Node.js server
Cannot GET /dashboard
Cannot GET / is Express saying no route or file matches the request.
3 causes, each with a fix