inertiajs / inertia-django

The Django adapter for Inertia.js
MIT License
326 stars 32 forks source link

Modify axios xsrfHeaderName for the usage with Django #8

Closed l-kotzur closed 1 year ago

l-kotzur commented 2 years ago

First, thanks for the great framework.

Since the form submission and redirect with django provided me a little bit of headache, I wanted to share the following experience which could help other developers.

Django uses a different CSRF-Header name than set by axios as default. Therefore, it needs to be corrected during the creation of the inertia app:

axios.defaults.xsrfHeaderName = "X-CSRFToken"
axios.defaults.xsrfCookieName = "csrftoken"

This fixes axios but inertiajs still ended in an csrf verification error for my case. I found out that the axios version used by inertiajs deviated from the axios verison in the application. In consequence, the corrected token names are not taken (https://github.com/inertiajs/inertia/issues/1046). Installing the same axios version in the application finally fixed the issue.

This is an issue special to inertia-django. Nevertheless, the correction would need to happen in inertiajs.

tl;dr: In case of CSRF Verifcation failed, add the two lines to the configuration of axios and make sure that axios has the same version as axios used by inertiajs.

BrandonShar commented 2 years ago

Thanks @l-kotzur that's a a great solution! I used the following strategy for mine:

const csrfToken = document.querySelector('meta[name=csrf-token]').content;
axios.defaults.headers.common['X-CSRFToken'] = csrfToken;

but I like yours more! I'll leave this open for now while I figure out the best way to add it to the docs.

BrandonShar commented 2 years ago

I didn't realize it when I left that comment, but now I know that your solution is much better than mine! I created an inertia based login for for an app I'm working on and with my method, the csrf token is invalidated upon inertia based login (since there's no full page refresh to change the meta tags). Your solution worked great!

l-kotzur commented 2 years ago

Thanks! :)

Do you have any plans on publishing an example app with django and inertia using a login/authentification?

BrandonShar commented 1 year ago

I do and I should really get a move on with that :)

I should have some free time soon and I've been planning on doing some screencasts on using Django Inertia and publishing the code.