Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Node.js, PHP and APIs

Django returns 403 for a fetch or AJAX POST because the CSRF token is not sent

ErrorPOST 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.

  • Applies to Django 4.2 LTS, 5.2 LTS, current Chrome and Firefox
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 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"
  2. 2Match what you see, then jump to its fix

    1. 1Request headers show no X-CSRFToken (or whatever CSRF_HEADER_NAME maps to)The request has no X-CSRFToken headerFix
    2. 2getCookie 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. 3The 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. 4The request has X-XSRF-TOKEN or another name, and the token is correctThe client sends a different header name than Django expectsFix

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-CSRFToken

Confirmed by docs.djangoproject.com

Did this fix it?

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

Did this fix it?

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

Did this fix it?

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/null

2Fix

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 gunicorn

Confirmed by docs.djangoproject.com

Did this fix it?

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

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 fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.