CSRF token InvalidAuthenticityToken

You can query your <meta name="csrf-token"> element for the token and include it in the request’s headers:

fetch(…, {
  method: "PUT",
  credentials: "same-origin",
  headers: {
    "X-CSRF-Token": getMetaValue("csrf-token")
  },
  …
})

function getMetaValue(name) {
  const element = document.head.querySelector(`meta[name="${name}"]`)
  return element.getAttribute("content")
}
9 Likes