
Ethan Collins
Pattern Recognition Specialist
Are your Node.js automation scripts constantly being blocked by Cloudflare? You're not alone. Cloudflare's powerful security measures, like its JavaScript challenges and "I'm Under Attack" mode, are effective at stopping bots but can also halt legitimate web scraping and data extraction tasks. These security checks validate visitors by running background tests that automated scripts often fail.
This guide will show you how to overcome this obstacle. We'll walk through a clear, step-by-step process using Node.js and the CapSolver service to efficiently solve Cloudflare challenges and obtain the necessary cf_clearance token for seamless access.
Before we begin, ensure you have the following ready:
First, we need to install the axios library for making HTTP requests. Open your terminal and execute the following command:
npm install axios
Here is the sample code for solving the Cloudflare challenge and obtaining the cf_clearance token using Node.js and the CapSolver API. This code demonstrates how to create an AntiCloudflareTask and poll for the solution.
This code incorporates the latest practices from the CapSolver official documentation, featuring a cleaner structure and necessary comments.
const axios = require('axios');
// -------------------PLEASE MODIFY THESE VALUES-------------------
// Your proxy details in the format: http://username:password@ip:port
const PROXY = 'http://username:password@ip:port';
// Your API key from the CapSolver Dashboard
const CAPSOLVER_API_KEY = 'YourAPIKEY';
// The URL of the target website where you want to solve the Cloudflare challenge
const PAGE_URL = 'https://www.yourwebsite.com';
// ----------------------------------------------------------------
/**
* Creates a task to solve the Cloudflare challenge using the CapSolver API.
* @param {string} websiteURL - The URL of the target website.
* @param {string} proxy - The proxy to use.
* @returns {Promise<string|null>} - The task ID, or null if creation fails.
*/
async function createCloudflareTask(websiteURL, proxy) {
console.log('Creating Cloudflare task for CapSolver...');
try {
const response = await axios.post('https://api.capsolver.com/createTask', {
clientKey: CAPSOLVER_API_KEY,
task: {
type: 'AntiCloudflareTask',
websiteURL: websiteURL,
proxy: proxy
}
});
if (response.data.errorId > 0) {
console.error(`Failed to create task: ${response.data.errorDescription}`);
return null;
}
console.log(`Task created successfully. Task ID: ${response.data.taskId}`);
return response.data.taskId;
} catch (error) {
console.error(`An error occurred while creating the task: ${error}`);
return null;
}
}
/**
* Polls for the task result.
* @param {string} taskId - The task ID returned by CapSolver.
* @returns {Promise<object|null>} - The solution object, or null if it fails.
*/
async function getTaskResult(taskId) {
console.log(`Getting result for task ID ${taskId}...`);
let solution = null;
while (!solution) {
await new Promise(resolve => setTimeout(resolve, 3000)); // Wait for 3 seconds
try {
const response = await axios.post('https://api.capsolver.com/getTaskResult', {
clientKey: CAPSOLVER_API_KEY,
taskId: taskId
});
if (response.data.errorId > 0) {
console.error(`Failed to get result: ${response.data.errorDescription}`);
return null;
}
if (response.data.status === 'ready') {
console.log('Solution retrieved successfully!');
solution = response.data.solution;
} else if (response.data.status === 'processing') {
console.log('Task is still processing, please wait...');
} else if (response.data.status === 'failed') {
console.error(`Task processing failed: ${response.data.errorDescription}`);
return null;
}
} catch (error) {
console.error(`An error occurred while getting the result: ${error}`);
return null;
}
}
return solution;
}
/**
* Main function to execute the entire process.
*/
async function main() {
console.log('Starting to solve Cloudflare challenge...');
const taskId = await createCloudflareTask(PAGE_URL, PROXY);
if (!taskId) {
console.log('Could not create task, exiting.');
return;
}
const solution = await getTaskResult(taskId);
if (!solution) {
console.log('Could not retrieve solution, exiting.');
return;
}
console.log('Solution details obtained:');
console.log(solution);
// You can now use the obtained cookies and user-agent to access the target website.
// The solution object contains 'url', 'status', 'headers', 'cookies', 'userAgent'.
// Example: How to use the obtained cookies and user-agent to make a request
try {
const cfCookie = solution.cookies.map(cookie => `${cookie.name}=${cookie.value}`).join('; ');
console.log('\nAccessing the target page with the obtained cookies and user-agent...');
const pageResponse = await axios.get(PAGE_URL, {
headers: {
'User-Agent': solution.userAgent,
'Cookie': cfCookie
},
// It's recommended to use a dedicated proxy-enabled axios instance for subsequent requests.
proxy: false,
});
console.log(`\nSuccessfully accessed! Page status code: ${pageResponse.status}`);
// console.log('Page content:', pageResponse.data); // Uncomment to see the page content
} catch (error) {
console.error(`\nError accessing page with solution: ${error.response ? error.response.status : error.message}`);
}
}
main();
Before running the code, be sure to modify the following variables:
PROXY: Replace this with your proxy server address and credentials. The format should be http://username:password@ip:port.CAPSOLVER_API_KEY: Find your API key in the CapSolver Dashboard and replace the placeholder.PAGE_URL: Replace this with the URL of the target website protected by Cloudflare.By integrating CapSolver, developers can automate the complex process of handling Cloudflare challenges within their Node.js applications. This approach not only has a high success rate but also frees you from dealing with ever-changing security policies. You simply call an API and receive the cf_clearance token and a matching User-Agent, enabling seamless access to your target website. This strategy is essential for any project requiring stable, large-scale data collection. For those interested in a deeper dive, our guide on how to solve the Cloudflare 5s challenge provides additional technical details.
Q1: Why do I need to use a proxy?
A1: Cloudflare monitors IP addresses for unusual activity. A single IP making many requests can be flagged as a bot. Using high-quality rotating proxies (like residential or ISP proxies) mimics real user behavior and greatly increases your success rate.
Q2: How long is the cf_clearance token valid?
A2: A cf_clearance token is typically valid for a few hours, though the exact duration depends on the website's Cloudflare settings. Once it expires, you must run the process again to get a new token.
Q3: Can I use the obtained cookie in my scraper?
A3: Yes. After getting the solution from CapSolver, you must include the cf_clearance cookie and the matching User-Agent in all subsequent HTTP requests. It is crucial to use the same proxy IP that was used to generate the token. While this guide focuses on Node.js, similar principles apply to other languages. For instance, you can learn how to solve Cloudflare with Python and Selenium in our other post.
Q4: What other types of CAPTCHAs can CapSolver handle?
A4: CapSolver supports a wide range of challenges beyond Cloudflare, including various versions of reCAPTCHA and image-based CAPTCHAs. To stay updated on the most effective solutions, you can check out our performance rankings of top Cloudflare challenge solvers. For a complete list of supported types, it's best to consult the official CapSolver documentation.
Learn how to fix the "failed to verify cloudflare turnstile token" error. This guide covers causes, troubleshooting steps, and how to defeat cloudflare turnstile with CapSolver.

Discover the best cloudflare challenge solver tools, compare API vs. manual automation, and find optimal solutions for your web scraping and automation needs. Learn why CapSolver is a top choice.
