Stop form spam in Rails

Updated

This guide adds Bot403 to a contact form in Rails. The browser solves a small proof of work. Then a controller checks the token with one call to the verify API, before it accepts the message. The visitor sees no puzzle, and the script sets no cookie. The free plan covers 5,000 checks a month and needs no card.

The example uses Rails 8.1.4.1 with Turbo (turbo-rails 2.0.23) on Ruby 4.0.9. Rails 8.1 needs Ruby 3.2 or newer. The check needs no gem: it uses Net::HTTP from the standard library. On 12 November 2026, the code on this page ran in a fresh rails new app against a local stand-in for the verify API that gives the documented answers, and in Chrome 157 with Turbo on. A good token went through. A reused token, a filled honeypot and a form with no token were refused. After a failed check, Turbo showed the form again with a message, and the second send went through. When the API did not answer, or took longer than 5 seconds, the form went through and Rails logged a warning.

Before you start

Sign in. Create a site. Copy its public key (pk_) and its secret key (sk_). Put the secret key in an environment variable, never in config/ or your repository.

Terminal
rails new contact && cd contact
export BOT403_SECRET_KEY=sk_live_YOUR_SECRET_KEY

You add or change these files:

Files
config/routes.rb
app/services/bot403_check.rb                 # the call to the verify API
app/controllers/concerns/bot403_protection.rb
app/controllers/messages_controller.rb
app/views/messages/new.html.erb
app/views/messages/thanks.html.erb
test/controllers/messages_controller_test.rb

1. The routes

config/routes.rb
Rails.application.routes.draw do
  resources :messages, only: %i[new create]
  get "thanks", to: "messages#thanks"
end

2. The form

The script tag protects every form on the page. Before the browser sends the form, the script adds a hidden _bot403 field with the token, and a hidden honeypot field (by default _website). The tag goes into the <head> through content_for :head. The layout of a new Rails 8.1 app already has <%= yield :head %>.

app/views/messages/new.html.erb
<% content_for :head do %>
  <script src="https://bot403.com/v1/bot403.js" data-bot403-key="pk_live_YOUR_PUBLIC_KEY" async></script>
<% end %>

<h1>Contact</h1>
<% if flash[:alert] %><p role="alert"><%= flash[:alert] %></p><% end %>

<%= form_with url: messages_path do |f| %>
  <%= f.label :email %>
  <%= f.email_field :email, required: true %>
  <%= f.label :message %>
  <%= f.text_area :message, required: true %>
  <%= f.submit "Send" %>
<% end %>
app/views/messages/thanks.html.erb
<p>Thanks. Your message is on its way.</p>

3. The check

Bot403Check.verify_form posts the form fields to https://bot403.com/api/v1/verify with your secret key and returns the answer. If Bot403 does not answer in 5 seconds, it raises Bot403Check::NoAnswer. A wrong secret key, a body over 64 KB or too many verify calls a minute raise a RuntimeError, so you see them and fix them.

app/services/bot403_check.rb
require "net/http"

# Checks the Bot403 token of a submitted form with one call to the verify API.
module Bot403Check
  URL = URI("https://bot403.com/api/v1/verify")
  NoAnswer = Class.new(StandardError) # a network error or a timeout

  # Posts the form fields. Bot403 reads the _bot403 field and the honeypot field.
  # Returns the answer as a Hash: {"ok" => true} or {"ok" => false, "reason" => "..."}.
  def self.verify_form(fields)
    req = Net::HTTP::Post.new(URL, "Authorization" => "Bearer #{ENV.fetch("BOT403_SECRET_KEY")}")
    req.set_form_data(fields)
    res = Net::HTTP.start(URL.host, URL.port, use_ssl: URL.scheme == "https", open_timeout: 5, read_timeout: 5) do |http|
      http.request(req)
    end
    # 200 is an answer, and so is 402 (reason "quota", only in a capped month).
    # 401 wrong key, 413 body over 64 KB, 429 too many calls a minute: fix these.
    raise "bot403 verify: HTTP #{res.code}" unless %w[200 402].include?(res.code)

    JSON.parse(res.body)
  rescue SystemCallError, IOError, Timeout::Error, SocketError, OpenSSL::SSL::SSLError => e
    raise NoAnswer, e.message
  end
end

Rails loads every folder in app/, so app/services needs no setup.

4. The concern and the controller

The concern picks the fields to send and reads the answer. The controller accepts the message only when bot403_passed? is true.

app/controllers/concerns/bot403_protection.rb
module Bot403Protection
  extend ActiveSupport::Concern

  private

  def bot403_passed?
    # The form body only: no query string, no route params.
    # Only top-level text fields: the token and the honeypot field are there.
    # The CSRF token stays on your server.
    fields = request.request_parameters
      .select { |name, value| value.is_a?(String) && name != request_forgery_protection_token.to_s }
    result = Bot403Check.verify_form(fields)
    # Refuse when ok is false, except for reason "quota".
    result["ok"] == true || result["reason"] == "quota"
  rescue Bot403Check::NoAnswer => e
    Rails.logger.warn("bot403 did not answer, letting the form through: #{e.message}")
    true
  end
end
app/controllers/messages_controller.rb
class MessagesController < ApplicationController
  include Bot403Protection

  def new
  end

  def create
    unless bot403_passed?
      flash.now[:alert] = "We could not send your message. Please try again."
      return render :new, status: :unprocessable_content
    end

    # A real visitor: send the email or store the message here.
    Rails.logger.info("message from #{params[:email]}")
    redirect_to thanks_path
  end

  def thanks
  end
end

A failed token is a normal answer, not an exception: ok is false and reason says why. The verify page lists every reason. The answer quota comes only in a capped month, and the example lets the form through then, so a capped month loses no message.

The trap: Turbo needs a 422 when the check fails

When the check fails, render the form with status: :unprocessable_content (HTTP 422). Turbo sends the form with fetch, and it shows an answer only when the answer is a redirect or an error status. In the test run with Turbo on, three ways to refuse the form gave three results:

What the controller does What the visitor sees
render :new (status 200) Nothing changes. The browser console shows Error: Form responses must redirect to another location
head :bad_request (400, empty body) Nothing changes, and no message
render :new, status: :unprocessable_content The form again, with the message "We could not send your message. Please try again."

After the 422, Turbo puts the new form in the page. The script finds it, gets a new token, and the next send goes through. Older code writes :unprocessable_entity. Rack 3.2, which Rails 8.1 uses, maps it to the same 422.

Turbo and the script work together without extra code. The script holds the submit until the token is ready, stops the other submit listeners, and then submits again. Turbo sends that second submit. In the test run, the POST had Turbo's X-Turbo-Request-Id header and the _bot403 field.

Keep the CSRF check, and leave its token out

Rails refuses a POST without a valid authenticity_token before your action runs. In the test run, a POST from curl without it got 422 with ActionController::InvalidAuthenticityToken. Keep this check. CSRF protection stops other sites from sending forms in the name of your visitor. Bot403 does not do that job. It stops scripts that send forms automatically. Never add skip_forgery_protection to make a spam test pass.

The concern removes the authenticity_token field before it posts the form, so the CSRF token stays on your server. In tests, Rails turns the CSRF check off (allow_forgery_protection = false in config/environments/test.rb), so the tests in "Test it" need no token.

Why request_parameters, and only top-level text fields

The concern sends request.request_parameters, not params. params also holds the URL's query string and the route parameters (controller, action). request_parameters holds only the body.

It also sends only the top-level text fields. With form_with model: @message, Rails names the fields message[email] and message[body], so they arrive as a nested hash. The script adds _bot403 and the honeypot field at the top level of the form, so Bot403 gets what it needs. In the test run, a form with nested fields sent only _bot403. An uploaded file arrives as an ActionDispatch::Http::UploadedFile, not a string, so the filter leaves files out too.

Keep the token out of the log

Add :_bot403 to the filtered parameters. The token is a long base64 string, and Rails logs every parameter that the filter does not match. The default list has :token, but that does not match _bot403, so the test run logged the whole token on every submit.

config/initializers/filter_parameter_logging.rb
Rails.application.config.filter_parameters += [:_bot403]

If you turn on the Content Security Policy

A new Rails app ships config/initializers/content_security_policy.rb with the policy commented out. If you turn it on, allow the script and its one request, as the script options page lists:

config/initializers/content_security_policy.rb
policy.script_src  :self, "https://bot403.com"
policy.connect_src :self, "https://bot403.com"
policy.worker_src  :self, :blob

Without worker_src :blob, the script solves the puzzle on the main thread. It still works, but the page may stall for a fraction of a second.

When the secret key is wrong

A wrong or missing secret key gets HTTP 401 from the verify API. Bot403Check raises, so Rails answers 500 and logs:

Log
RuntimeError (bot403 verify: HTTP 401):

If BOT403_SECRET_KEY is not set at all, ENV.fetch raises KeyError, which is also a 500. Every form on the site fails until you fix the key, so watch for these lines after a deploy. A 429 means too many verify calls for the site this minute: 100 on the free plan.

Test it

The tests swap Bot403Check for a module with a fixed answer, so they need no network and no key. They use stub_const from Active Support, because Minitest 6.1, which a new Rails 8.1 app gets, has no minitest/mock.

test/controllers/messages_controller_test.rb
require "test_helper"

class MessagesControllerTest < ActionDispatch::IntegrationTest
  # Replaces Bot403Check for one request: no network, no key.
  # Returns the fields that the controller sent to it.
  def post_form(answer, fields)
    sent = nil
    fake = Module.new do
      const_set(:NoAnswer, Bot403Check::NoAnswer)
      define_singleton_method(:verify_form) do |form|
        sent = form
        answer.is_a?(Exception) ? raise(answer) : answer
      end
    end
    stub_const(Object, :Bot403Check, fake) { post messages_path, params: fields }
    sent
  end

  test "a verified form goes through" do
    sent = post_form({ "ok" => true }, { email: "[email protected]", _bot403: "token" })
    assert_redirected_to thanks_path
    assert_equal "token", sent["_bot403"]
  end

  test "a failed token renders the form again with 422" do
    post_form({ "ok" => false, "reason" => "invalid" }, { email: "[email protected]" })
    assert_response :unprocessable_content
  end

  test "bot403 down lets the form through" do
    post_form(Bot403Check::NoAnswer.new("timeout"), { email: "[email protected]" })
    assert_redirected_to thanks_path
  end
end
Terminal
bin/rails test
# 3 runs, 8 assertions, 0 failures, 0 errors, 0 skips

Then run bin/rails server and open http://localhost:3000/messages/new. Send the form. The browser goes to /thanks, and the site in your dashboard shows one check. If you get a failure that you do not expect, read the troubleshooting page. It lists every reason and its fix. For a Python app, read Stop form spam in Django. All guides are in the guides index.

Stop spam, not customers.

The CAPTCHA your visitors never see.

Get started free