CAPSOLVER
Blog
How to solve Cloudflare Challenge with Node.JS

How to Solve Cloudflare Challenge with Node.js

Logo of CapSolver

Ethan Collins

Pattern Recognition Specialist

03-Dec-2025

Introduction

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.

⚙️ Prerequisites

Before we begin, ensure you have the following ready:

  • A working proxy: This is crucial for solving Cloudflare challenges. It is highly recommended to use ISP or residential proxies, as their IP addresses are less likely to be flagged.
  • Node.js installed: Make sure Node.js is installed on your system.
  • CapSolver API Key: You will need a CapSolver account to obtain an API key. CapSolver is an AI-based service designed to handle various CAPTCHA and bot challenges.

🤖 Step 1: Install Necessary Node.js Packages

First, we need to install the axios library for making HTTP requests. Open your terminal and execute the following command:

bash Copy
npm install axios

👨‍💻 Step 2: Write Node.js Code to Solve the Cloudflare Challenge

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.

Updated Node.js Code

This code incorporates the latest practices from the CapSolver official documentation, featuring a cleaner structure and necessary comments.

javascript Copy
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();

⚠️ Important Variables to Change

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.

Conclusion

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.

Frequently Asked Questions (FAQ)

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.

Compliance Disclaimer: The information provided on this blog is for informational purposes only. CapSolver is committed to compliance with all applicable laws and regulations. The use of the CapSolver network for illegal, fraudulent, or abusive activities is strictly prohibited and will be investigated. Our captcha-solving solutions enhance user experience while ensuring 100% compliance in helping solve captcha difficulties during public data crawling. We encourage responsible use of our services. For more information, please visit our Terms of Service and Privacy Policy.

More

How to Automate Cloudflare Challenge Solving in Selenium
How to Automate Cloudflare Challenge Solving in Selenium

Master the definitive strategy for Cloudflare Challenge Solving in Selenium. Use Undetected-Chromedriver, behavioral mimicry, and CapSolver's API for reliable web automation

Cloudflare
Logo of CapSolver

Ethan Collins

03-Dec-2025

How to solve Cloudflare Challenge with Node.JS
How to Solve Cloudflare Challenge with Node.js

A look at why Cloudflare blocks Node.js scrapers and how developers reliably get cf_clearance for data workflows.

Cloudflare
Logo of CapSolver

Ethan Collins

03-Dec-2025

 Top Cloudflare Challenge Solvers in 2026: Performance Rankings
Top Cloudflare Challenge Solvers in 2026: Performance Rankings

Discover the Top Cloudflare Challenge Solvers in 2026. We compare CapSolver's superior speed and 99%+ success rate against 5 smaller competitors. Learn why CapSolver is the best choice for web automation.

Cloudflare
Logo of CapSolver

Aloísio Vítor

11-Nov-2025

Solve Cloudflare with Python & Selenium
How to Solve Cloudflare Captcha with Python & Selenium

Struggling with Cloudflare Captcha? Learn how to tackle it using Python and Selenium! This guide breaks down what Cloudflare Captcha is and offers effective solutions for web scraping in 2024.

Cloudflare
Logo of CapSolver

Rajinder Singh

10-Nov-2025

How to Solve Cloudflare in 2026: The 6 Best Methods for Uninterrupted Automation
How to Solve Cloudflare in 2026: The 6 Best Methods for Uninterrupted Automation

Discover the 6 best methods to solve the Cloudflare Challenge 5s in 2026 for web scraping and automation. Includes detailed strategies, code examples, and a deep dive into the AI-powered CapSolver solution

Cloudflare
Logo of CapSolver

Ethan Collins

29-Oct-2025

How to Solve the Cloudflare 5s Challenge: A Technical Guide for Web Scraping
How to Solve the Cloudflare 5s Challenge: A Technical Guide for Web Scraping

Learn how to solve the Cloudflare 5-second challenge using advanced CAPTCHA solver APIs. A step-by-step guide for developers on overcoming Cloudflare JavaScript and Managed Challenges with CapSolver for stable web scraping automation.

Cloudflare
Logo of CapSolver

Anh Tuan

28-Oct-2025