DEV Community

Cover image for πŸ” CSRF Token in Web Development: Secure Your React, Next.js, Django & Laravel Apps
Raj Aryan
Raj Aryan

Posted on

πŸ” CSRF Token in Web Development: Secure Your React, Next.js, Django & Laravel Apps

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'
});
Enter fullscreen mode Exit fullscreen mode

πŸ” 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})
Enter fullscreen mode Exit fullscreen mode

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()]);
});
Enter fullscreen mode Exit fullscreen mode

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)