> ## Documentation Index
> Fetch the complete documentation index at: https://docs.clearproxy.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Node.js SDK

> Official Node.js SDK for ClearProxy API

## Installation & Setup

Get started with ClearProxy in your Node.js project.

<Steps>
  <Step title="Installation">
    Install the package via npm:

    ```bash theme={null}
    npm i clearproxy
    ```
  </Step>

  <Step title="Initialization">
    Initialize the client using your API key.

    ```javascript theme={null}
    import { ClearProxy } from "clearproxy";

    const client = new ClearProxy("clearpx_yourkey");
    ```
  </Step>
</Steps>

***

## Validating Proxies

The `check()` method is the core of the SDK, allowing you to validate proxy lists with various configurations.

### `client.check(file, options)`

**Parameters:**

* `file` (string) - Path to your proxy list file.
* `options` (object) - Configuration for the checking job.

#### Configuration Options

| Option       | Type   | Description                                  | Default |
| :----------- | :----- | :------------------------------------------- | :------ |
| `region`     | string | Testing region (e.g., `us1`, `eu1`, `asia1`) | `us1`   |
| `timeout`    | number | Request timeout in milliseconds (1000-20000) | `5000`  |
| `type`       | string | Proxy protocol (`http`, `socks4`, `socks5`)  | `http`  |
| `customUrls` | array  | Custom URL validation rules                  | `[]`    |

#### Basic Example

```javascript theme={null}
const result = await client.check("proxies.txt", {
  region: "us1",
  timeout: 5000,
  type: "http"
});

console.log(`Working: ${result.working.length}`);
console.log(`Failed: ${result.failed.length}`);
```

***

## Real-Time Progress Tracking

Real-time feedback via WebSockets, allowing you to track progress as it happens instead of waiting for the entire job to finish.

### Implementation

To enable real-time tracking, provide an `onProgress` callback in the `check()` options.

```javascript theme={null}
const result = await client.check("proxies.txt", {
  onProgress: (event) => {
    console.log(`Progress: ${event.progress}%`);
    console.log(`Status: ${event.details.message}`);
    console.log(`Working found: ${event.details.working_so_far}`);
  }
});
```

### Job ID Management

You can optionally provide a `jobId` to identify the socket connection. If omitted while using `onProgress`, the SDK automatically generates one.

| Option       | Type     | Description                                                   |
| :----------- | :------- | :------------------------------------------------------------ |
| `onProgress` | function | Callback triggered for every progress update.                 |
| `jobId`      | string   | Custom ID for tracking. (Default: `sdk_[random]_[timestamp]`) |

<Note>
  **WebSocket Logic:** The SDK manages the WebSocket lifecycle automatically—opening it when the check starts and closing it upon completion or failure.
</Note>

***

## Advanced Validation (Custom URLs)

Verify if your proxies can access specific websites with custom status code and content requirements.

### Usage

```javascript theme={null}
const result = await client.check("proxies.txt", {
  customUrls: [
    {
      url: "https://discord.com",
      requiredStatusCodes: [200, 301, 302]
    },
    {
      url: "https://www.google.com",
      requiredText: "Search",
      caseSensitive: false
    }
  ]
});
```

### Helper Methods

The SDK provides utilities to process custom validation results easily.

#### `client.getCustomUrlSummary(result)`

Get an aggregated summary of all tested URLs.

#### `client.filterByCustomUrl(result, url)`

Extract a list of proxies that specifically passed for a given URL.

```javascript theme={null}
const discordProxies = client.filterByCustomUrl(result, "https://discord.com");
console.log(`Found ${discordProxies.length} proxies valid for Discord`);
```

***

## Utility Methods

### Exporting Results

Convert your validated proxy lists into different formats.

#### `client.export(proxies, format, auth)`

* `format`: `txt`, `json`, or `csv`
* `auth`: boolean (include user:pass if available)

```javascript theme={null}
const textOutput = client.export(result.working, "txt", true);
fs.writeFileSync("working.txt", textOutput);
```

### Account & API Info

<CodeGroup>
  ```javascript Account Info theme={null}
  const info = await client.me();
  console.log(`Checks Left: ${info.user.checks}`);
  ```

  ```javascript List Regions theme={null}
  const regions = await client.regions();
  console.log("Available Regions:", regions);
  ```

  ```javascript Health Check theme={null}
  const status = await client.health();
  console.log("API Status:", status.status);
  ```
</CodeGroup>

***

## Response Structure

### Standard Response

```javascript theme={null}
{
  summary: {
    total_working: 150,
    countries: { "United States": 100, "Germany": 50 },
    anonymity_levels: { elite: 120, anonymous: 30 }
  },
  metadata: {
    user: { 
      email: "user@example.com", 
      remaining_checks: 4500,
      subscription_detail: { UnlimitedPro: false }
    },
    region_used: "us1",
    total_checked: 500
  },
  proxies: [...], // Array of all tested proxies
  working: [...], // Array of working proxies only
  failed: [...]   // Array of failed proxies only
}
```

### Custom URL Response

When `customUrls` are provided, the `custom_url_validation` field is populated.

```javascript theme={null}
{
  custom_url_validation: {
    summary: { total_urls_tested: 2, processing_time: "8.45s" },
    per_url_summary: [
      {
        url: "https://discord.com",
        success_count: 120,
        failed_count: 30,
        successful_proxies: [...]
      }
    ]
  }
}
```

***

## Error Handling

```javascript theme={null}
try {
  const result = await client.check("proxies.txt");
} catch (error) {
  console.error("ClearProxy Error:", error.message);
}
```

***

## Complete Example

This example demonstrates a full workflow: initialization, checking with real-time progress, using custom validation, and saving results.

```javascript theme={null}
import { ClearProxy } from "clearproxy";
import fs from "fs";

async function main() {
  // 1. Initialize the client
  const client = new ClearProxy("clearpx_yourkey");

  try {
    console.log("Starting proxy check...");

    // 2. Perform the check with all features enabled
    const result = await client.check("proxies.txt", {
      region: "us1",
      timeout: 5000,
      onProgress: (event) => {
        console.log(`[${event.progress}%] ${event.details.message}...`);
      },
      customUrls: [
        {
          url: "https://discord.com",
          requiredStatusCodes: [200, 301, 302]
        }
      ]
    });

    // 3. Process the results
    console.log(`\nCheck Complete!`);
    console.log(`Total Working: ${result.working.length}`);

    // 4. Filter and export specific results
    const discordProxies = client.filterByCustomUrl(result, "https://discord.com");
    console.log(`Discord Valid: ${discordProxies.length}`);

    if (discordProxies.length > 0) {
      const output = client.export(discordProxies, "txt", true);
      fs.writeFileSync("discord_working.txt", output);
      console.log("Saved discord_working.txt");
    }

    // 5. Check remaining balance
    const info = await client.me();
    console.log(`Remaining Checks: ${info.user.checks}`);

  } catch (error) {
    console.error("Workflow Failed:", error.message);
  }
}

main();
```
