Skip to main content

Class: Browser

Defined in: packages/utils/src/browser.ts:55

Cookie and Origin-aware client for HTTP and WebSockets

For detailed examples of Browser in testing examples, see @lumenize/testing Usage and @lumenize/testing Agents.

Automatically manages cookies across requests, making it easy to interact with APIs that rely on cookies for authentication, session management, and other flows. This is common in data extraction scenarios and testing.

The Browser automatically detects the appropriate fetch function to use:

  1. Uses provided fetch if passed to constructor
  2. Uses SELF.fetch from cloudflare:test if in Cloudflare Workers vitest environment
  3. Uses globalThis.fetch if available
  4. Throws error if no fetch is available

Example

// Simple usage - auto-detects fetch
const browser = new Browser();

// Login sets session cookie
await browser.fetch('https://api.example.com/auth/login', {
method: 'POST',
body: JSON.stringify({ username: 'user', password: 'pass' })
});

// Cookie automatically included in subsequent requests
const data = await browser.fetch('https://api.example.com/data/export');

// WebSocket with cookies
const ws = new browser.WebSocket('wss://api.example.com/stream');

// CORS testing with origin context
const page = browser.context('https://app.example.com');
await page.fetch('https://api.example.com/data');

Constructors

Constructor

new Browser(fetchFn?): Browser

Defined in: packages/utils/src/browser.ts:78

Create a new Browser instance

Parameters

fetchFn?

{(input, init?): Promise<Response>; (input, init?): Promise<Response>; }

Optional fetch function to use. If not provided, will use globalThis.fetch. In Cloudflare Workers vitest environment, use the Browser from @lumenize/testing which automatically provides SELF.fetch.

Returns

Browser

Example

// In Cloudflare Workers test environment - use Browser from @lumenize/testing
import { Browser } from '@lumenize/testing';
const browser = new Browser(); // Auto-detects SELF.fetch

// Outside Workers environments - pass fetch explicitly or use globalThis.fetch
import { Browser } from '@lumenize/utils';
const browser = new Browser(fetch);

Accessors

fetch

Get Signature

get fetch(): {(input, init?): Promise<Response>; (input, init?): Promise<Response>; }

Defined in: packages/utils/src/browser.ts:110

Cookie-aware fetch function

Automatically includes cookies from this browser instance in requests and stores cookies from responses.

Example
const browser = new Browser();

// First request sets session cookie
await browser.fetch('https://api.example.com/login?token=xyz');

// Subsequent requests include the cookie
const response = await browser.fetch('https://api.example.com/data');
Returns

(input, init?): Promise<Response>

MDN Reference

Parameters
input

URL | RequestInfo

init?

RequestInit<CfProperties<unknown>>

Returns

Promise<Response>

(input, init?): Promise<Response>

MDN Reference

Parameters
input

URL | RequestInfo

init?

RequestInit<RequestInitCfProperties>

Returns

Promise<Response>


WebSocket

Get Signature

get WebSocket(): (url, protocols?) => WebSocket

Defined in: packages/utils/src/browser.ts:143

Cookie-aware WebSocket constructor

Automatically includes cookies from this browser instance in the WebSocket upgrade request.

Example
const browser = new Browser();
const ws = new browser.WebSocket('wss://api.example.com/stream');
ws.onopen = () => console.log('Connected!');
Returns

new WebSocket(url, protocols?): WebSocket

Parameters
url

string | URL

protocols?

string | string[]

Returns

WebSocket

Methods

context()

context(origin, options?): object

Defined in: packages/utils/src/browser.ts:189

Create a context with Origin header for browser-like CORS behavior

Returns an object with fetch and WebSocket that both:

  • Include cookies from this browser
  • Include the specified Origin header
  • Include any custom headers

The fetch function returned by context() validates CORS headers and will throw a TypeError (like a real browser) if the server doesn't properly allow the origin.

Parameters

origin

string

The origin to use (e.g., 'https://example.com')

options?

Optional headers and WebSocket configuration

headers?

Record<string, string>

maxQueueBytes?

number

Returns

Object with fetch function and WebSocket constructor

fetch()

fetch: {(input, init?): Promise<Response>; (input, init?): Promise<Response>; }

Call Signature

(input, init?): Promise<Response>

MDN Reference

Parameters
input

URL | RequestInfo

init?

RequestInit<CfProperties<unknown>>

Returns

Promise<Response>

Call Signature

(input, init?): Promise<Response>

MDN Reference

Parameters
input

URL | RequestInfo

init?

RequestInit<RequestInitCfProperties>

Returns

Promise<Response>

lastPreflight

lastPreflight: null | PreflightInfo

WebSocket()

WebSocket: (url, protocols?) => WebSocket

Parameters
url

string | URL

protocols?

string | string[]

Returns

WebSocket

Example

const browser = new Browser();

// Simple usage - validates CORS on cross-origin requests
const page = browser.context('https://example.com');
await page.fetch('https://api.example.com/data'); // Validates CORS

// Same-origin request - no CORS validation needed
await page.fetch('https://example.com/data'); // No validation

// With custom headers
const page2 = browser.context('https://example.com', {
headers: { 'X-Custom': 'value' },
maxQueueBytes: 1024 * 1024
});
const ws = new page2.WebSocket('wss://api.example.com/ws');

// CORS error example - will throw TypeError
try {
await browser.context('https://app.com').fetch('https://api.com/data');
// Throws if api.com doesn't send proper CORS headers
} catch (err) {
console.error('CORS error:', err); // TypeError: Failed to fetch
}

getAllCookies()

getAllCookies(): object[]

Defined in: packages/utils/src/browser.ts:388

Get all cookies as an array of cookie objects

Returns

object[]

Array of cookie objects with name, value, and metadata


getAllCookiesAsObject()

getAllCookiesAsObject(): Record<string, string>

Defined in: packages/utils/src/browser.ts:415

Get all cookies as a simple name-value object

Returns

Record<string, string>

Object with cookie names as keys and values as values


getCookie()

getCookie(name, domain?): undefined | string

Defined in: packages/utils/src/browser.ts:370

Get a specific cookie by name

Parameters

name

string

Cookie name

domain?

string

Optional domain filter

Returns

undefined | string

Cookie value or undefined if not found


getCookiesForRequest()

getCookiesForRequest(requestUrl): null | string

Defined in: packages/utils/src/browser.ts:294

Get cookies that should be included in a request

Automatically cleans up expired cookies.

Parameters

requestUrl

string

The URL being requested

Returns

null | string

Cookie header value or null if no cookies match


removeCookie()

removeCookie(name, domain?, path?): void

Defined in: packages/utils/src/browser.ts:435

Remove a cookie

Parameters

name

string

Cookie name

domain?

string

Optional domain filter

path?

string

Optional path filter

Returns

void


setCookie()

setCookie(name, value, options): void

Defined in: packages/utils/src/browser.ts:336

Set a cookie manually

Parameters

name

string

Cookie name

value

string

Cookie value

options

Omit<Cookie, "name" | "value"> = {}

Optional cookie attributes (domain, path, expires, etc.)

Returns

void

Example

browser.setCookie('auth_token', 'abc123', {
domain: 'api.example.com',
path: '/',
expires: new Date(Date.now() + 3600000) // 1 hour
});