Next.js Course
Next.js
/
Intermediate

CSRF Protection

Definition

Cross-Site Request Forgery (CSRF): An attack where a malicious site tricks a user's browser into executing an unwanted action on a site where they are currently authenticated.

Explain Like I'm New

You are logged into your Bank. You visit `EvilSite.com`. EvilSite secretly sends a POST request to `Bank.com/transfer-money`. Because your browser automatically attaches your Bank cookies, the Bank thinks YOU made the request.

Real World Example

Preventing CSRF by using `SameSite` cookies, ensuring that the browser ONLY sends cookies if the request actually originates from your own Next.js domain.

Common Use Cases

  • Form security
  • API protection
  • Cookie management

Interactive Example

// Setting a secure, CSRF-resistant cookie in Next.js Middleware
import { NextResponse } from 'next/server';

export function middleware(request) {
  const response = NextResponse.next();
  
  response.cookies.set('session_token', '12345abcde', {
    httpOnly: true, // Prevents XSS from stealing the cookie
    secure: true,   // Only sent over HTTPS
    
    // 🛡️ THE CSRF DEFENSE 🛡️
    // 'Strict' means the browser will NEVER send this cookie 
    // if the request comes from an external website.
    sameSite: 'strict', 
  });
  
  return response;
}

Interview Questions

basic

  • What attribute on a browser cookie is the primary defense against CSRF attacks in modern web development?

intermediate

  • Why do Server Actions in Next.js automatically protect you from CSRF attacks?

Flash Cards

Question

Cookie attribute?

Click to reveal answer
Answer

The `SameSite` attribute (usually set to `Lax` or `Strict`).

Question

Server Actions protect?

Click to reveal answer
Answer

Next.js Server Actions automatically implement 'Origin Matching'. They compare the `Origin` header of the incoming POST request to the server's actual host name. If they don't match, the request is violently rejected.