Why do I get CSRF errors when making AJAX calls with axios?
Making CSRF-enabled AJAX requests with Django is a frequent stumbling block. The site gets suspicious and rejects your JS-based requests, as the CSRF token is missing from the request. Everything just to make your Django project more secure, but it can be an annoying gotcha.
Here’s how to avoid CSRF errors when using axios with Django:
Set axios defaults, to pass along CSRF tokens
Before you start using axios to fetch and submit data, you have to configure it to work correctly.
To make sure, that axios does not miss submitting the CSRF token, you have to tell it where to find the data, and how to name it:
axios.defaults.xsrfCookieName = 'csrftoken'
axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"
The two fields describe the name of
- the cookie, where the CSRF token can be found
- the header field to which we write the token when doing a request
How do those two lines connect to Django?
By default, the CSRF token is passed to us by Django inside the cookie, and we let axios know which name to look out for. The Django settings variables in question are CSRF_COOKIE_NAME and CSRF_HEADER_NAME.
You might have seen that the Django docs define the default value of CSRF_HEADER_NAME as HTTP_X_CSRFTOKEN
,
but axios gets X-CSRFTOKEN
. Underscores are replaced by dashes, and the HTTP_
prefix is dropped for axios. Nothing fancy going on there.
Pitfalls
You might have to check other Django project settings to make sure everything is in sync. This is only the case, if you are working on an existing project, where somebody might have changed the default.
If your AJAX requests still don’t come through, check if other CSRF-related settings are changed from the default values. Search for CSRF here and look up corresponding setting fields in your project’s configs.
The setting CSRF_COOKIE_HTTPONLY might be set, which would prevent both the header and the cookie fields to be used for CSRF tokens. The easiest way to fix it, is to disable this if you can. Otherwise, JS will not be able to access the cookie at all. You can read more in this section of the docs if you’re still experiencing problems, or would like to get a deeper understanding.
That’s it!
I hope this overview has helped you to make your axios AJAX calls work, and the CSRF token is not in your way anymore. Have fun using Django with your fancy frontend JS framework of choice!
Don’t have a frontend framework yet? Try Vue.js.