Skip to content

Commit 36c8797

Browse files
authored
Merge pull request #15 from inertiajs/always-include-csrf
Automatically include and document CSRF tokens
2 parents 0f06c7f + 5d8cbeb commit 36c8797

File tree

3 files changed

+30
-0
lines changed

3 files changed

+30
-0
lines changed

README.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,25 @@ your frontend of choice, just replace the contents of `entry.js` with [this file
4343

4444
You can also check out the official Inertia docs at https://inertiajs.com/.
4545

46+
### CSRF
47+
48+
Django's CSRF tokens are tightly coupled with rendering templates so Inertia Django automatically handles adding the CSRF cookie for you to each Inertia response. Because the default names Django users for the CSRF headers don't match Axios (the Javascript request library Inertia uses), we'll need to either modify Axios's defaults OR Django's settings.
49+
50+
**You only need to choose one of the following options, just pick whichever makes the most sense to you!**
51+
52+
In your `entry.js` file
53+
```javascript
54+
axios.defaults.xsrfHeaderName = "X-CSRFToken"
55+
axios.defaults.xsrfCookieName = "csrftoken"
56+
```
57+
OR
58+
59+
In your Django `settings.py` file
60+
```python
61+
CSRF_HEADER_NAME = 'HTTP_X_XSRF_TOKEN'
62+
CSRF_COOKIE_NAME = 'XSRF-TOKEN'
63+
```
64+
4665
## Usage
4766

4867
### Responses

inertia/middleware.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from .settings import settings
22
from django.contrib import messages
33
from django.http import HttpResponse
4+
from django.middleware.csrf import get_token
45

56
class InertiaMiddleware:
67
def __init__(self, get_response):
@@ -12,6 +13,10 @@ def __call__(self, request):
1213
if not self.is_inertia_request(request):
1314
return response
1415

16+
# Inertia requests don't ever render templates, so they skip the typical Django
17+
# CSRF path. We'll manually add a CSRF token for every request here.
18+
get_token(request)
19+
1520
if self.is_non_post_redirect(request, response):
1621
response.status_code = 303
1722

inertia/tests/test_rendering.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,3 +98,9 @@ def test_that_shared_props_are_merged(self):
9898
self.inertia.get('/share/'),
9999
inertia_page('share', props={'name': 'Brandon', 'position': 'goalie', 'number': 29})
100100
)
101+
102+
class CSRFTestCase(InertiaTestCase):
103+
def test_that_csrf_inclusion_is_automatic(self):
104+
response = self.inertia.get('/props/')
105+
106+
self.assertIsNotNone(response.cookies.get('csrftoken'))

0 commit comments

Comments
 (0)