Ruby on Rails CAPTCHA Integration
This recipe shows how to integrate TrustCaptcha into a Ruby on Rails application. The frontend setup is the same as for any other Ruby application — this page focuses on the server-side validation.
The setup section gets you to a working integration in three small steps using a controller action directly. Below it, an optional refactor section shows the more reusable Rails-idiomatic approach (a before_action callback in ApplicationController).
Preparation
Section titled “Preparation”You should have already completed the following steps before you wire TrustCaptcha into your Rails application.
Read Get-Started: Get a quick overview of the concepts behind TrustCaptcha and the integration process in get started.
Existing CAPTCHA: If you don’t have a CAPTCHA yet, sign in or create a new user account. Then create a new CAPTCHA.
1. Embed the frontend widget
Section titled “1. Embed the frontend widget”First, add the TrustCaptcha script to your page (see the JavaScript Guide for version pinning and self-hosting options).
Then place the <trustcaptcha-component> element inside your ERB form. The widget appends a hidden tc-verification-token field on submit, which your Rails controller receives in params like any other form input.
<script type="module" src="https://cdn.trustcomponent.com/trustcaptcha/3.0.x/trustcaptcha.esm.min.js"></script>
<%= form_with url: contact_path, method: :post, local: true do |form| %> <%= form.label :email %> <%= form.email_field :email, required: true %>
<trustcaptcha-component sitekey="<your_site_key>"></trustcaptcha-component>
<%= form.submit "Send" %><% end %>See the Widget Overview for the full property reference.
2. Install the Ruby SDK
Section titled “2. Install the Ruby SDK”gem 'trustcaptcha', '~> 3.0'bundle install3. Validate the token in your controller
Section titled “3. Validate the token in your controller”require 'trustcaptcha/trust_captcha'
class ContactsController < ApplicationController def create # In production, load from credentials: Rails.application.credentials.trustcaptcha[:api_key] api_key = '<your_api_key>' token = params['tc-verification-token'].to_s
begin trust_captcha = TrustCaptcha.new(api_key) result = trust_captcha.get_verification_result(token) rescue StandardError flash.now[:alert] = 'CAPTCHA verification failed.' return render :new, status: :bad_request end
if !result.verification_passed || result.score > 0.5 flash.now[:alert] = 'CAPTCHA verification failed.' return render :new, status: :bad_request end
# CAPTCHA passed — params are safe to use. # ... your business logic ...
redirect_to contact_success_path endendThat’s it — the form is now protected. For real deployments, move the API key out of the source code (see the comment) and consider explicit failover handling — see Failover Behavior for the reasoning and a code template.
Refactor: extract to a before_action
Section titled “Refactor: extract to a before_action”If you protect more than one action, the most idiomatic Rails approach is a before_action callback declared once in ApplicationController (or a shared concern) and applied to whichever actions need it.
Configure the API key
Section titled “Configure the API key”Use Rails encrypted credentials so the key never lands in source control:
rails credentials:edittrustcaptcha: api_key: <your_api_key>Add the before_action
Section titled “Add the before_action”require 'trustcaptcha/trust_captcha'
class ApplicationController < ActionController::Base private
def verify_trust_captcha token = params['tc-verification-token'].to_s
begin trust_captcha = TrustCaptcha.new(Rails.application.credentials.trustcaptcha[:api_key]) result = trust_captcha.get_verification_result(token) rescue StandardError return head :bad_request end
head :bad_request unless result.verification_passed && result.score <= 0.5 endendApply the callback to your actions
Section titled “Apply the callback to your actions”class ContactsController < ApplicationController before_action :verify_trust_captcha, only: :create
def create # CAPTCHA already verified — params are safe to use. redirect_to contact_success_path endendAdding before_action :verify_trust_captcha, only: [:create, :update] to any controller now opts the listed actions into CAPTCHA verification.
CSRF. Rails’ built-in CSRF protection (protect_from_forgery) and TrustCaptcha are independent layers — both should stay enabled. The CAPTCHA token does not replace the CSRF token.
Strong Params. The token field is read from params directly (not via the strong-params hash), so it doesn’t need to be permitted in your *_params method.
Configured SDK options. For custom timeouts, proxy, or a custom API host, pass them to the constructor: TrustCaptcha.new(api_key, api_host: ..., proxy: ...). Build the SDK once in an initializer (e.g. config/initializers/trustcaptcha.rb) and reuse it across requests. See the Ruby Guide for the full constructor options.
Next steps
Section titled “Next steps”Once you have wired TrustCaptcha into your Rails application, you can use TrustCaptcha to its full extent. However, we still recommend the following additional technical and organizational measures:
Security rules: You can find many security settings for your CAPTCHA in the CAPTCHA settings. These include, for example, authorized websites, CAPTCHA bypass for specific IP addresses, bypass keys, IP based blocking, geoblocking, individual difficulty and duration of the CAPTCHA, and much more. Learn more about the security rules.
Privacy & GDPR compliance: Include a passage in your privacy policy that refers to the use of TrustCaptcha. We also recommend that you enter into a data processing agreement with us to stay GDPR-compliant. Learn more about data protection.
Accessibility & UX: Customize TrustCaptcha to your website so that your website is as accessible as possible and offers the best possible user experience. More about accessibility.
Failover behavior: Decide how your backend should behave when our service is temporarily unreachable. This is particularly important for high-availability flows where blocking real users during an outage is worse than letting through a small amount of unverified traffic. Learn more about failover behavior.
Testing: If you use automated testing, make sure that the CAPTCHA does not block it. Learn more about testing.