I’m working on a project where the frontend and backend are completely separate. The frontend is a single-page app hosted on its own server with nginx. The backend is a Django app on a different domain that only serves JSON API responses.
I’m confused about how to implement CSRF protection in this setup. Usually, Django includes the CSRF token in the rendered HTML, but that’s not possible here.
Has anyone dealt with this before? What’s the best way to get the CSRF token to the frontend and include it in API requests? Are there any security concerns I should be aware of?
I’ve tried looking for solutions online, but most assume the frontend and backend are on the same domain. Any help would be appreciated!
hey there, i’ve dealt with this before. one approach is to create a separate endpoint that returns the csrf token. your frontend can fetch it on load and store it. then include the token in the headers of subsequent api requests.
just make sure to use https and handle token expiration. good luck with ur project!
interesting question! have u considered using JWT tokens instead? they can handle authentication and CSRF protection in one go. plus, they’re stateless which is great for decoupled setups.
what kinda frontend framework r u using? some have built-in solutions for this. curious to hear more about ur project!
For decoupled setups, you can implement CSRF protection using a combination of techniques. One effective method is to leverage Django’s built-in CSRF middleware alongside a custom authentication system.
First, create an endpoint that issues a CSRF token upon user authentication. Store this token securely in the frontend, such as in an HTTP-only cookie. For subsequent API requests, include the token in a custom HTTP header (e.g., ‘X-CSRFToken’).
On the backend, configure Django to expect the token in this custom header. You’ll need to modify your CSRF middleware settings accordingly. This approach maintains security while allowing cross-domain communication.
Remember to implement proper token rotation and expiration policies to enhance security further. Always use HTTPS to protect token transmission.