# CSRF token InvalidAuthenticityToken

**URL:** <https://discuss.hotwired.dev/t/csrf-token-invalidauthenticitytoken/91>\
**Category:** General\
**Created:** [February 15, 2018, 5:01am UTC](https://discuss.hotwired.dev/t/csrf-token-invalidauthenticitytoken/91 "2018-02-15T05:01:44Z")\
**Posts on this page:** 9\
**Page:** 1

<div class="post-metadata">

**Author:** ![basicBrogrammer](https://yyz1.discourse-cdn.com/flex027/user_avatar/discuss.hotwired.dev/basicbrogrammer/32/41_2.png) [@basicBrogrammer](https://discuss.hotwired.dev/u/basicBrogrammer)\
**Post date:** [February 15, 2018, 5:01am UTC](https://discuss.hotwired.dev/t/csrf-token-invalidauthenticitytoken/91/1 "2018-02-15T05:01:44Z")

</div>

I tried to use a fetch(… method: ‘PUT’) and I’m getting an InvalidAuthenticityToken error. I’m guessing this has something to do with the csrf token. Has anyone fixed this problem ?

---

<div class="post-metadata">

**Author:** ![scottharvey](https://yyz1.discourse-cdn.com/flex027/user_avatar/discuss.hotwired.dev/scottharvey/32/10_2.png) [@scottharvey](https://discuss.hotwired.dev/u/scottharvey)\
**Post date:** [February 15, 2018, 1:03pm UTC](https://discuss.hotwired.dev/t/csrf-token-invalidauthenticitytoken/91/2 "2018-02-15T13:03:59Z")

</div>

Are you using the `jquery_ujs` or the `rails_ujs` gem?

In my application I’m using `jquery_ujs` and haven’t had any issues with authenticity tokens.

---

<div class="post-metadata">

**Author:** ![javan](https://yyz1.discourse-cdn.com/flex027/user_avatar/discuss.hotwired.dev/javan/32/594_2.png) [@javan](https://discuss.hotwired.dev/u/javan)\
**Post date:** [February 15, 2018, 1:44pm UTC](https://discuss.hotwired.dev/t/csrf-token-invalidauthenticitytoken/91/3 "2018-02-15T13:44:01Z")

</div>

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

```auto
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")
}

```

---

<div class="post-metadata">

**Author:** ![basicBrogrammer](https://yyz1.discourse-cdn.com/flex027/user_avatar/discuss.hotwired.dev/basicbrogrammer/32/41_2.png) [@basicBrogrammer](https://discuss.hotwired.dev/u/basicBrogrammer)\
**Post date:** [February 15, 2018, 2:34pm UTC](https://discuss.hotwired.dev/t/csrf-token-invalidauthenticitytoken/91/4 "2018-02-15T14:34:49Z")

</div>

That’s what I ended up doing. I wasn’t sure if that was the best practices.  
What was curious though…  
`document.querySelector(`meta[name="${name}"]`).content` #=\> worked  
however;  
`$(`meta[name="${name}"]`).content` #=\> didn’t work work in a debugger in the stimulus controller. If I let the page finish loading, it does work 😕

---

<div class="post-metadata">

**Author:** ![basicBrogrammer](https://yyz1.discourse-cdn.com/flex027/user_avatar/discuss.hotwired.dev/basicbrogrammer/32/41_2.png) [@basicBrogrammer](https://discuss.hotwired.dev/u/basicBrogrammer)\
**Post date:** [February 15, 2018, 2:35pm UTC](https://discuss.hotwired.dev/t/csrf-token-invalidauthenticitytoken/91/5 "2018-02-15T14:35:42Z")

</div>

@scottharvey I’m using the gem, but stimulus is in webpack… so those don’t crossover do they ?

---

<div class="post-metadata">

**Author:** ![scottharvey](https://yyz1.discourse-cdn.com/flex027/user_avatar/discuss.hotwired.dev/scottharvey/32/10_2.png) [@scottharvey](https://discuss.hotwired.dev/u/scottharvey)\
**Post date:** [February 16, 2018, 12:46am UTC](https://discuss.hotwired.dev/t/csrf-token-invalidauthenticitytoken/91/6 "2018-02-16T00:46:12Z")

</div>

`jquery_ujs` has [installation instructions](https://github.com/rails/jquery-ujs#installation-using-rails-and-webpacker) for webpack so it should work but I haven’t tried using Webpack.

---

<div class="post-metadata">

**Author:** ![adrienpoly](https://yyz1.discourse-cdn.com/flex027/user_avatar/discuss.hotwired.dev/adrienpoly/32/78_2.png) [@adrienpoly](https://discuss.hotwired.dev/u/adrienpoly)\
**Post date:** [February 21, 2018, 12:11am UTC](https://discuss.hotwired.dev/t/csrf-token-invalidauthenticitytoken/91/7 "2018-02-21T00:11:38Z")

</div>

Just to add my 2 cents to this thread, in a Rails app you can also use Rails-ujs ajax function. It is my understanding that it automatically includes the CSRF token for you.

As an example here is what I have been using in an app:

```auto
const data = new FormData();
data.append("myModelName[field]", value);

Rails.ajax({
  url: "/my_post_url",
  type: "POST",
  data
});

```

---

<div class="post-metadata">

**Author:** ![will](https://yyz1.discourse-cdn.com/flex027/user_avatar/discuss.hotwired.dev/will/32/373_2.png) [@will](https://discuss.hotwired.dev/u/will)\
**Post date:** [November 8, 2018, 7:29pm UTC](https://discuss.hotwired.dev/t/csrf-token-invalidauthenticitytoken/91/8 "2018-11-08T19:29:33Z")

</div>

I have fixed this in the past using the `rails-ujs` module:

```javascript
import { Controller } from 'stimulus'
import Rails from 'rails-ujs'

export default class extends Controller {
  connect() {
    fetch('/some/url', {
      method: 'PUT',
      credentials: 'same-origin',
      headers: { 'X-CSRF_Token': Rails.csrfToken() }
    })
  }
}

```

---

<div class="post-metadata">

**Author:** ![kevinmirc](https://yyz1.discourse-cdn.com/flex027/user_avatar/discuss.hotwired.dev/kevinmirc/32/3511_2.png) [@kevinmirc](https://discuss.hotwired.dev/u/kevinmirc)\
**Post date:** [November 12, 2023, 11:38pm UTC](https://discuss.hotwired.dev/t/csrf-token-invalidauthenticitytoken/91/9 "2023-11-12T23:38:20Z")

</div>

Quick update in 2023 for anyone landing on this page.

The Ruby on Rails Guide (for v7) suggests using `FetchRequest` from the library `@rails/request.js`. This will automatically include the CSRF token in requests.

```js
import { FetchRequest } from '@rails/request.js'
...
async myMethod () {
  const request = new FetchRequest('post', 'localhost:3000/posts', {
    body: JSON.stringify({ name: 'Request.JS' })
  })
  const response = await request.perform()
  if (response.ok) {
    const body = await response.text
  }
}

```

If you’re using another http request library, the token can be included in the request header by querying the meta tag (as others suggested)

```js
document.head.querySelector("meta[name=csrf-token]")?.content

```

> **[Working with JavaScript in Rails — Ruby on Rails Guides](https://guides.rubyonrails.org/working_with_javascript_in_rails.html#ajax-requests)**
>
> Working with JavaScript in RailsThis guide covers the options for integrating JavaScript functionality into your Rails application, including the options you have for using external JavaScript packages and how to use Turbo with Rails.After reading...
