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.
π TL;DR
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:
π Read the full guide on Medium
π¬ Are you using CSRF in your stack? Whatβs your implementation style?
Let me know in the comments! π
#webdev #react #nextjs #django #laravel #csrf #security #frontend #backend #fullstack #infosec #javascript #php #python #devto
Top comments (0)