Skip to main content

Class: Browser

Defined in: packages/testing/src/browser.ts:149

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 (Node.js, browsers, bun)
  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?, options?): Browser

Defined in: packages/testing/src/browser.ts:181

Create a new Browser instance

Parameters

fetchFn?

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

Optional fetch function to use. If not provided, auto-detects: first tries SELF.fetch from cloudflare:test (Workers vitest environment), then falls back to globalThis.fetch.

options?

BrowserOptions

Optional configuration including metrics tracking.

Returns

Browser

Example

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

// Outside Workers environments — pass fetch explicitly or rely on globalThis.fetch
import { Browser } from '@lumenize/testing';
const browser = new Browser(fetch);

// With metrics tracking
const metrics: Metrics = {};
const browser = new Browser(fetch, { metrics });
await browser.fetch('https://example.com');
console.log(metrics.httpRequests); // 1

Accessors

fetch

Get Signature

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

Defined in: packages/testing/src/browser.ts:224

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>

(input, init?): Promise<Response>

MDN Reference

Parameters
input

string | Request<unknown, CfProperties<unknown>> | URL

init?

RequestInit<CfProperties<unknown>>

Returns

Promise<Response>


WebSocket

Get Signature

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

Defined in: packages/testing/src/browser.ts:349

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?): Context

Defined in: packages/testing/src/browser.ts:379

Create a browsing context (conceptually a browser tab)

Each context has:

  • Cookie-aware, CORS-validating fetch scoped to the origin
  • Cookie-aware WebSocket constructor
  • Per-context sessionStorage (independent per context)
  • BroadcastChannel constructor for cross-context messaging (shared per 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

Context

A Context instance (backward-compatible: destructuring still works)

Example

const browser = new Browser();

// Full context with storage and messaging
const tab = browser.context('https://example.com');
tab.sessionStorage.setItem('key', 'value');
const ch = new tab.BroadcastChannel('sync');

// Backward-compatible destructuring
const { fetch, WebSocket } = browser.context('https://example.com');

duplicateContext()

duplicateContext(ctx, options?): Context

Defined in: packages/testing/src/browser.ts:408

Create a duplicate of an existing context, simulating browser tab duplication.

The new context gets a clone of the original's sessionStorage (same data, independent mutations) and shares the same BroadcastChannel namespace and cookies. This is exactly how real browsers behave when a tab is duplicated.

Parameters

ctx

Context

The context to duplicate

options?

Optional headers and WebSocket configuration overrides

headers?

Record<string, string>

maxQueueBytes?

number

Returns

Context

A new Context with cloned sessionStorage

Example

const tab1 = browser.context('https://example.com');
tab1.sessionStorage.setItem('lmz_tab', 'abc123');

const tab2 = browser.duplicateContext(tab1);
tab2.sessionStorage.getItem('lmz_tab'); // 'abc123' (cloned)

// BroadcastChannel works across original and duplicate
const ch1 = new tab1.BroadcastChannel('probe');
const ch2 = new tab2.BroadcastChannel('probe');
// ch1 and ch2 can communicate

getAllCookies()

getAllCookies(): object[]

Defined in: packages/testing/src/browser.ts:623

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/testing/src/browser.ts:650

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/testing/src/browser.ts:605

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/testing/src/browser.ts:528

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/testing/src/browser.ts:670

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/testing/src/browser.ts:571

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
});