I have a React SPA with a Django backend. Like most SPAs, there is an index.html file that needs to be served. But the problem is that this file is served with nginx, so user does not obtain csrf token required to make api calls. I don't really want to serve index.html, as it would require separating the file from the rest of npm run build
output and break the "just put it in /static/ directory" workflow, and also for caching reasons. Is there any other workaround?
Asked
Active
Viewed 516 times
3

RomaValcer
- 2,786
- 4
- 19
- 29
-
CSRF token is always updated with each page load. It has to be served by django no matter what you really want to do there with your nginx setups. Place the index.html file in django templates folder, serve it with your index view, translate CSRF token to javascript code and use it in your ReactJS code – Dmitrii G. Jul 19 '18 at 13:32
-
@DmitriiG. please make it into an answer, and I will gladly accept it. – RomaValcer Jul 19 '18 at 14:36
1 Answers
-1
CSRF token is always updated with each page load. It has to be served by django since django is the application that provides and validates it. Place the index.html file in your django templates folder, serve it with your index view, translate CSRF token to javascript code and use it in your ReactJS code
index.html
...
<body>
<script>
var csrftoken = '{{ csrf_token }}';
</script>
...
</body>
...

Dmitrii G.
- 895
- 1
- 7
- 21
-
Django will also set the corresponding cookie, if I am not mistaken. But it feels like a problem for scale, as it's serving a static file with Django. – RomaValcer Jul 19 '18 at 14:56
-
-
@RomaValcer sorry, didn't see your comment in time. If that is indeed a big problem for you, you can replace the native CSRF verification with an API endpoint. Basically serving the token by a GET request. You would be reinventing the wheel here, but that should do the trick in dynamically getting the token instead of getting it from rendered html canonical way. – Dmitrii G. Jul 23 '18 at 14:03
-
@RomaValcer Make sure to protect the API with same-origin policy though as that is the main purpose of CSRF protection. – Dmitrii G. Jul 23 '18 at 14:04