CSRF token with fetch

Read the token from a meta tag and send it in a header.

AJAX · CSRF token with fetchIntermediate
const csrf = document.querySelector('meta[name="csrf-token"]').content;

function post(url, data) {
  return fetch(url, {
    method: 'POST',
    credentials: 'same-origin',
    headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': csrf },
    body: JSON.stringify(data)
  });
}

post('/api/delete', { id: 3 });
csrfsecurityheadersmeta