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

posted Originally published at medium.com 1 min read

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!

If you read this far, tweet to the author to show them you care. Tweet a Thanks
0 votes
0 votes
0 votes

More Posts

Implementing Secure Authentication in Modern Web Apps: OAuth 2.0 & JWT with Angular and Node.js

Sunny - Oct 2

Laravel 12 & Laravel Cloud: The Next Big Leap in Web Development

Snehal Kadwe - Mar 9

PDF Viewer in React and Understanding PDF.js Layers

Sunny - Jul 14

Mastering React: A Mindset for Component-Centric Development

Losalini Rokocakau - May 3, 2024

Build a Full-Stack Video Streaming App with React.js, Node.js, Next.js, MongoDB, Bunny CDN, and Material UI

torver213 - Mar 29
chevron_left