Cloudflare
How to get past the Cloudflare challenge page in Node.js
Node.js can fetch Cloudflare protected pages without a browser once it holds a valid cf_clearance cookie. The work is in keeping three things consistent: the proxy IP, the user agent and the cookies.
How the pieces relate
Cloudflare's challenge page is answered by a browser, which receives a cf_clearance cookie. The cookie is valid only for requests that look like they come from that same browser: the same IP address and the same user agent string. GateSolver's AntiCloudflareTask passes the challenge through the proxy you provide and returns the cookies together with the user agent it used. Your Node.js code then has to send all later requests through that proxy, with that user agent and those cookies.
Node's built in fetch does not support proxies or a cookie jar by itself. The undici package, which powers that fetch, adds a ProxyAgent; a cookie jar takes about twenty lines. Install with npm install undici. The code needs Node 20 or newer for Headers.getSetCookie().
Request the clearance
The proxy must keep one exit IP while you use the cookie. If your provider rotates by default, ask for a sticky session.
// clearance.mjs
const SOLVE_HOST = 'https://gatesolver.com';
const SEND_AS_JSON = { 'content-type': 'application/json' };
async function solverRequest(method, payload) {
const reply = await (await fetch(`${SOLVE_HOST}/${method}`, {
method: 'POST',
headers: SEND_AS_JSON,
body: JSON.stringify({ clientKey: process.env.GATE_KEY, ...payload }),
})).json();
if (reply.errorId) throw new Error(`${method}: ${reply.errorCode} ${reply.errorDescription ?? ''}`);
return reply;
}
export async function getClearance(websiteURL, proxy, userAgent) {
const task = { type: 'AntiCloudflareTask', websiteURL, proxy };
if (userAgent) task.userAgent = userAgent;
const { taskId } = await solverRequest('createTask', { task });
const until = Date.now() + 125_000;
while (Date.now() < until) {
await new Promise((wake) => setTimeout(wake, 3000));
const r = await solverRequest('getTaskResult', { taskId });
if (r.status === 'ready') return r.solution; // cookies, token, userAgent
if (r.status === 'failed') throw new Error('clearance task failed, nothing charged');
}
throw new Error('clearance task did not finish in time');
}
The optional userAgent parameter lets you fix the browser string in advance, which is useful when other parts of your system already send a specific one. If you leave it out, read solution.userAgent and use that.
A small cookie jar
A cookie jar for a single site needs to do two things: start from the cookies in the solution, and absorb any Set-Cookie headers the site sends later, such as refreshed bot management cookies.
// jar.mjs
export class SiteJar {
#cookies = new Map();
seed(obj = {}) {
for (const [name, value] of Object.entries(obj)) this.#cookies.set(name, value);
}
absorb(response) {
for (const line of response.headers.getSetCookie()) {
const first = line.split(';', 1)[0];
const cut = first.indexOf('=');
if (cut > 0) this.#cookies.set(first.slice(0, cut).trim(), first.slice(cut + 1).trim());
}
}
toHeader() {
return [...this.#cookies].map(([n, v]) => `${n}=${v}`).join('; ');
}
}
This jar ignores Domain, Path and Expires on purpose: it serves one site, and expiry is handled by detecting the challenge again. If you crawl several sites or need full cookie semantics, use a library such as tough-cookie instead.
A fetch that stays consistent
// cf-fetch.mjs
import { fetch as proxiedFetch, ProxyAgent } from 'undici';
import { SiteJar } from './jar.mjs';
import { getClearance } from './clearance.mjs';
export async function clearedFetcher(startUrl, proxy) {
const sol = await getClearance(startUrl, proxy);
const agent = new ProxyAgent(proxy);
const jar = new SiteJar();
jar.seed(sol.cookies);
return async function get(url, extraHeaders = {}) {
const res = await proxiedFetch(url, {
dispatcher: agent,
headers: {
'user-agent': sol.userAgent, // must match the clearance
'accept-language': 'en-GB,en;q=0.8',
accept: 'text/html,application/xhtml+xml,*/*;q=0.8',
cookie: jar.toHeader(),
...extraHeaders,
},
});
jar.absorb(res);
return res;
};
}
const get = await clearedFetcher('https://listings.example.com/', 'http://user:pass@198.51.100.7:8000');
const page = await get('https://listings.example.com/category/tools?page=2');
console.log(page.status, page.headers.get('cf-mitigated') ?? 'no challenge');
The agent, the user agent and the jar are created once and captured by the returned function, so every call is consistent without the caller having to remember anything. Recent undici versions read the proxy credentials from the URL; if yours does not, pass them with the agent's token option as a Basic authorization value.
Detect when to solve again
The clearance does not last forever. When a response carries cf-mitigated: challenge, or comes back 403 with the "Just a moment" page, build a new fetcher and repeat the request once. Keep a counter: if a fresh clearance is challenged again within a few requests, something else is wrong, and solving more will not help.
- IP drift. The proxy switched exit IPs. Check by fetching an IP echo service through the same agent before and after.
- Header mismatch. Some other part of your code set a different user agent. Make the fetcher the only way requests go out.
- Client fingerprint. Cloudflare can also weigh TLS and HTTP/2 characteristics. Node's TLS stack does not look like Chrome's, and on strict sites that alone can trigger new challenges. The glossary entry on TLS fingerprinting explains it; the practical fix is a real browser through Playwright for those sites.
- Rate. Requests far faster than a person would make bring the challenge back. Pace them.
When a browser is the better tool
If the site's pages need JavaScript to render their content anyway, skip the HTTP client and use Playwright with the same proxy. Add the solution cookies to the context with context.addCookies() (with the site's domain and path) and set the context's userAgent to the solution value before the first navigation. The browser then also passes Cloudflare's passive checks on its own TLS stack. The Playwright integration guide shows the context setup.
Running several identities at once
For more throughput, create one fetcher per proxy IP rather than sharing one across many workers. Each fetcher owns its agent, its jar and its user agent, so nothing leaks between identities, and a challenge on one IP never forces a new solve on the others. A simple pool keeps an array of fetchers and hands URLs to them round robin, with a small per fetcher concurrency limit (one or two requests in flight is plenty). Because the API accepts any number of open tasks, the initial clearances for all identities can be requested in parallel with Promise.all; only the request rate of 600 calls per minute per key needs watching.
Persist each identity's proxy, user agent and cookies when your process shuts down, and restore them on start. A clearance that is still valid saves a solve, and restoring the user agent along with it keeps the binding intact. The reuse guide shows a storage format that works for this.
Logging that pays off later
Log three things per identity: when its clearance was obtained, how many requests it served, and when the challenge came back. After a day of running you will know how long clearances last on the site you target and how many requests each one carries, which tells you exactly how many identities and solves a given crawl needs.
Cost and good use
A solved challenge costs $0.84 per 1,000 tasks; failed tasks and error replies cost nothing. One clearance typically covers many page loads, so the real cost per page depends mostly on how long you can reuse each cookie, which the cf_clearance reuse guide covers. Use this for public catalogs, price and stock monitoring, and testing your own Cloudflare rules. A firewall block such as error 1020 is a different matter: it is a rule, not a challenge, and no clearance changes it. Fields are listed on the Cloudflare Challenge task page.
Common questions
Why do I need undici when Node has fetch?
The built in fetch has no proxy option. undici provides ProxyAgent, which routes requests through the proxy the clearance is bound to.
Which Node.js version is required?
Node 20 or newer, for Headers.getSetCookie. The rest works on Node 18.
Do I have to set every cookie from the solution?
Yes, set all of them. cf_clearance is the key one, but other Cloudflare cookies in the solution can matter too.
Can I share one clearance between proxies?
No. The cookie is tied to the IP that passed the challenge. Each proxy IP needs its own clearance.
What if the challenge returns right after a fresh solve?
Check IP stability, header consistency and request rate. Repeated solving will not fix those causes.
Keep reading
- Cloudflare Challenge solver$0.84 per 1,000 tasks, answers under 10 seconds.
- Reusing cf_clearance cookies safelyDesign sessions around cf_clearance: bind each cookie to one IP and user agent, track its age and refresh only when needed.
- cf_clearance cookieThe cookie Cloudflare sets after a passed challenge, why it only works from one IP and user agent, and its lifespan.
- PlaywrightPlaywright in Node.js and Python: read widget keys from the DOM or network, inject tokens, and add answers through route interception.