Skip to content

How To: Use Cloudflare Turnstile with Devise

Vadim Kononov edited this page Nov 6, 2026 · 1 revision

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.

Install

Add the gem and run the installer:

# Gemfile
gem 'devise-cloudflare-turnstile'
bundle install
bin/rails generate devise_cloudflare_turnstile:install

Add helpers to your layout

Add 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.

Configure API keys

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_key

That is enough to protect Devise sign in, sign up, password-reset request, and resend confirmation/unlock forms.

Skipping protection

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
end

Or use the skip_turnstile macro in a custom Devise controller:

class Users::PasswordsController < Devise::PasswordsController
  skip_turnstile # every action
  # skip_turnstile only: :create
end

Protecting non-Devise forms

This 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.

Further reading

Clone this wiki locally