CloakBrowser

Practical CloakBrowser code examples for routing stealth browser traffic through Residential Proxies, separated into JavaScript (Node.js) and Python sections.

Cloakbrowser is an opensource stealth browser developed by CloakHQ that will increase the success rate of the web scraping process, although there still many factors affecting the success rate.

CloakBrowser code examples divided by programming language (JavaScript and Python) for stealth browser automation with Residential Proxy.

JavaScript (Node.js)

Prerequisites

npm install cloakbrowser proxy-chain
npx cloakbrowser install
  • cloakbrowser: Node.js stealth browser library featuring custom Chromium fingerprint evasion and Playwright-like APIs.

Proxy Format

In JavaScript, CloakBrowser accepts a proxy object during launch():

const proxy = {
  server: 'http://proxy.mrscraper.com:10000',
  username: 'user-country-us-sessid-session1',
  password: 'pass123',
}

SOCKS5 Proxy Setup

For SOCKS5 proxies, use proxy-chain to anonymize the authenticated SOCKS5 connection before passing the local proxy server to CloakBrowser:

import { launch } from 'cloakbrowser'
import { anonymizeProxy, closeAnonymizedProxy } from 'proxy-chain'

const username = 'user-country-us'
const password = 'pass123'

const socks5Proxy =
  `socks5://${encodeURIComponent(username)}:${encodeURIComponent(password)}` +
  `@proxy.mrscraper.com:10001`

const localProxy = await anonymizeProxy(socks5Proxy)

const browser = await launch({
  proxy: {
    server: localProxy,
  },
})

try {
  const page = await browser.newPage()

  await page.goto('https://ipinfo.io/json')

  console.log(await page.textContent('body'))
} finally {
  await browser.close()
  await closeAnonymizedProxy(localProxy, true)
}

Use port 10001 for SOCKS5. Always close the browser before calling closeAnonymizedProxy().

1. Basic Stealth Request

Demonstrates launching CloakBrowser with an authenticated residential proxy in JavaScript. It navigates to an IP lookup endpoint and prints the verified proxy IP.

import { launch } from 'cloakbrowser'

async function testStealthProxy() {
  // Launch stealth browser with proxy options
  const browser = await launch({
    headless: true,
    proxy: {
      server: 'http://proxy.mrscraper.com:10000',
      username: 'user-country-us',
      password: 'pass123',
    },
  })

  const page = await browser.newPage()
  await page.goto('https://api.ipify.org?format=json')

  const content = await page.textContent('body')
  console.log('Your Stealth Proxy IP:', content)

  await browser.close()
}

testStealthProxy().catch(console.error)

Use Case: Baseline proxy connectivity check and stealth browser launch in Node.js.

2. Sticky Session Navigation

Maintains a static IP address across sequential page navigations by reusing a session ID (sessid) and extending session time (sesstime-30).

import { launch } from 'cloakbrowser'

async function runStickyStealthSession() {
  const browser = await launch({
    headless: true,
    proxy: {
      server: 'http://proxy.mrscraper.com:10000',
      // 30-minute Canadian static session
      username: 'user-country-ca-sessid-stealth1-sesstime-30',
      password: 'pass123',
    },
  })

  const page = await browser.newPage()

  const targetUrls = [
    'https://example.com/step1',
    'https://example.com/step2',
    'https://example.com/step3',
  ]

  for (const url of targetUrls) {
    await page.goto(url)
    console.log(`Visited ${url} -> Title:`, await page.title())
  }

  await browser.close()
}

runStickyStealthSession().catch(console.error)

Use Case: Executing sensitive multi-page JavaScript workflows (logins, checkouts) while bypassing bot detection and retaining IP consistency.

3. Parallel Stealth Workers

Demonstrates spawning multiple concurrent JavaScript CloakBrowser instances, each configured with a unique sticky session ID for isolated parallel operations.

import { launch } from 'cloakbrowser'

async function runParallelWorkers() {
  const workerIds = ['worker_1', 'worker_2', 'worker_3']

  const workerPromises = workerIds.map(async (workerId) => {
    const browser = await launch({
      headless: true,
      proxy: {
        server: 'http://proxy.mrscraper.com:10000',
        username: `user-country-us-sessid-${workerId}`,
        password: 'pass123',
      },
    })

    const page = await browser.newPage()
    await page.goto('https://api.ipify.org?format=json')
    const ipData = await page.textContent('body')

    console.log(`Stealth Worker [${workerId}] IP:`, ipData)
    await browser.close()
  })

  await Promise.all(workerPromises)
}

runParallelWorkers().catch(console.error)

Use Case: High-concurrency Node.js web scraping where each worker thread requires dedicated stealth fingerprinting and IP isolation.

4. Production Error Handling

Production-ready error handling pattern for JavaScript CloakBrowser, providing navigation timeout configurations, response status validation, and safe browser closing routines.

import { launch } from 'cloakbrowser'

async function safeStealthScrape(targetUrl) {
  let browser = null
  try {
    browser = await launch({
      headless: true,
      proxy: {
        server: 'http://proxy.mrscraper.com:10000',
        username: 'user-country-us-sessid-prod1',
        password: 'pass123',
      },
    })

    const page = await browser.newPage()

    // Set 30s timeout
    const response = await page.goto(targetUrl, { timeout: 30000 })

    if (!response || !response.ok()) {
      throw new Error(`HTTP Error ${response?.status()}`)
    }

    console.log('Successfully loaded page title:', await page.title())
  } catch (error) {
    console.error(`CloakBrowser execution failed:`, error.message)
  } finally {
    if (browser) {
      await browser.close()
    }
  }
}

safeStealthScrape('https://example.com')

Use Case: Deploying enterprise Node.js stealth scrapers that handle timeouts and site exceptions safely.


Python

Prerequisites

pip install cloakbrowser
python -m cloakbrowser install
  • cloakbrowser: Python package for stealth browser automation and anti-bot evasions.
  • Install sing-box separately and make sure the sing-box command is available on your PATH for SOCKS5 proxy bridging.

Proxy Format

In Python, CloakBrowser receives a dictionary with proxy parameters:

proxy = {
    "server": "http://proxy.mrscraper.com:10000",
    "username": "user-country-us-sessid-session1",
    "password": "pass123"
}

SOCKS5 Proxy Setup

CloakBrowser's Python integration uses sing-box to expose the authenticated SOCKS5 proxy as a local HTTP proxy:

import json
import os
import subprocess
import tempfile
import time

from cloakbrowser import launch

username = "user-country-us"
password = "pass123"

local_proxy = "http://127.0.0.1:8080"

singbox_config = {
    "inbounds": [
        {
            "type": "http",
            "tag": "http-in",
            "listen": "127.0.0.1",
            "listen_port": 8080,
        }
    ],
    "outbounds": [
        {
            "type": "socks",
            "tag": "mrscraper",
            "server": "proxy.mrscraper.com",
            "server_port": 10001,
            "username": username,
            "password": password,
            "version": "5",
        }
    ],
    "route": {
        "final": "mrscraper"
    },
}

with tempfile.NamedTemporaryFile(
    mode="w",
    suffix=".json",
    delete=False,
) as config_file:
    json.dump(singbox_config, config_file)
    config_path = config_file.name

singbox_process = subprocess.Popen([
    "sing-box",
    "run",
    "-c",
    config_path,
])

try:
    time.sleep(1)

    browser = launch(
        headless=True,
        proxy={
            "server": local_proxy,
        },
    )

    try:
        page = browser.new_page()
        page.goto("https://ipinfo.io/json")
        print(page.text_content("body"))
    finally:
        browser.close()
finally:
    singbox_process.terminate()
    singbox_process.wait()
    os.remove(config_path)

Use port 10001 for SOCKS5 and always terminate sing-box after closing the browser.

1. Basic Stealth Request

Demonstrates launching CloakBrowser using its Python API to route automated browser requests through a residential proxy.

from cloakbrowser import launch

def test_stealth_proxy():
    # Launch browser with proxy server and credentials
    browser = launch(
        headless=True,
        proxy={
            "server": "http://proxy.mrscraper.com:10000",
            "username": "user-country-us",
            "password": "pass123"
        }
    )

    page = browser.new_page()
    page.goto("https://api.ipify.org?format=json")

    print("Your Stealth Proxy IP:", page.text_content("body"))
    browser.close()

if __name__ == "__main__":
    test_stealth_proxy()

Use Case: Quick stealth proxy verification script in Python for anti-bot testing and scraping.

2. Sticky Session Navigation

Maintains a static Python stealth browser session across multiple page navigations using a session ID (sessid).

from cloakbrowser import launch

def run_sticky_session():
    browser = launch(
        headless=True,
        proxy={
            "server": "http://proxy.mrscraper.com:10000",
            "username": "user-country-us-sessid-python1-sesstime-20",
            "password": "pass123"
        }
    )

    page = browser.new_page()

    urls = [
        "https://example.com/step1",
        "https://example.com/step2",
        "https://example.com/step3"
    ]

    for url in urls:
        page.goto(url)
        print(f"Scraped {url} -> Title: {page.title()}")

    browser.close()

if __name__ == "__main__":
    run_sticky_session()

Use Case: Python multi-step form completion and account crawling requiring anti-bot protection and session IP continuity.

3. Geotargeting & Stealth Fingerprinting

Demonstrates routing Python CloakBrowser traffic through a German residential proxy while leveraging stealth browser features.

from cloakbrowser import launch

def geotargeted_stealth():
    browser = launch(
        headless=True,
        proxy={
            "server": "http://proxy.mrscraper.com:10000",
            "username": "user-country-de-sessid-shop1",
            "password": "pass123"
        }
    )

    page = browser.new_page()
    page.goto("https://httpbin.org/headers")

    print("Stealth Browser Headers:\n", page.text_content("body"))
    browser.close()

if __name__ == "__main__":
    geotargeted_stealth()

Use Case: Accessing heavily protected international websites that combine WAF anti-bot protections with geo-restrictions.

4. Production Error Handling & Lifecycle Management

Provides robust Python error handling, custom navigation timeout configuration, response validation, and guaranteed teardown.

from cloakbrowser import launch

def safe_stealth_scrape(target_url):
    browser = None
    try:
        browser = launch(
            headless=True,
            proxy={
                "server": "http://proxy.mrscraper.com:10000",
                "username": "user-country-us-sessid-prod1",
                "password": "pass123"
            }
        )

        page = browser.new_page()
        page.set_default_timeout(30000)

        page.goto(target_url)
        print("Successfully loaded page title:", page.title())
    except Exception as error:
        print(f"CloakBrowser Python execution failed: {error}")
    finally:
        if browser:
            browser.close()

if __name__ == "__main__":
    safe_stealth_scrape("https://example.com")

Use Case: Production Python automation scripts requiring clean error logging and reliable browser process cleanup.

Note

  • CloakBrowser follows standard Playwright page and navigation APIs in both JavaScript and Python.
  • Run npx cloakbrowser install or python -m cloakbrowser install prior to execution to download stealth binaries.
  • Keep sensitive proxy credentials in environment variables (process.env.PROXY_PASSWORD or os.environ.get("PROXY_PASSWORD")).

On this page