HTTPCloak Node.js Client
HTTPCloak is a Node.js HTTP client specifically engineered for advanced browser fingerprint emulation across HTTP/1.1, HTTP/2, and HTTP/3 (QUIC) protocols. It is designed to mimic real browser characteristics, including TLS and HTTP/2 fingerprints, to bypass sophisticated bot detection systems. The current stable version is 1.6.1, indicating an actively developed library that regularly incorporates updates necessary to counter evolving anti-bot technologies. While a formal release cadence isn't specified, libraries in this domain typically require frequent maintenance. Its key differentiators include comprehensive multi-protocol support and configurable browser presets, making it highly effective for web scraping, automation, and bypassing anti-bot measures.
Common errors
-
ERR_REQUIRE_ESM: Must use import to load ES Module: .../node_modules/httpcloak/dist/index.js
cause Attempting to use `require()` to import `httpcloak` in an ECMAScript Module (ESM) project, or when Node.js is running in ESM mode.fixChange your import statement to `import { Session } from 'httpcloak';` and ensure your project is configured for ESM (e.g., `"type": "module"` in `package.json`). -
TypeError: session.get is not a function
cause The `Session` class was not correctly imported or instantiated, leading to an attempt to call a method on an undefined or incorrect object.fixVerify that `import { Session } from 'httpcloak';` (ESM) or `const { Session } = require('httpcloak');` (CJS) is used, and that you are creating an instance: `const session = new Session({...});`. -
UnhandledPromiseRejectionWarning: Error: Session already closed or invalid state
cause Attempting to make a request or perform an action on an `httpcloak` session after `session.close()` has already been called.fixEnsure that `session.close()` is called only once, after all operations for that session are complete. If concurrent operations are intended, manage them with `Promise.all` before closing the session, or use separate sessions for distinct sets of operations.
Warnings
- gotcha Failing to call `session.close()` can lead to resource leaks, including open sockets and memory, especially in long-running applications or when creating many sessions. Each `Session` instance manages its own network connections and state.
- gotcha HTTP/3 support might require specific Node.js versions (Node.js 14+ is listed, but specific HTTP/3 features might be more robust in newer versions) and could be sensitive to underlying operating system QUIC implementations. Connection failures or unexpected behavior might occur if the environment is not fully compatible.
- breaking The library primarily uses named exports. Directly `require('httpcloak')` without destructuring in CommonJS, or `import Session from 'httpcloak'` in ESM (expecting a default export), will result in `undefined` or an error when trying to access `Session`.
Install
-
npm install httpcloak -
yarn add httpcloak -
pnpm add httpcloak
Imports
- Session
const Session = require('httpcloak').Session; // Incorrect CommonJS access if in ESM context import Session from 'httpcloak'; // Incorrect default importimport { Session } from 'httpcloak'; - Session (CommonJS)
import { Session } from 'httpcloak'; // Will throw 'ERR_REQUIRE_ESM' in CommonJS environmentconst { Session } = require('httpcloak'); - SessionOptions (TypeScript Type)
import { SessionOptions } from 'httpcloak'; // Incorrect if only importing the type, may cause runtime issues if SessionOptions is not a runtime valueimport type { SessionOptions } from 'httpcloak';
Quickstart
import { Session } from 'httpcloak';
async function runHttpcloakExample() {
const session = new Session({
preset: 'chrome-latest', // Emulate the latest Chrome browser fingerprint
// You can also specify proxy, timeouts, etc. here
// proxy: 'http://username:password@proxy.example.com:8080',
// timeout: 15000
});
try {
console.log('Performing GET request to Cloudflare trace...');
const getResponse = await session.get('https://www.cloudflare.com/cdn-cgi/trace');
console.log('GET Status Code:', getResponse.statusCode);
console.log('GET Response Text:\n', getResponse.text.slice(0, 200), '...'); // Log first 200 chars
console.log('\nPerforming POST request to a mock API...');
const postResponse = await session.post('https://jsonplaceholder.typicode.com/posts', {
title: 'foo',
body: 'bar',
userId: 1,
}, {
'Content-Type': 'application/json' // Custom headers for the request
});
console.log('POST Status Code:', postResponse.statusCode);
console.log('POST Response JSON:', JSON.parse(postResponse.text));
console.log('\nAttempting concurrent requests...');
const [res1, res2] = await Promise.all([
session.get('https://example.com/'),
session.get('https://httpbin.org/get')
]);
console.log('Concurrent Request 1 Status:', res1.statusCode);
console.log('Concurrent Request 2 Status:', res2.statusCode);
} catch (error) {
console.error('An error occurred:', error.message);
} finally {
console.log('\nClosing HTTPCloak session...');
session.close(); // Essential for resource cleanup
}
}
runHttpcloakExample();