Need help fixing this error?ActionController::InvalidAuthenticityToken

Uh-oh, you ran into an error! Don't worry, AppSignal is here to help you. Besides monitoring for errors, we've written some guides on how to fix common errors. Let us know if you need any more help.

Read the solution below

Why does this error occur?

This error occurs when Rails' request forgery protection system does not accept a `POST`, `PUT` or `DELETE` request.

When Rails generates the HTML for a form or a XHR-powered link it adds a authenticity_token hidden field or parameter. Before letting the request through to the controller Rails checks that the parameter is present and correct.

The purpose of this protection mechanism is making it harder for bots do automated requests. They have to fetch the form as well and extract the authenticity_token from it.

There a number of things that can go wrong to cause this error:

Missing`csrf_meta_tags`

This Rails helper adds two meta tags that can be used from JavaScript to add the right parameters. This helper should be called in your layout file. If it's missing, requests sent via JavaScript will result in this error on the server.

erb
<head> <%= csrf_meta_tags %> </head>

Missing`jquery_ujs`

If the unobtrusive scripting adapter for jQuery is not required in your assets the necessary parameters are not added. Make sure the `jquery-rails` gem is installed and that this is present in your main assets file. If it's missing, requests sent via JavaScript will result in this error.

erb
//= require jquery //= require jquery_ujs

Page caching

If you use page caching, Rails will keep the static HTML for a page in the cache. After a while the authenticity token for this page is stale and posting a form will result in this error. In this case either don't use page caching, or disable the forgery protection for that controller action:

Ruby
skip_before_action :verify_authenticity_token

APIs and webhooks

If you have controllers that are meant to be called by external parties you should disable forgery protection. This is relevant the case for APIs and web hooks:

Ruby
skip_before_action :verify_authenticity_token

Packed with features

Real-time alerts.
Amazing insights.

Get real-time alerts for issues in your applications. Dive deep into your requests and data to debug issues to their core.

Start your free trial

Don’t let the bad bugs bite. Try AppSignal for free.

AppSignal offers a 30-day free trial, no credit card is required. All features are available in all plans. Start monitoring your application in just a few clicks!