Rails rejects a POST with 'Can't verify CSRF token authenticity'
WARNING: Can't verify CSRF token authenticityShort 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.
Fix it fast
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.log2Match what you see, then jump to its fix
- 1
The page source has no meta tag named csrf-tokenThe layout does not render the token tagsFix - 2
Normal forms work, but the call made by your JavaScript failsAjax or fetch requests do not send the tokenFix - 3
The caller is a mobile app, webhook or script that sends no browser sessionA token-authenticated API controller uses the browser protectionFix - 4
The 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
- 1
What does the error look like?
WARNING: Can't verify CSRF token authenticityActionController::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/*.erb2Fix
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 csrfConfirmed by guides.rubyonrails.org
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]")?.content2Fix
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.logConfirmed by guides.rubyonrails.org
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/controllers2Fix
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
end3Verify
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/ordersConfirmed by api.rubyonrails.org
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/controllers2Fix
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
end3Verify
Open a form, clear the cookie, submit; you land back on the page with the message.
# manual check in the browserConfirmed by guides.rubyonrails.org
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 fixWeb apps
AuthUserPoolException: Auth UserPool not configured in a Next.js app
Auth UserPool not configured
The error means an Amplify Auth call ran before Amplify.configure did.
3 causes, each with a fixWeb apps
Module not found for antd/dist/antd.less after upgrading to Ant Design 5
Module not found: Error: Can't resolve 'antd/dist/antd.less'
Ant Design 5 dropped Less and the bundled CSS file for CSS-in-JS, so antd/dist/antd.less no longer exists.
3 causes, each with a fixWeb apps
Apollo Server rejects a request as a potential CSRF
HTTP 400 Bad Request from the GraphQL endpoint
Apollo Server's CSRF prevention is on by default.
3 causes, each with a fixWeb apps
Apollo Client is blocked by CORS when the GraphQL server runs on AWS Lambda
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Apollo Server does not set CORS for you when it runs behind a framework or integration, and on Lambda that layer is API Gateway.
5 causes, each with a fixWeb 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