How To: Use Cloudflare Turnstile with Devise - heartcombo/devise GitHub Wiki
To protect Devise forms with Cloudflare Turnstile (a CAPTCHA alternative), use the devise-cloudflare-turnstile gem. It auto-injects the widget and verifies responses on Devise create actions. No changes to Devise views or controllers are required.
Add the gem and run the installer:
# Gemfile
gem 'devise-cloudflare-turnstile'bundle install
bin/rails generate devise_cloudflare_turnstile:installAdd these two helpers to your layout's <head> (for example app/views/layouts/application.html.erb):
<%= devise_turnstile_meta_tag %>
<%= devise_turnstile_scripts %>Both render nothing on non-Devise pages, so they are safe in a shared layout.
Create a site in the Cloudflare Turnstile dashboard, then set your keys (via environment variables or the generated initializer):
export CLOUDFLARE_TURNSTILE_SITE_KEY=your_site_key
export CLOUDFLARE_TURNSTILE_SECRET_KEY=your_secret_keyThat is enough to protect Devise sign in, sign up, password-reset request, and resend confirmation/unlock forms.
Skip whole controllers or specific actions in the initializer:
# config/initializers/cloudflare_turnstile.rb
Cloudflare::Turnstile::Rails.configure do |config|
config.skip :confirmations # every action
config.skip passwords: :create # a single action
config.skip unlocks: %i[new create] # a set of actions
endOr use the skip_turnstile macro in a custom Devise controller:
class Users::PasswordsController < Devise::PasswordsController
skip_turnstile # every action
# skip_turnstile only: :create
endThis gem covers Devise forms only. For contact, checkout, or other forms, use cloudflare-turnstile-rails directly. It is installed as a dependency and shares the same configuration.
- devise-cloudflare-turnstile - full documentation, widget customization, and testing keys
- cloudflare-turnstile-rails - Rails helpers for non-Devise forms
- Cloudflare Turnstile docs