Reducing Spam on Your Rails 7 Contact Form with Google reCAPTCHA

September 2, 2024 Coding

Spam is an inevitable nuisance, especially when your web application includes a contact form that’s publicly accessible. Fortunately, Google reCAPTCHA offers a simple and effective way to prevent bots from flooding your inbox with spammy submissions. In this post, I'll walk you through how to implement Google reCAPTCHA in a Rails 7 application using the Simple Form gem.

Why Use reCAPTCHA?

Google reCAPTCHA helps you verify that a user is human and not a bot. It provides different versions, such as reCAPTCHA v2 (with a "I'm not a robot" checkbox) and reCAPTCHA v3 (which is invisible to the user). The choice depends on your preference for user experience.

Step 1: Set Up Your reCAPTCHA Account

First, head over to Google reCAPTCHA and sign in with your Google account. Register your site by choosing reCAPTCHA v2 or v3, depending on your preference. You’ll be provided with a site key and a secret key—keep these handy, as you’ll need them soon.

Step 2: Install the recaptcha Gem

To integrate reCAPTCHA with your Rails application, you’ll need to install the recaptcha gem. Add it to your Gemfile:

gem 'recaptcha', require: 'recaptcha/rails'

Step 3: Store Your reCAPTCHA Keys Securely

It's essential to keep your reCAPTCHA keys out of your source code. Here’s how to store them securely in your .env file:

  1. Add the keys to your .env file in the root directory of your Rails application:

    RECAPTCHASITEKEY=your-site-key
    RECAPTCHASECRETKEY=your-secret-key

  2. Ensure you have the dotenv-rails gem installed, which loads these environment variables:

    gem 'dotenv-rails', groups: [:development, :test]

  3. Run bundle install to install the gem.

Step 4: Configure reCAPTCHA in Rails

Next, create an initializer to configure reCAPTCHA with your keys. This file will be responsible for linking your Rails app to Google reCAPTCHA:

  1. Create or update config/initializers/recaptcha.rb:

    Recaptcha.configure do |config|
    config.sitekey = ENV['RECAPTCHASITEKEY']
    config.secret
    key = ENV['RECAPTCHASECRETKEY']
    end

Step 5: Update Your Simple Form View

Now that reCAPTCHA is configured, you need to include it in your contact form. If you're using the Simple Form gem, here's how to do it:

  1. For reCAPTCHA v2, add the reCAPTCHA widget to your form:

    <%= simpleformfor @contact, url: contactpath do |f| %>
    <!-- Your form fields here -->
    <%= recaptcha
    tags %>
    <%= f.button :submit, 'Submit' %>
    <% end %>

  2. For reCAPTCHA v3, which doesn’t display a widget, you’ll still need to include the recaptcha_v3 helper:

    <%= simpleformfor @contact, url: contactpath do |f| %>
    <!-- Your form fields here -->
    <%= recaptcha
    v3(action: 'contact_form') %>
    <%= f.button :submit, 'Submit' %>
    <% end %>

Step 6: Verify reCAPTCHA in Your Controller

Before you process the form submission, it’s crucial to verify the reCAPTCHA response. Here’s how to implement this check in your controller:

  1. In your ContactsController, verify the reCAPTCHA response:

    class ContactsController < ApplicationController
    def create
    if verify_recaptcha
    # Process form submission
    else
    flash[:alert] = "reCAPTCHA verification failed, please try again."
    render :new
    end
    end
    end

  2. For reCAPTCHA v3, specify the action:

    if verifyrecaptcha(action: 'contactform')
    # Process form submission
    else
    flash[:alert] = "reCAPTCHA verification failed, please try again."
    render :new
    end

Step 7: Test Your Implementation

Before deploying your changes, test the contact form locally to ensure everything is working correctly. Check that the CAPTCHA appears (for v2), that the form submits successfully, and that spam submissions are blocked.

Conclusion

Implementing Google reCAPTCHA is a straightforward way to protect your Rails 7 application from spam. By following these steps, you’ll not only enhance the security of your contact form but also ensure a smoother user experience.

If you have any questions or run into issues, feel free to leave a comment below. Happy coding!

Comments (0)

Leave a comment