Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Next.js and React

Rails rejects a POST with 'Can't verify CSRF token authenticity'

ErrorWARNING: Can't verify CSRF token authenticity

Short answer

Rails checks every non-GET request for a token that matches the session. The warning means the token was missing or wrong. Add csrf_meta_tags to the layout, send the X-CSRF-Token header from your Ajax code, and use a null_session strategy for token-authenticated API controllers.

  • Applies to Rails 7.2, Rails 8.0, Ruby 3.3
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Open the Rails log for the failing request. It shows the controller, the HTTP method and whether an authenticity_token parameter or X-CSRF-Token header arrived.

    tail -n 40 log/development.log
  2. 2Match what you see, then jump to its fix

    1. 1The page source has no meta tag named csrf-tokenThe layout does not render the token tagsFix
    2. 2Normal forms work, but the call made by your JavaScript failsAjax or fetch requests do not send the tokenFix
    3. 3The caller is a mobile app, webhook or script that sends no browser sessionA token-authenticated API controller uses the browser protectionFix
    4. 4The page was open for a long time, or sign-in and sign-out happened in another tabThe session cookie is gone or changed before the form is sentFix

What does the error look like?

  • WARNING: Can't verify CSRF token authenticity
  • ActionController::InvalidAuthenticityToken

Cause 1 of 4

The layout does not render the token tags

1Check

csrf_meta_tags must be in the head of every layout that renders forms. Look at the rendered page for the two meta tags.

grep -n 'csrf_meta_tags' app/views/layouts/*.erb

2Fix

Add the helper to the head of the layout.

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

3Verify

Reload the page and look for csrf-param and csrf-token meta tags, then submit the form.

curl -s http://localhost:3000/ | grep csrf

Confirmed by guides.rubyonrails.org

Did this fix it?

Cause 2 of 4

Ajax or fetch requests do not send the token

1Check

Turbo adds X-CSRF-Token itself. Other Ajax code has to add it as a default header. Check the failing request in the browser network tab for that header.

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

2Fix

Read the token from the meta tag and send it as the X-CSRF-Token header.

const token = document.head.querySelector("meta[name=csrf-token]")?.content;
await fetch("/orders", {
  method: "POST",
  headers: { "X-CSRF-Token": token, "Content-Type": "application/json" },
  body: JSON.stringify({ item: 1 }),
  credentials: "same-origin"
});

3Verify

The request returns 200 or 201 and the warning is gone from the log.

tail -n 20 log/development.log

Confirmed by guides.rubyonrails.org

Did this fix it?

Cause 3 of 4

A token-authenticated API controller uses the browser protection

1Check

Controllers inheriting from ActionController::Base are protected with the :exception strategy by default. API clients cannot send a session token.

grep -rn 'protect_from_forgery' app/controllers

2Fix

For API endpoints that authenticate some other way, use the null_session strategy. Unverified requests are handled with an empty session, so they must pass your own token check.

class Api::BaseController < ActionController::Base
  protect_from_forgery with: :null_session
end

3Verify

Call the endpoint with its API token; it should respond without the CSRF warning.

curl -i -X POST -H 'Authorization: Bearer TOKEN' http://localhost:3000/api/orders

Confirmed by api.rubyonrails.org

Did this fix it?

Cause 4 of 4

The session cookie is gone or changed before the form is sent

1Check

The Security guide says the exception is raised when the token is missing or incorrect on a non-GET request, and shows rescue_from for it. A form that was rendered before the session changed is one way to get there.

grep -rn 'InvalidAuthenticityToken' app/controllers

2Fix

Handle the exception and send the user back to a fresh form, instead of showing a server error.

class ApplicationController < ActionController::Base
  rescue_from ActionController::InvalidAuthenticityToken do
    redirect_back fallback_location: root_path, alert: "Your session expired. Please try again."
  end
end

3Verify

Open a form, clear the cookie, submit; you land back on the page with the message.

# manual check in the browser

Confirmed by guides.rubyonrails.org

Did this fix it?

How do I stop it coming back?

  • Keep csrf_meta_tags in every layout and use form helpers that add authenticity_token.
  • Set a default X-CSRF-Token header once in your Ajax wrapper, or use Turbo / Request.JS.
  • Give API controllers their own base class with an explicit protection strategy and a token check.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Related fixes

Web apps

tsconfig rejects allowImportingTsExtensions

An error that allowImportingTsExtensions needs noEmit or emitDeclarationOnly

allowImportingTsExtensions lets files import each other with .ts or .tsx extensions, and TypeScript only allows it together with noEmit or emitDeclarationOnly.

2 causes, each with a fix

Web apps

A POST to a Google Apps Script web app returns 405 or a CORS error

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Apps Script web apps run doPost for POST and doGet for GET, and the Apps Script guides describe no other entry points.

3 causes, each with a fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.