Let’s see if I remember the exact steps I took to add reCAPTCHA v3 to my rails application…

Local Development

Gemfile

Add ‘recaptcha’ gem

gem "recaptcha"

Run bundle install

bundle install

.env

I am setting my environment variables using .env.

Oh yeah, if you haven’t done so already make sure to get your key and secret from Google before continuing.

development:
  ...
  RECAPTCHA_SITE_KEY: 6L**************************************Bc-
  RECAPTCHA_SECRET_KEY: 6L***********************************3hE
  ...
production:
  ...
  RECAPTCHA_SITE_KEY: 6L**************************************Bc-
  RECAPTCHA_SECRET_KEY: 6L**************************************Bc-
  ...

Don’t forget the possible dash (-) at the end of the site key!

View

Add the following line to your devise sign up form. In my case it was in app/views/users/registrations/new.html.erb

<%= form_for(resource, as: resource_name, url: registration_path(resource_name),  html: { class: "form-horizontal"}) do |f| %>

  <%= recaptcha_v3(action: 'registration') %>
  ...

Controller

Add the following code to your <Model>::RegistrationController

class Users::RegistrationsController < Devise::RegistrationsController

    def create
       recaptcha_valid = verify_recaptcha(model: @user, action: 'registration')
      if recaptcha_valid
        super
      else
        flash.now[:error] = "Recaptcha Human Check Failed"
        redirect_to new_user_registration_path
      end
    end
...

Heroku

Config Vars

If you are hosting your app on heroku – make sure to add the key and secret to your heroku config vars.

Heroku Config Vars Screenshot

One you have clicked on Reveal Config Vars you can enter your key and secret values.

Screenshot of heroku config vars input boxes.
Heroku Config Vars

I ran into a problem when I did this step. I had not realized that I did not copy the full key. I was missing a dash (-) at the end of my key! So double check your key and secret.

Sign Ups are now Protected by Google reCAPTCHA v3

I hope I didn’t forget any of the steps. Please let me know if I did. I would hate to give out bad information.

As always, feel free to reach out to me if you have any coding question or post on newbstack.com.