Solve Cloudflare Turnstile in Playwright (Node.js) Automatically

Playwright drives a real Chromium, Firefox or WebKit browser, but that alone does not get you past Cloudflare Turnstile. Automated browsers are easy to fingerprint, and the "Verify you are human" checkbox will often spin forever or fail in a headless session.

The reliable approach is to let a solving service produce the Turnstile token and have Playwright place it into the page. This guide walks through it with Node.js and the SolverCF API.

Only automate sites you own or have permission to test, and follow each site's terms of service.

How Turnstile hands over its token

When Turnstile succeeds, it does two things:

  1. Writes the token into a hidden input named cf-turnstile-response inside the form.
  2. Calls the page's callback function (if the site registered one) with the token.

To bypass the widget you reproduce both: fill the hidden input and, when present, call the callback. Then submit the form as usual.

Setup

Shell
npm init -y
npm install playwright
npx playwright install chromium

Node.js 18+ is required for the built-in fetch. Grab your client key from the SolverCF dashboard — new accounts include 100 free solves.

Step 1: Read the site key from the page

JavaScript
async function getSiteKey(page) {
  await page.waitForSelector('[data-sitekey], .cf-turnstile, iframe[src*="challenges.cloudflare.com"]', { timeout: 15000 });

  return page.evaluate(() => {
    const el = document.querySelector('[data-sitekey]');
    if (el) return el.getAttribute('data-sitekey');

    // explicit rendering: the key is in the iframe URL (…/0x4AAAA…/…)
    const frame = document.querySelector('iframe[src*="challenges.cloudflare.com"]');
    const match = frame?.src.match(/\/(0x4[\w-]+)\//);
    return match ? match[1] : null;
  });
}

Step 2: Solve the token with SolverCF

JavaScript
const API = 'https://solvercf.com/token/extension';
const CLIENT_KEY = process.env.SOLVERCF_KEY;

async function call(method, body) {
  const res = await fetch(`${API}/${method}`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ clientKey: CLIENT_KEY, ...body }),
  });
  const json = await res.json();
  if (json.errorId !== 0) throw new Error(`${method}: ${json.errorDescription || json.errorCode}`);
  return json;
}

async function solveTurnstile(websiteUrl, websiteKey, timeoutMs = 90000) {
  const { taskId } = await call('createTask', {
    task: { type: 'TurnstileTask', websiteUrl, websiteKey },
  });

  const deadline = Date.now() + timeoutMs;
  while (Date.now() < deadline) {
    await new Promise(r => setTimeout(r, 1500));
    const result = await call('getTaskResult', { taskId });
    if (result.status === 'ready') return result.solution;   // { token, userAgent }
    if (['failed', 'expired'].includes(result.status)) throw new Error(`task ${result.status}`);
  }
  throw new Error('Turnstile not solved in time');
}

Step 3: Inject the token and submit

JavaScript
async function injectToken(page, token) {
  await page.evaluate((token) => {
    // 1. fill every Turnstile response field (create one if the form has none yet)
    let inputs = document.querySelectorAll('[name="cf-turnstile-response"]');
    if (inputs.length === 0) {
      const form = document.querySelector('form');
      const input = document.createElement('input');
      input.type = 'hidden';
      input.name = 'cf-turnstile-response';
      form?.appendChild(input);
      inputs = [input];
    }
    inputs.forEach(i => { i.value = token; });

    // 2. call the site's callback if it declared one: <div class="cf-turnstile" data-callback="onSolved">
    const cbName = document.querySelector('[data-callback]')?.getAttribute('data-callback');
    if (cbName && typeof window[cbName] === 'function') window[cbName](token);
  }, token);
}

Putting it together

Launch the browser with the User-Agent returned by the solver, so the token and the browser that submits it look like the same client. Because the token is only issued after solving, the simplest flow is: open the page once to read the site key, solve, then open a context with the matching User-Agent.

JavaScript
const { chromium } = require('playwright');

(async () => {
  const url = 'https://example.com/login';
  const browser = await chromium.launch({ headless: true });

  // 1. read the site key
  const probe = await browser.newPage();
  await probe.goto(url, { waitUntil: 'domcontentloaded' });
  const siteKey = await getSiteKey(probe);
  await probe.close();
  if (!siteKey) throw new Error('No Turnstile widget found');

  // 2. solve
  const solution = await solveTurnstile(url, siteKey);

  // 3. use a context with the solver's User-Agent, inject and submit
  const context = await browser.newContext({ userAgent: solution.userAgent });
  const page = await context.newPage();
  await page.goto(url, { waitUntil: 'domcontentloaded' });

  await page.fill('input[name="email"]', '[email protected]');
  await page.fill('input[name="password"]', 'your-password');
  await injectToken(page, solution.token);
  await page.click('button[type="submit"]');

  await page.waitForLoadState('networkidle');
  console.log('Landed on:', page.url());
  await browser.close();
})();

Adjust the form selectors to the site you automate.

Tips for stable runs

  • Solve right before submitting. Tokens are single-use and expire after roughly five minutes.
  • Keep the User-Agent consistent between the solve and the browser context.
  • Check what the site really sends. Some single-page apps post the token as JSON or in a header. Record one manual submit in DevTools → Network and mirror it.
  • Full-page "Just a moment..." screens are different. That is a Cloudflare Challenge; you need a cf_clearance cookie. Solve it with cloudflareTaskType: "cookie" (see the cf_clearance guide) and add the cookie with context.addCookies(), using the same proxy and User-Agent.
  • Need speed? The token pool can return pre-solved tokens for popular site keys instantly.

Next steps

The complete parameter reference, including optional proxy and userAgent inputs, is in the Cloudflare Turnstile docs. Prefer Python? Read Solve Cloudflare Turnstile with Selenium or the plain requests guide.