Send asynchronous browser requests with fetch, XMLHttpRequest, JSON, errors, and progressive UI.
Lessons
Defend cookie-based requests against forgery.
CSRF Protection is easiest to learn by reading the example, changing it, and observing the result.
// Send a CSRF token with state-changing requests
const token = document.querySelector('meta[name="csrf-token"]').content;
await fetch('/api/lessons', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': token
},
credentials: 'same-origin',
body: JSON.stringify({ title: 'Safe POST' })
});Practice the CSRF Protection example in a small scratch file, then explain what changed and why.