ruby javascript 16 lines · 2 tabs

CSRF protection for Rails and JSON APIs

Kai Nakamura Apr 2026
2 tabs
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  before_action :authenticate_user!
end
2 files · ruby, javascript Explain with highlit

CSRF is still relevant whenever browsers automatically attach credentials. I keep standard anti-forgery tokens on server-rendered forms and use same-site cookies plus explicit bearer tokens for SPA APIs. The key is matching the defense to the authentication mechanism instead of assuming one pattern fits everything.

Share this code

Here's the card — post it anywhere.

CSRF protection for Rails and JSON APIs — share card
Link copied