CSRF (Cross-Site Request Forgery) is a type of malicious exploit where unauthorized commands are transmitted from a user that the web application trusts.
What Does That Mean?
Let’s say you’re logged into your bank account and unknowingly visit a malicious website. That website secretly sends a request (using your active session) to transfer money — without your permission. Yikes!
That’s where CSRF Tokens step in to protect your application.
⚙️ How Does CSRF Protection Work?
A CSRF token is a secret, unique value generated by the server and included in web forms or responses. When the client (browser/frontend) sends a state-changing request (like POST or DELETE), it must include this token. If the server receives the request without a valid token, it’s rejected.
CSRF in React & Next.js
In frontend apps like React or Next.js, you must:
Fetch the CSRF token (usually via a dedicated endpoint like /csrf-token)
Store it (preferably in memory or context)
Send it back via headers (X-CSRFToken) in all unsafe HTTP requests
fetch('/api/data', {
method: 'POST',
headers: {
'X-CSRFToken': csrfToken,
'Content-Type': 'application/json'
},
body: JSON.stringify({ ...data }),
credentials: 'include'
});
CSRF in Django
Django comes with CSRF protection out of the box via middleware. You can extract and return the CSRF token using:
from django.middleware.csrf import get_token
def csrf_token_view(request):
token = get_token(request)
return JsonResponse({'csrfToken': token})
Use X-CSRFToken header in frontend requests and Django will validate it against the session.
CSRF in Laravel
Laravel uses the VerifyCsrfToken middleware and offers the CSRF token via Blade templates or API routes:
Route::get('/csrf-token', function () {
return response()->json(['csrfToken' => csrf_token()]);
});
In your JS code, include this token in the headers for secure requests.
If you're not handling CSRF tokens properly:
Your users are vulnerable.
Your app is unsafe.
Your API is exposed.
I’ve written a full breakdown with visuals, best practices, and a detailed frontend-backend walkthrough here:
Are you using CSRF in your stack? What’s your implementation style?
Let me know in the comments!