Csrf token not being sent in fetch request?

Hey all! I’m trying to send a fetch post request to my backend. The request looks like so:

    fetch(url, {
      method: 'POST',
      cache: 'no-cache', 
      credentials: 'same-origin', 
      headers: {
        'x-csrf-token' : <%= csrf_token_value() %>

However, I’m recieving the following error:

[debug] ** (Plug.CSRFProtection.InvalidCSRFTokenError) invalid CSRF (Cross Site Request Forgery) token, please make sure that:

  * The session cookie is being sent and session is loaded
  * The request include a valid '_csrf_token' param or 'x-csrf-token' header

When I inspect the network activity, this is what I see:

Which looks like the header just isn’t being included in the request at all? What am I doing wrong here and how can I fix it?

Can you verify that this code is being generated correctly in the html source code?

I think you have to wrap the eex tag in quotes '<%= csrf_token_value() %>'


I don’t really recommend interpolating inside of javascript, it tends to cause issues. Instead, use the normal app.js file, and fetch the csrf token value from the dom element it’s on normally.