Protect state-changing requests from CSRF
Quick answer
Cross-site request forgery (CSRF) abuses a browser’s ambient credentials to induce an unwanted state-changing operation. Servers need request authenticity controls as well as authentication and authorization.
How it works
Keep safe HTTP methods free of requested state changes. For cookie-authenticated mutations, use the framework’s established CSRF mechanism with server-side token validation and appropriate origin checks. Set explicit SameSite and Secure cookie attributes as appropriate; HttpOnly protects cookie visibility to scripts but does not stop the browser sending cookies. SameSite is site-based, not origin-based, and is defense in depth. The examples model narrow decisions using synthetic values; they are not a token implementation, real header parsing or a complete server policy.
Local examples
Run in Node.js v22.16.0 as a CommonJS script. Actual ByteMind editor support is unverified.
(async () => {const permit=(method,authorized,verified)=>method==="POST"&&authorized===true&&verified===true;console.log(permit("GET",true,true),permit("POST",true,true),permit("POST",true,false));})()Expected console output:
false true falseThe sample mutation is POST-only and needs both server decisions.
Run in Node.js v22.16.0 as a CommonJS script. Actual ByteMind editor support is unverified.
(async () => {const permitted=o=>o==="https://app.example";console.log(permitted("https://app.example"),permitted("https://help.example"),permitted(null));})()Expected console output:
true false falseThe modeled policy rejects the unrelated and absent values.
Common mistakes
Do not rely on a disabled submit button, client validation or CORS alone for CSRF protection.
Practice
Write an endpoint review checklist: safe-method semantics, server authorization, framework CSRF validation and explicit cookie policy.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Protect state-changing requests from CSRF — Knowledge Check
Apply the concept and reason about local example output.
Where must a cookie-authenticated mutation validate CSRF protection?
What is HttpOnly designed to restrict?
Why should a GET endpoint not perform a requested mutation?
What is the exact console output in Protect state-changing requests from CSRF example 1?
(async () => {const permit=(method,authorized,verified)=>method==="POST"&&authorized===true&&verified===true;console.log(permit("GET",true,true),permit("POST",true,true),permit("POST",true,false));})()What is the exact console output in Protect state-changing requests from CSRF example 2?
(async () => {const permitted=o=>o==="https://app.example";console.log(permitted("https://app.example"),permitted("https://help.example"),permitted(null));})()