reCAPTCHA
How to solve reCAPTCHA v2 in Node.js with Puppeteer
Node.js 18 and later ship a global fetch, so a reCAPTCHA v2 client needs no HTTP package at all. This guide pairs that client with Puppeteer, which is where most Node scripts meet the checkbox.
How the pieces fit together
Puppeteer drives the page; GateSolver produces the token. The browser never has to click the checkbox or look at image tiles. Instead, your script reads the site key from the page, asks the API for an answer, writes the answer into the hidden response field and continues the flow as if a person had passed the widget.
That split matters for reliability. A headless browser that tries to click through image challenges gets slower and more suspicious with every round, while a token task returns a finished answer, typically under 9 seconds. You only pay for tasks that come back solved.
Set up the project
Create a folder, run npm init -y, set "type": "module" in package.json so top level await works, and install Puppeteer with npm install puppeteer. Check your runtime with node --version; anything from 18 up has fetch and AbortSignal.timeout available globally.
Write a small API client
The client is one module with two exported functions. gateCall handles the JSON round trip and turns API errors into thrown errors; getV2Token creates the task and waits for it with an async loop built on setTimeout from node:timers/promises.
// gate.js
import { setTimeout as pause } from 'node:timers/promises';
const ENDPOINT = 'https://gatesolver.com';
const CLIENT_KEY = process.env.GATE_KEY ?? 'YOUR_API_KEY';
async function gateCall(method, extra) {
const res = await fetch(`${ENDPOINT}/${method}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json; charset=utf-8', Accept: 'application/json' },
body: JSON.stringify({ clientKey: CLIENT_KEY, ...extra }),
signal: AbortSignal.timeout(30_000),
});
const json = await res.json();
if (json.errorId) throw new Error(`${json.errorCode} ${json.errorDescription ?? ''}`.trim());
return json;
}
export async function getV2Token(pageUrl, siteKey) {
const { taskId } = await gateCall('createTask', {
task: { type: 'ReCaptchaV2TaskProxyLess', websiteURL: pageUrl, websiteKey: siteKey },
});
for (let round = 0; round < 42; round++) {
await pause(3000);
const r = await gateCall('getTaskResult', { taskId });
if (r.status === 'ready') return r.solution.gRecaptchaResponse;
if (r.status === 'failed') throw new Error('Task failed (free of charge)');
}
throw new Error('Gave up waiting for the token');
}
Forty two rounds of three seconds is a little over two minutes, which lines up with the 120 second window after which an unsolved task is closed as failed. Reading the key from GATE_KEY keeps it out of your repository.
Read the site key inside Puppeteer
Once the page has loaded, the key is in the DOM. Ask the page for it rather than parsing HTML yourself, because many sites add the widget after scripts run.
const siteKey = await page.$eval('[data-sitekey]', el => el.getAttribute('data-sitekey'));
If no element carries the attribute, the widget was rendered with grecaptcha.render(). The anchor iframe's src then contains the key as the k parameter: new URL(frame.url()).searchParams.get('k') on the frame whose URL includes /recaptcha/api2/anchor.
Inject the token and submit
The widget keeps its answer in a hidden textarea with the id g-recaptcha-response. Fill it, and if the site registered a callback, call that too, since some forms only enable their submit button from inside the callback.
// run.js
import { launch } from 'puppeteer';
import { getV2Token } from './gate.js';
const target = 'https://example.com/signup-test';
const browser = await launch({ headless: true });
const page = await browser.newPage();
await page.goto(target, { waitUntil: 'networkidle2' });
const key = await page.$eval('[data-sitekey]', el => el.dataset.sitekey);
const answer = await getV2Token(target, key);
await page.evaluate((value) => {
const box = document.querySelector('#g-recaptcha-response');
box.value = value;
const holder = document.querySelector('[data-callback]');
const fnName = holder?.getAttribute('data-callback');
if (fnName && typeof window[fnName] === 'function') window[fnName](value);
}, answer);
await Promise.all([
page.waitForNavigation({ waitUntil: 'domcontentloaded' }),
page.click('form [type=submit]'),
]);
console.log('landed on', page.url());
await browser.close();
The Promise.all pattern starts waiting for navigation before the click, so a fast redirect is never missed. If the form submits through XHR instead of a page load, wait for the response with page.waitForResponse() and a URL filter instead.
Common mistakes in Node scripts
- Solving too early. Tokens live about two minutes. Solve after the form is filled, right before the click, not when the page first opens.
- Several textareas. Pages with more than one widget have
g-recaptcha-response,g-recaptcha-response-1and so on. Match the textarea inside the same form as your submit button. - Swallowed errors. An unhandled rejection in
getV2Tokenwill end the process. Wrap the call and retry only onERROR_CAPTCHA_UNSOLVABLEorERROR_SERVICE_UNAVAILABLE, both of which are free. - Missing callback. If the button stays disabled after injection, the site relies on a callback that is not declared in
data-callback. The guide on how to find the reCAPTCHA callback function shows how to locate it.
Debugging a flow that does nothing
When the script runs without errors but the site never accepts the submit, slow it down and watch. Launch with headless: false and slowMo: 50 so you can see each action, and attach a listener with page.on('console', m => console.log(m.text())) to read the page's own log lines. Many sites print a warning when the response field is empty at submit time, which tells you the injection ran against the wrong textarea.
Next, open the network panel of the visible browser and find the request the form sends. Check that it carries the token you injected, under the name the server expects. Some front ends copy the value into a JSON body as captcha or recaptchaToken instead of sending the textarea as is; in that case filling the textarea is not enough and the callback is what moves the value into the request.
Finally, compare timings. Print a timestamp when the task is created, when the token arrives and when the click happens. If the gap between arrival and click is long because other steps run in between, reorder the script so the solve is the last thing before the submit.
Scaling up
Because there is no cap on concurrent tasks, a batch of pages can each solve in parallel with Promise.all. The limit to respect is the request rate: 600 calls a minute per key, which polling at three seconds leaves a lot of room for. As a rough guide, each pending task makes about twenty status calls a minute, so even thirty solves running side by side stay inside the limit. Opening a fresh browser context per job, rather than a fresh browser, keeps memory use down when you run many pages at once. For a deeper look at running Puppeteer against protected pages, see the Puppeteer integration guide; the reCAPTCHA v2 page lists every field the task accepts.
Common questions
Do I need axios or node-fetch for this client?
No. Node.js 18 and later include fetch and AbortSignal.timeout, so the client runs with no HTTP dependency.
Can I use the token in a page opened by Playwright instead?
Yes. The token is not tied to Puppeteer; filling the same textarea with page.evaluate in Playwright works the same way.
Why does the submit button stay greyed out after injection?
The page probably enables it from a reCAPTCHA callback. Call that function with the token after filling the textarea.
Is the token tied to the Puppeteer browser?
Not for a proxyless task. If the site checks that the solve and the submit share an IP, use ReCaptchaV2Task with the same proxy your browser uses.
How do I keep my API key out of the code?
Read it from an environment variable such as GATE_KEY, as the example does, and set it in your shell or process manager.
Keep reading
- PuppeteerOne Puppeteer client for three jobs: the reCAPTCHA v2 checkbox, v3 scores tied to an action, and text image CAPTCHAs.
- Find the reCAPTCHA callback functionFrom data-callback to a walk through the ___grecaptcha_cfg clients object: how to reach the function that consumes the token.
- reCAPTCHA v2 solver$0.56 per 1,000 tasks, answers under 9 seconds.
- PuppeteerThe Node.js library that drives Chrome and Chromium over the DevTools Protocol, popular for scraping, screenshots and PDFs.