ActionController::InvalidAuthenticityToken 💎 Ruby / Rails

Rails: ActionController::InvalidAuthenticityToken (Can't verify CSRF token authenticity)

A non-GET request arrived without a valid CSRF token for the session.

Seen on: Ruby

Meaning

Forms built without Rails helpers, AJAX/fetch calls missing the X-CSRF-Token header, cached pages, cookies blocked, or API clients hitting a controller that expects CSRF protection.

Common causes

  • Form without authenticity_token (manual HTML)
  • fetch/AJAX without X-CSRF-Token header
  • Session cookie lost (domain, SameSite, cache)
  • API requests to a non-API controller

⚡ Quick fix

  1. Use form_with / include csrf_meta_tags and send the header
  2. Use ActionController::API or skip_forgery_protection for token-authenticated APIs
  3. Check cookies/session store

Detailed fix by platform

JavaScript

  1. javascript
    const token = document.querySelector('meta[name="csrf-token"]').content;
    fetch("/posts", { method: "POST", headers: { "X-CSRF-Token": token, "Content-Type": "application/json" }, body: JSON.stringify(data) });

How to diagnose

  1. Request — Token sent?
  2. Session — Cookie present?
  3. Controller — API or HTML?

🔧 Still not fixed?

Many errors look alike. If the steps above didn’t solve it, one of these is probably what you’re facing:

🧠 Still stuck? Analyze your error

Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.