AWS WAF and other CAPTCHAs
How to solve image text CAPTCHAs in Node.js
The hard part of an image CAPTCHA in a browser script is getting clean image bytes out of the page. This guide compares three ways to do it in Puppeteer and then reads the text for $0.28 per 1,000.
Why the image source matters
An image CAPTCHA belongs to the session that loaded it. In a browser script that session is the browser itself, so the safest bytes are the ones the browser already shows. Downloading the image URL again from Node.js with a plain HTTP client usually fails: it lacks the browser's cookies, and even with them the server may draw a new picture on every request. The three methods below all take the image from inside the page.
| Method | Works when | Watch out for |
|---|---|---|
| Element screenshot | Always, for any visible element | Device scale and overlapping elements |
| Canvas toDataURL | Image is same origin or CORS enabled | A tainted canvas throws an error |
| In page fetch of src | Image URL returns the same picture twice | Many CAPTCHA endpoints redraw on each request |
Set up Puppeteer
Node.js 18 or newer gives you fetch for the API calls; Puppeteer downloads a matching browser when you install it. The examples are ES modules.
npm install puppeteer
export CAPTCHA_GATE_KEY=YOUR_API_KEY
Method one: screenshot the element
Puppeteer can screenshot a single element and return the result as base64 directly. This is the most dependable method because it captures exactly what is drawn, whatever the image's origin or format.
export async function shotAsBase64(page, selector) {
const el = await page.waitForSelector(selector, { visible: true });
await page.waitForFunction(
(s) => { const n = document.querySelector(s); return !n.complete || n.naturalWidth > 0; },
{}, selector,
);
return el.screenshot({ encoding: 'base64', type: 'png' });
}
The wait checks that an img has finished loading before the capture, so you do not send a blank frame. Keep the default device scale factor of 1 while capturing; a high scale enlarges the picture, which is harmless, but cropping by other elements such as a cookie banner is not, so close overlays first.
Method two: draw it on a canvas
If the image comes from the same origin as the page, the browser can redraw it on a canvas and hand back a PNG data URL at its natural size. This avoids any screen scaling and gives the original pixels.
export async function canvasAsBase64(page, selector) {
const dataUrl = await page.$eval(selector, (img) => {
const board = document.createElement('canvas');
board.width = img.naturalWidth;
board.height = img.naturalHeight;
board.getContext('2d').drawImage(img, 0, 0);
return board.toDataURL('image/png');
});
return dataUrl.slice(dataUrl.indexOf(',') + 1);
}
A cross origin image without CORS headers taints the canvas, and toDataURL then throws a security error. Catch it and fall back to the screenshot method. The last line removes the data:image/png;base64, prefix, which the task does not accept.
Method three: fetch inside the page
A fetch run inside the page carries the page's cookies. It is useful when the CAPTCHA URL returns a stable image for the session, for example when it contains a fixed id. Test it first: load the URL twice in a tab and see whether the text changes.
export async function fetchAsBase64(page, selector) {
return page.$eval(selector, async (img) => {
const blob = await (await fetch(img.src, { credentials: 'include' })).blob();
const text = await new Promise((ok) => {
const fr = new FileReader();
fr.onload = () => ok(fr.result);
fr.readAsDataURL(blob);
});
return text.split(',')[1];
});
}
Read the text through the API
The task is ImageToTextTask with the base64 in body. Image answers are fast, so the loop polls once a second.
import { setTimeout as delay } from 'node:timers/promises';
const OCR_HOST = 'https://gatesolver.com';
const ocrKey = process.env.CAPTCHA_GATE_KEY ?? 'YOUR_API_KEY';
async function ocrCall(path, data) {
const payload = JSON.stringify({ clientKey: ocrKey, ...data });
const r = await fetch(`${OCR_HOST}/${path}`, { method: 'POST', body: payload, headers: { 'Content-Type': 'application/json' } });
const json = await r.json();
if (json.errorId) throw Object.assign(new Error(json.errorCode), { code: json.errorCode });
return json;
}
export async function imageText(base64, options = {}) {
const { taskId } = await ocrCall('createTask', {
task: { type: 'ImageToTextTask', body: base64, ...options },
});
for (let n = 0; n < 60; n += 1) {
await delay(1000);
const state = await ocrCall('getTaskResult', { taskId });
if (state.status === 'ready') return state.solution.text;
if (state.status === 'failed') throw new Error(`image task ${taskId} failed (free)`);
}
throw new Error(`image task ${taskId} took too long`);
}
Pass { module: 'common' } or { score: 0.9 } as options when a site needs them. Errors carry their errorCode on the code property, so a caller can retry ERROR_CAPTCHA_UNSOLVABLE and stop on ERROR_ZERO_BALANCE.
Type the answer and submit
const { default: puppeteer } = await import('puppeteer');
const browser = await puppeteer.launch();
const [tab] = await browser.pages();
await tab.goto('https://example.com/tracking', { waitUntil: 'networkidle2' });
let b64;
try { b64 = await canvasAsBase64(tab, '#captchaImg'); }
catch { b64 = await shotAsBase64(tab, '#captchaImg'); }
const code = await imageText(b64);
await tab.type('#parcel', 'ZX81-4471');
await tab.type('#captchaInput', code, { delay: 40 });
await Promise.all([tab.waitForNavigation(), tab.click('button[type=submit]')]);
console.log(tab.url());
await browser.close();
Typing with a small delay looks like normal input and lets any key listeners on the field run. Enter the text with its case unchanged, since many image CAPTCHAs are case sensitive.
Handle a refreshed image
Some forms redraw the image after a wrong answer or after a timeout. Treat each picture as a new task: read it again with the same method, solve, and type. A retry limit of two or three keeps a broken page from looping. Each unsolvable task is free, but a solved task is charged even if the form later rejects the text, so fix the capture before adding retries.
Many forms at once
A browser tab costs memory, but the API side has no limit on concurrent tasks, so the practical ceiling is your machine. Open a few tabs, give each its own page object, and let each tab run the capture, solve and type cycle independently with Promise.all. Five tabs polling once a second use about 300 API requests a minute, which leaves headroom under the 600 per minute limit for one key. If you need more parallel work than that, poll a little less often (every 1.5 seconds is fine for most image tasks) or split the job across two processes that share the key carefully. Keep each tab's session separate: two tabs sharing one form session can overwrite each other's CAPTCHA image on the server side.
Common capture problems
- Blank or grey image: captured before loading finished. Keep the load check from method one.
- Half the characters missing: the element was partly off screen or covered. Scroll it into view and close banners.
- SecurityError from toDataURL: cross origin image. Use the screenshot method.
- Answer fits a different picture: the in page fetch got a redrawn image. Use the canvas or screenshot method.
See the Puppeteer integration guide for token CAPTCHAs in the same browser, and the Python version for HTTP only forms. The current price is on the image to text page.
Common questions
Which capture method should I try first?
The canvas method gives original pixels when the image is same origin. Fall back to the element screenshot, which works in every case.
Why not download the image URL from Node.js directly?
A separate HTTP client lacks the browser session and many CAPTCHA endpoints draw a new image on every request, so the answer would not match.
Does this work with Playwright too?
Yes. locator.screenshot returns a Buffer you can convert with toString base64, and the canvas code runs unchanged in page.evaluate.
Should I lowercase the returned text?
No. Type it exactly as returned, because many image CAPTCHAs are case sensitive.
How fast are image text tasks?
Usually ready under 1 seconds, which is why the loop polls once a second.
Keep reading
- PuppeteerOne Puppeteer client for three jobs: the reCAPTCHA v2 checkbox, v3 scores tied to an action, and text image CAPTCHAs.
- Image to Text solver$0.28 per 1,000 tasks, answers under 1 seconds.
- Solve image text CAPTCHAs in PythonDownload the distorted text image in the form session, base64 it, send ImageToTextTask and type the answer back with the right case.
- PuppeteerThe Node.js library that drives Chrome and Chromium over the DevTools Protocol, popular for scraping, screenshots and PDFs.