More languages
How to solve Cloudflare Turnstile in Ruby
This guide solves Turnstile from Ruby with Faraday, reads the form with Nokogiri and posts the token back, then shows a Net::HTTP version for scripts that cannot add gems. Each token is billed at $0.84 per 1,000.
What you need
Ruby 3.1 or newer, the faraday gem (version 2 or later, which includes JSON request and response middleware) and nokogiri for HTML parsing. Add them to your Gemfile or install them with gem install faraday nokogiri. You also need the URL of a page with a Turnstile widget that you are allowed to automate, and your API key in the GATESOLVER_KEY environment variable.
A Faraday connection for the API
Faraday's middleware takes care of encoding and decoding JSON, so the solver code deals only with hashes. The connection is built once and reused for every call.
require 'faraday'
module TurnstileGate
API = Faraday.new(url: 'https://gatesolver.com') do |f|
f.request :json
f.response :json
f.options.timeout = 25
f.options.open_timeout = 10
end
Failure = Class.new(StandardError)
def self.call(path, **payload)
body = API.post(path, payload.merge(clientKey: ENV.fetch('GATESOLVER_KEY'))).body
raise Failure, "#{path}: #{body['errorCode']}" unless body['errorId'].to_i.zero?
body
end
def self.token(page_url:, site_key:, action: nil, cdata: nil)
task = { type: 'AntiTurnstileTaskProxyLess', websiteURL: page_url, websiteKey: site_key }
meta = { action: action, cdata: cdata }.compact
task[:metadata] = meta unless meta.empty?
job = call('/createTask', task: task).fetch('taskId')
40.times do
sleep 3
res = call('/getTaskResult', taskId: job)
return res.dig('solution', 'token') if res['status'] == 'ready'
raise Failure, 'Turnstile task failed (free)' if res['status'] == 'failed'
end
raise Failure, 'no token after two minutes'
end
end
ENV.fetch raises at once if the key is missing, which is better than a confusing ERROR_KEY_DENIED_ACCESS later. Hash#compact removes nil values, so metadata appears only when the page sets an action or cdata.
Read the form with Nokogiri
Load the page through a second Faraday connection that keeps cookies, then parse it. Faraday does not store cookies by itself; the simplest approach for a single form is to carry the Set-Cookie values forward by hand.
require 'nokogiri'
site = Faraday.new(url: 'https://forms.example.org') do |f|
f.request :url_encoded
f.headers['User-Agent'] = 'Mozilla/5.0 (X11; Linux x86_64) form-check/1.0'
end
landing = site.get('/subscribe')
session = Array(landing.headers['set-cookie']).join(',').scan(/(?:^|,\s*)([^=;,\s]+=[^;,]*)/).flatten.join('; ')
html = Nokogiri::HTML(landing.body)
widget = html.at_css('.cf-turnstile[data-sitekey]') or abort 'no Turnstile widget found'
form = widget.ancestors('form').first || html.at_css('form')
extra = form.css('input[type=hidden][name]').to_h { |i| [i['name'], i['value'].to_s] }
extra.delete('cf-turnstile-response')
Faraday joins repeated headers with a comma, which is why the cookie line is split with a small regular expression. If your flow spans several pages, the faraday-cookie_jar middleware gem handles cookies properly; check its README for the current setup.
Solve and post the form
token = TurnstileGate.token(
page_url: 'https://forms.example.org/subscribe',
site_key: widget['data-sitekey'],
action: widget['data-action'],
cdata: widget['data-cdata']
)
reply = site.post(form['action'] || '/subscribe') do |req|
req.headers['Cookie'] = session
req.headers['Referer'] = 'https://forms.example.org/subscribe'
req.body = extra.merge('email' => 'qa+list@example.org', 'cf-turnstile-response' => token)
end
puts "#{reply.status} #{reply.body[/thank you[^<]*/i] || 'no confirmation text'}"
The url_encoded request middleware turns the hash into a normal form body. The last line prints the status and, if present, the confirmation text the site shows after a successful submit, which is a quick check that the token was accepted.
The same flow with Net::HTTP
In a one file script on a server without Bundler, the standard library is enough. Net::HTTP.post sends a body with headers in one call.
require 'net/http'
require 'json'
def gs_plain(route, data)
uri = URI("https://gatesolver.com/#{route}")
data = data.merge(clientKey: ENV.fetch('GATESOLVER_KEY'))
out = JSON.parse(Net::HTTP.post(uri, data.to_json, 'Content-Type' => 'application/json').body)
out['errorId'].to_i.zero? ? out : raise("#{route}: #{out['errorCode']}")
end
Swap TurnstileGate.call for gs_plain and the polling loop stays the same. For the form post, Net::HTTP.post_form does not accept custom headers, so use a Net::HTTP::Post object with set_form_data when you need to send the cookie.
Running inside Rails or Sidekiq
In a background job, solve inside perform, right before the post. Do not pass tokens through job arguments: a job that waits in the queue for more than a couple of minutes would carry an expired token. Let Sidekiq's retry handle network errors, but rescue TurnstileGate::Failure with a message containing ERROR_ZERO_BALANCE or ERROR_KEY_DENIED_ACCESS and stop retrying, since those need a person.
If the site rejects the submit
- Check that the cookie from the landing request went out with the post.
- Post to the form's real
actionURL, including any query string. - Send
data-actionanddata-cdatawhen the widget sets them. - Make sure the token was used once and within a few minutes.
A typical token returns under 3 seconds, and failed tasks are not charged. The Cloudflare Turnstile page lists all task fields, and the Ruby scraping guide covers sessions and parsing in more depth.
Error handling with Faraday
Faraday raises Faraday::TimeoutError and Faraday::ConnectionFailed for network problems. Those are worth a retry after a short pause. The raise_error response middleware can also turn 4xx and 5xx statuses into exceptions; leave it off for the API connection, since the API reports errors in the JSON body with errorId, which TurnstileGate.call already checks. For the site connection, turning it on makes failed submits loud instead of silent.
Inside TurnstileGate, retry once on ERROR_CAPTCHA_UNSOLVABLE or a failed status, both of which are free. Do not retry on ERROR_ZERO_BALANCE, ERROR_KEY_DENIED_ACCESS or ERROR_INVALID_TASK_DATA; the first needs a top-up, the second a correct key, and the third tells you which field is missing in its description.
Testing
Faraday ships a test adapter, Faraday::Adapter::Test, with stubs for each path. Stub /createTask to return a task id and /getTaskResult to return ready with a token, stub sleep in the test, and the whole flow runs offline in milliseconds. Keep one test for the failure path so a broken key is reported clearly.
Concurrency
A Faraday connection can be shared between threads with the default adapter. For many forms at once, use a small thread pool and keep under 600 API requests per minute on your key.
Choosing between Faraday and Net::HTTP
Use Faraday when the script is part of an application that already depends on it, or when you want middleware for logging, retries and instrumentation. Use Net::HTTP for single file tools, containers where every gem adds build time, and environments without Bundler. The API calls are identical JSON in both cases, so switching later is a matter of replacing one method. Whichever you choose, keep the API key in ENV and out of the code and the logs.
Common questions
Does Faraday 2 need a separate JSON gem?
No. JSON request and response middleware are included in Faraday 2. Older Faraday 1 used the faraday_middleware gem.
Why handle cookies by hand?
Faraday has no built in cookie store. For one form, forwarding Set-Cookie is enough; for longer flows, use a cookie jar middleware.
Can I pass the token to a Sidekiq job?
Better not. Tokens expire within minutes, so solve inside the job right before the post.
What does Hash#compact do in the task?
It drops nil values, so metadata is only sent when the widget sets an action or cdata.
Is Nokogiri required?
Only for reading the form. A regular expression can find data-sitekey on simple pages, but Nokogiri is more reliable.
Keep reading
- Cloudflare Turnstile solver$0.84 per 1,000 tasks, answers under 3 seconds.
- Web scraping with RubyRuby scraping two ways: a persistent Net::HTTP connection or HTTParty for fetching, Nokogiri for parsing, and retry blocks that read naturally.
- Find Turnstile site key, action and cDataWhere Turnstile keeps its site key, action and cData: widget attributes, turnstile.render options and explicit rendering setups.
- Cloudflare TurnstileThe Turnstile widget from Cloudflare, its managed, non-interactive and invisible modes, and the cf-turnstile-response token field.