AI agents and automation
How to solve image CAPTCHAs in n8n
Older portals still protect forms with a distorted text picture. In n8n the only tricky part is turning that picture into base64; after that, an ImageToTextTask at $0.28 per 1,000 returns the characters.
The plan
An image CAPTCHA is tied to a session. The server generates the picture, stores the expected text against your session cookie, and checks the form against it. So the workflow has to keep one cookie across three requests: load the form, download the picture, and submit. In between, it converts the picture to base64 and asks the API to read it.
- Open form: HTTP Request, GET the form page with headers kept.
- Get image: HTTP Request, GET the picture as a file, sending the session cookie.
- To base64: Extract From File node, or a Code node.
- Read text: Code node that creates the task and polls.
- Submit: HTTP Request that posts the form with the text.
Node and option names follow n8n 1.x at the time of writing.
Open the form and keep the cookie
In Open form, set the response to include headers and status, format text. Then find two things in the HTML: the image URL (often an img with an id like captcha and a path such as /captcha.php?r=...) and any hidden fields. A small Code node can pull both, along with the cookie.
// Code node "Form parts"
const resp = $input.first().json;
const markup = String(resp.data ?? resp.body ?? '');
const src = markup.match(/<img[^>]+id="captcha[^"]*"[^>]*src="([^"]+)"/i)?.[1];
if (!src) throw new Error('captcha image not found');
const jar = [].concat(resp.headers?.['set-cookie'] ?? [])
.map((line) => line.split(';')[0]).join('; ');
const hidden = {};
for (const m of markup.matchAll(/<input[^>]+type="hidden"[^>]*name="([^"]+)"[^>]*value="([^"]*)"/g)) {
hidden[m[1]] = m[2];
}
return [{ json: { imgUrl: new URL(src, 'https://portal.example.org/lookup').href, jar, hidden } }];
Adjust the image selector to your page and replace the base address with the form's URL. If attributes come in a different order, a single regular expression will miss them; in that case, use the HTML node's "Extract HTML Content" operation with CSS selectors instead.
Download the picture as binary data
In Get image, set the URL to {{ $json.imgUrl }}, add a Cookie header with {{ $json.jar }}, and set the response format to File. The node stores the picture in a binary property, by default named data. Sending the cookie here is essential: without it, the server generates the picture for a new session and the answer will never match the form.
Convert binary to base64
n8n offers two ways at the time of writing. Pick whichever your version supports.
Extract From File node
Add an Extract From File node with the operation "Move File to Base64 String", input binary field data, and a destination field such as imageB64. The output item then holds the base64 text as a normal JSON field.
Code node
In a Code node, the helper this.helpers.getBinaryDataBuffer(itemIndex, propertyName) returns the raw bytes regardless of how your instance stores binary data. Reading $binary.data.data directly can return a reference instead of the content when n8n keeps binaries on disk, so the helper is the safer choice.
// Code node "To base64"
const bytes = await this.helpers.getBinaryDataBuffer(0, 'data');
const prev = $('Form parts').first().json;
return [{ json: { ...prev, imageB64: bytes.toString('base64') } }];
The API expects plain base64 without a data:image/png;base64, prefix, which is exactly what both methods produce.
Send the picture as an ImageToTextTask
Image tasks are quick, so poll every second rather than every three. The Code node below uses this.helpers.httpRequest; if your instance blocks it, build the same loop from HTTP Request, Wait (1 second) and IF nodes.
// Code node "Read text"
const item = $input.first().json;
const ask = (route, extra) => this.helpers.httpRequest({
method: 'POST', url: 'https://gatesolver.com/' + route, json: true,
body: Object.assign({ clientKey: $vars.GATESOLVER_KEY ?? 'YOUR_API_KEY' }, extra),
});
const job = await ask('createTask', { task: { type: 'ImageToTextTask', body: item.imageB64 } });
if (job.errorId) { throw new Error(`image task not created (${job.errorCode})`); }
for (let tick = 0; tick < 60; tick++) {
await new Promise((ok) => setTimeout(ok, 1000));
const out = await ask('getTaskResult', { taskId: job.taskId });
if (out.status === 'ready') return [{ json: { ...item, captchaText: out.solution.text } }];
if (out.errorId || out.status === 'failed') throw new Error('unreadable: ' + (out.errorCode ?? 'failed'));
}
throw new Error('no text after a minute');
The task also accepts an optional module for a particular text style and a score threshold between 0.8 and 1. Start without them and add them only if answers are often wrong. Unreadable images come back as ERROR_CAPTCHA_UNSOLVABLE and are free.
Submit the answer
In Submit, POST to the form's action URL with Body Content Type "Form Urlencoded". Add the visible fields, every hidden field from {{ $json.hidden }}, and the CAPTCHA field (its name is in the form, often captcha or code) set to {{ $json.captchaText }}. Send the same Cookie header as before.
Many image CAPTCHAs are case sensitive. Enter the text exactly as returned; do not lowercase or trim inner spaces unless you know the site ignores them. The FAQ on image CAPTCHA case sensitivity covers the edge cases.
When the site says the code is wrong
- Check that all three requests used the same cookie. This is the most common cause.
- Make sure the picture was downloaded after the form, not cached from an earlier run.
- Look at the image file in n8n's binary view. If it is tiny or blank, the URL or cookie is wrong.
- If the text is close but wrong, try the
moduleoption or ascorethreshold.
More background on the task is on Image to Text, and the OCR entry explains how recognition differs from ordinary text extraction.
Running it on a schedule
Lookups on legacy portals are often repetitive: check the status of a set of reference numbers each morning, for example. Feed those numbers from a spreadsheet node or a database query, and place a Loop Over Items node in front of Open form with a batch size of one. Each number then gets its own session, its own image and its own answer, which is exactly what the server expects. Running several items through the same session at once would mix up images and answers.
Add a short Wait between items as well. Portals that still use image CAPTCHAs are often small systems, and a polite pace keeps your automation welcome. At $0.28 per 1,000 images, the solving part of a daily batch of a hundred lookups is a small fraction of a dollar.
Storing results
Parse the result page with the HTML node, write the fields you need to your sheet or database, and keep the raw page for a few days in case a value is disputed.
Common questions
Why must the image request send the session cookie?
The server stores the expected text against your session. Without the cookie, the picture belongs to a new session and the answer will not match.
Should the base64 include the data:image prefix?
No. Send only the base64 text. Both the Extract From File node and Buffer toString produce that form.
Why poll every second for image tasks?
Text recognition finishes much faster than token tasks, so a one second interval returns the answer sooner.
Is an unreadable image charged?
No. If the image cannot be read the task returns ERROR_CAPTCHA_UNSOLVABLE and costs nothing.
Can I use the in.php method instead?
Yes. in.php with method base64 and json=1 works too, but the JSON createTask flow fits n8n expressions more naturally.
Keep reading
- n8nA reusable n8n solve loop built only from HTTP Request, Wait and IF nodes, with an attempt cap and clean error branches.
- Image to Text solver$0.28 per 1,000 tasks, answers under 1 seconds.
- OCROptical character recognition turns pictures of text into characters, and it is the engine behind solving distorted text CAPTCHAs.
- Are image CAPTCHA answers case sensitive?It depends on the site: many compare case-insensitively, some do not, so test once and submit answers exactly as returned.