How to handle CSRF protection with completely decoupled frontend and backend servers

I’m working on a project where my frontend and backend are running on completely different servers with separate domains. The frontend runs on nginx and uses a single page application approach with hash routing.

Most tutorials I find online assume the frontend is rendered by Django templates, so they can easily include the CSRF token in forms or pass it through cookies. But in my setup, the backend only serves JSON API endpoints and has no connection to the frontend server.

How can I get the CSRF token from my Django backend to use in my frontend requests? Since they’re on different domains, I can’t rely on the usual cookie-based approach that works when everything runs together.

What’s the best way to implement CSRF protection in this kind of separated architecture?

Interesting challenge! Why not try sessionid auth instead of CSRF tokens? How are you handling user sessions across domains - using Redis for shared session storage? Also, have you checked out django-cors-headers for the cross-domain setup?

Django has a built-in endpoint for CSRF tokens that’s perfect for decoupled setups. Just create a view that returns the token as JSON and hit it from your frontend before making authenticated requests. I’ve done this before - I make an initial call to /csrf-token/ when the app loads. The backend sends back a fresh token, I store it in my state management, then include it in the X-CSRFToken header for API calls. The trick is configuring your Django settings to allow cross-origin requests for the CSRF endpoint while keeping your actual API endpoints protected. You’ll need proper CORS setup and CSRF_COOKIE_HTTPONLY = False if you’re using cookie-based retrieval, but the dedicated endpoint approach works better for completely separate domains.

jwt tokens r a great alt for api auth! csfr can be tricky with diff domains. jwt’s stateless approach makes it perfect for ur setup - just auth once, get ur token, and you’re good for future requests. no more csfr issues, yay!