Cloudflare
How to solve Cloudflare Turnstile in Node.js with Playwright
Modern sites usually create the Turnstile widget from JavaScript and receive the token in a callback. With Playwright you can see those options as the page sets them and answer the callback yourself.
The approach
On a single page app, the Turnstile widget is rarely a static div. The app calls turnstile.render(container, options) with the site key, an optional action and cData, and a callback that receives the token. That callback is how the token reaches the app's state and, from there, its API request. Writing a value into a hidden input does not help if the app never reads that input.
So this guide does three things inside Playwright: it records the options every time the page calls turnstile.render, it solves a task with exactly those values, and it calls the recorded callback with the token. The page then behaves as if the widget had passed on its own.
A small solver module
The module below is a class so the API key and polling interval live in one place. It uses the global fetch of Node 18+ and returns the full solution object.
// turnstile-solver.mjs
export class TurnstileSolver {
#key;
#pollMs;
constructor(key, pollMs = 3000) {
this.#key = key;
this.#pollMs = pollMs;
}
async #call(method, body) {
const res = await fetch('https://gatesolver.com/' + method, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'User-Agent': 'turnstile-runner/1.0' },
body: JSON.stringify({ ...body, clientKey: this.#key }),
});
const data = await res.json();
if (data.errorId) {
const err = new Error(`GateSolver ${data.errorCode}`);
err.code = data.errorCode;
throw err;
}
return data;
}
async solve({ url, sitekey, action, cdata }) {
const metadata = Object.fromEntries(Object.entries({ action, cdata }).filter(([, v]) => v));
const task = { type: 'AntiTurnstileTaskProxyLess', websiteURL: url, websiteKey: sitekey };
if (Object.keys(metadata).length) task.metadata = metadata;
const created = await this.#call('createTask', { task });
for (let elapsed = 0; elapsed <= 123_000; elapsed += this.#pollMs) {
await new Promise((resume) => setTimeout(resume, this.#pollMs));
const out = await this.#call('getTaskResult', { taskId: created.taskId });
if (out.status === 'ready') return out.solution;
if (out.status === 'failed') throw Object.assign(new Error('Turnstile task failed'), { code: 'FAILED' });
}
throw Object.assign(new Error('Turnstile task timed out'), { code: 'TIMEOUT' });
}
}
Private fields (#key) keep the key out of logs that print the object. Errors carry the API's code on err.code, which makes the retry decision a simple switch later.
Record turnstile.render in the page
The Turnstile script defines window.turnstile when it loads. An init script can watch for it and wrap render, storing each widget's options on window where Playwright can read them.
// capture.js (passed to context.addInitScript)
window.__tsWidgets = [];
const hook = setInterval(() => {
const ts = window.turnstile;
if (!ts || typeof ts.render !== 'function' || ts.render.__hooked) return;
const original = ts.render.bind(ts);
const hooked = (el, opts = {}) => {
window.__tsWidgets.push({
sitekey: opts.sitekey, action: opts.action, cdata: opts.cData,
done: opts.callback,
});
return original(el, opts);
};
hooked.__hooked = true;
ts.render = hooked;
}, 15);
setTimeout(() => clearInterval(hook), 45_000);
Note the property names: the render option is cData with a capital D, while the task's metadata field is cdata. The script calls the original render so the page keeps working, which also means the real widget will still run its own check in your browser; your token simply arrives first and through the same callback.
Put it together in Playwright
// main.mjs
import { chromium as chrome } from 'playwright';
import { TurnstileSolver } from './turnstile-solver.mjs';
const formUrl = 'https://app.example.net/signup';
const solver = new TurnstileSolver(process.env.GATE_KEY);
const browser = await chrome.launch({ headless: true });
const ctx = await browser.newContext();
await ctx.addInitScript({ path: './capture.js' });
const signup = await ctx.newPage();
await signup.goto(formUrl);
await signup.waitForFunction(() => window.__tsWidgets.length > 0, null, { timeout: 20_000 });
const meta = await signup.evaluate(() => {
const w = window.__tsWidgets[0];
return { sitekey: w.sitekey, action: w.action, cdata: w.cdata };
});
await signup.fill('#email', 'qa+signup@example.net');
const { token } = await solver.solve({ url: formUrl, ...meta });
await signup.evaluate((t) => {
const w = window.__tsWidgets[0];
document.querySelectorAll('input[name="cf-turnstile-response"]').forEach((i) => (i.value = t));
if (typeof w.done === 'function') w.done(t);
}, token);
await signup.click('button[type="submit"]');
await browser.close();
Functions cannot cross from the page to Node, which is why the callback stays in the page and only the plain values (site key, action, cData) are returned by evaluate. The second evaluate runs in the page, where the stored callback is still a live function. Filling every cf-turnstile-response input as well covers forms that read the field at submit time instead of using the callback.
Why the form is filled before the solve
The order of steps in the example is deliberate. Typing into fields, waiting for validation and clicking through a multi step form can take several seconds, and every second spent after the token arrives is a second taken from its short lifetime. Filling first and solving last keeps the gap between token and submit as small as possible. It also means a validation error on your inputs shows up before you have paid for a token, rather than after.
The same thinking applies to retries. If the submit fails for a reason unrelated to Turnstile, such as a duplicate email, fix the input and start a new solve; the first token has been consumed by the site's verification even though the form was refused.
Debugging the capture hook
When waitForFunction times out, the hook never saw a render call. Open the page with chromium.launch({ headless: false }) and type window.turnstile in the console. If it is undefined, the widget lives inside an iframe from another origin, and you should attach the script to that frame's document instead. If it exists but __tsWidgets is empty, the page rendered implicitly from a static div, and the attribute based approach below applies. Logging inside the hook with console.log and listening with signup.on('console', ...) shows exactly when the page calls render.
Static widgets without render calls
If the page uses a plain <div class="cf-turnstile" data-sitekey="0x4...">, the script renders it automatically and your hook may never see a call. Read the values from the attributes instead: data-sitekey, data-action, data-cdata and data-callback (the name of a global function). Then fill the hidden input and, if a callback name is set, call window[name](token).
Retries and timing
Retry once or twice when err.code is ERROR_CAPTCHA_UNSOLVABLE or ERROR_SERVICE_UNAVAILABLE; those cost nothing. Do not retry ERROR_ZERO_BALANCE or ERROR_KEY_DENIED_ACCESS; surface them so someone can act. Fill the form before solving, as the example does, so the token is used within seconds. Cloudflare documents a token lifetime of 300 seconds and single use, so a retry of the submit always needs a new task.
Running many pages
Each Playwright context gets its own init script and its own __tsWidgets list, so parallel contexts do not interfere. The API has no cap on open tasks; keep the overall request rate under 600 per minute per key. A Turnstile task costs $0.84 per 1,000 solved and usually arrives under 3 seconds.
If nothing happens after the callback
- Check that the widget you used is the one inside the form you submit; pages with a login and a newsletter box may render two.
- Look at the request the form sends in the network panel and confirm the token is in it.
- If the whole page shows "Just a moment" before the form even appears, you are facing a challenge page, not the widget; see the Node.js challenge guide.
Field details are on the Turnstile task page, and the Playwright integration guide covers proxies and contexts in more depth.
Common questions
Why wrap turnstile.render instead of reading the DOM?
Apps that render the widget from JavaScript keep the action, cData and callback in the render options, not in attributes.
Is the option called cData or cdata?
The render option is cData; the task metadata field is cdata. The capture script maps one to the other.
Can I pass the callback function to Node.js?
No. Functions stay in the page. Keep the callback there and call it from a second page.evaluate with the token.
Does the real widget still run?
Yes, the hook calls the original render. Your token reaches the callback directly, usually before the widget would.
Will this work with Puppeteer?
Yes. Use page.evaluateOnNewDocument for the capture script; the rest is the same.
Keep reading
- PlaywrightPlaywright in Node.js and Python: read widget keys from the DOM or network, inject tokens, and add answers through route interception.
- Cloudflare Turnstile solver$0.84 per 1,000 tasks, answers under 3 seconds.
- Find Turnstile site key, action and cDataWhere Turnstile keeps its site key, action and cData: widget attributes, turnstile.render options and explicit rendering setups.
- CAPTCHA callback functionThe function a page runs once a widget passes, and why writing the token into a field sometimes changes nothing.