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

# Sessions with X402

> Purchase a browser session with a wallet, without a Hyperbrowser API key

Purchase a browser session for **\$0.10 per hour** using your wallet. Choose a `timeoutMinutes` value from **5 to 60** (default **30**) and pay upfront for that duration.

You receive connection credentials and can navigate, click, type, scrape, and take screenshots using your own automation code. No Hyperbrowser account or API key is required. Browser actions after purchase do not require additional X402 payments.

## Pricing

| Session duration | Price (USDC) |
| - | - |
| 5 minutes | \$0.01 |
| 10 minutes | \$0.02 |
| 15 minutes | \$0.03 |
| 30 minutes (default) | \$0.05 |
| 45 minutes | \$0.08 |
| 60 minutes | \$0.10 |

## Purchase a session

The TypeScript example below uses the X402 SDKs to handle the payment challenge, sign with your wallet, and retry the request automatically. It supports both EVM and Solana wallets.

### 1. Install dependencies

```bash theme={null}
npm install @x402/fetch @x402/core @x402/evm @x402/svm viem @solana/kit @scure/base dotenv
npm install --save-dev tsx
```

### 2. Configure your wallet

Set either or both keys in a `.env` file. Use a `0x`-prefixed EVM private key or a base58-encoded Solana 64-byte secret key, and fund the wallet with USDC on the network you intend to use.

```dotenv theme={null}
EVM_PRIVATE_KEY=0x...
SOLANA_PRIVATE_KEY=...
```

Set only one key to choose EVM or Solana. With both set, the client uses the first compatible payment option returned by the server.

### 3. Create the session

Save this as `create-session.ts`. If your keys are in `.env.agent`, replace `dotenv.config()` with `dotenv.config({ path: ".env.agent" })`.

```typescript theme={null}
import dotenv from "dotenv";
import { writeFile } from "node:fs/promises";
import { wrapFetchWithPayment } from "@x402/fetch";
import { x402Client, x402HTTPClient } from "@x402/core/client";
import { registerExactEvmScheme } from "@x402/evm/exact/client";
import { registerExactSvmScheme } from "@x402/svm/exact/client";
import { privateKeyToAccount } from "viem/accounts";
import { createKeyPairSignerFromBytes } from "@solana/kit";
import { base58 } from "@scure/base";

dotenv.config();

async function main() {
  const evmKey = process.env.EVM_PRIVATE_KEY;
  const solanaKey = process.env.SOLANA_PRIVATE_KEY;
  if (!evmKey && !solanaKey) {
    throw new Error("Set EVM_PRIVATE_KEY or SOLANA_PRIVATE_KEY in .env");
  }

  const client = new x402Client();

  if (evmKey) {
    registerExactEvmScheme(client, {
      signer: privateKeyToAccount(evmKey as `0x${string}`),
    });
  }

  if (solanaKey) {
    const signer = await createKeyPairSignerFromBytes(base58.decode(solanaKey));
    registerExactSvmScheme(client, { signer });
  }

  const fetchWithPayment = wrapFetchWithPayment(fetch, client);
  const response = await fetchWithPayment(
    "https://api.hyperbrowser.ai/x402/session",
    {
      method: "POST",
      signal: AbortSignal.timeout(60_000),
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ timeoutMinutes: 5 }),
    }
  );

  const session = await response.json();
  if (!response.ok) {
    throw new Error(
      `Session creation failed (${response.status}): ${JSON.stringify(session)}`
    );
  }

  await writeFile("session.json", JSON.stringify(session, null, 2), {
    mode: 0o600,
  });
  console.log("Session:", session);

  const httpClient = new x402HTTPClient(client);
  console.log(
    "Payment settled:",
    httpClient.getPaymentSettleResponse((name) => response.headers.get(name))
  );
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});
```

Run the example:

```bash theme={null}
npx tsx create-session.ts
```

The response is saved to `session.json` for the browser connection and management examples below. Add any of the [supported options](#supported-options) to the request body to configure the browser.

<Accordion title="Payment flow with cURL">
  ### 1. Request payment requirements

  Send `{}` for the default session, or include any of the [supported options](#supported-options). This example requests five minutes:

  ```bash theme={null}
  curl -i https://api.hyperbrowser.ai/x402/session \
    -H "Content-Type: application/json" \
    -d '{"timeoutMinutes": 5}'
  ```

  A valid unpaid request returns `402 Payment Required`. The `PAYMENT-REQUIRED` header contains base64-encoded JSON with the accepted networks, assets, amount, and recipient.

  ### 2. Sign and retry

  Use your X402 client to generate a signed payment authorization from those requirements. Set `PAYMENT_SIGNATURE` to the encoded authorization returned by your client, then retry with the same request body:

  ```bash theme={null}
  curl --fail-with-body https://api.hyperbrowser.ai/x402/session \
    -H "Content-Type: application/json" \
    -H "PAYMENT-SIGNATURE: ${PAYMENT_SIGNATURE}" \
    -d '{"timeoutMinutes": 5}' \
    -o session.json
  ```

  Hyperbrowser verifies the payment authorization, creates the browser, and settles payment before returning its connection details. The successful response also includes a `PAYMENT-RESPONSE` header with settlement information.
</Accordion>

## Session response

The example below shows the shape of `session.json`; the URL hosts and tokens are illustrative:

```json theme={null}
{
  "id": "a52c49a1-dc81-4730-bac7-3e966f4d10c9",
  "wsEndpoint": "wss://connect.example.com/?token=CONNECT_TOKEN",
  "webdriverEndpoint": "https://connect.example.com/webdriver",
  "liveUrl": "https://live.example.com/?token=LIVE_TOKEN",
  "computerActionEndpoint": "https://connect.example.com/computer-action?token=ACTION_TOKEN",
  "token": "SESSION_TOKEN",
  "managementToken": "MANAGEMENT_TOKEN",
  "expiresAt": "2026-10-06T12:05:00.000Z"
}
```

Save the successful response: it contains the credentials needed to use this browser. The session token does not grant access to account management APIs.

## Use the browser

| Response field | Usage |
| - | - |
| `wsEndpoint` | Connect through CDP with Playwright, Puppeteer, or another compatible client. Authentication is already in the URL. |
| `webdriverEndpoint` and `token` | Connect with Selenium/WebDriver, sending `token` in the `x-hyperbrowser-token` header. |
| `liveUrl` | Open the browser's live view. Interaction is disabled when `viewOnlyLiveView` is `true`. |
| `computerActionEndpoint` | Send mouse, keyboard, and screenshot requests directly to the returned endpoint. Authentication is already in the URL. See the [computer actions cURL examples](/docs/sessions/computer-actions#using-curl). |
| `managementToken` | Authorize the X402 get and stop endpoints for this session. Valid for 24 hours from purchase. |
| `expiresAt` | The returned session expiry timestamp, based on the requested timeout. |

For example, install `playwright-core` and `tsx` to run the TypeScript example using the saved response:

```bash theme={null}
npm install playwright-core
npm install --save-dev tsx
```

Save this as `use-session.ts` and run it with `npx tsx use-session.ts`:

```typescript theme={null}
import { readFile } from "node:fs/promises";
import { chromium } from "playwright-core";

async function main() {
  const session: { wsEndpoint: string } = JSON.parse(
    await readFile("session.json", "utf8")
  );
  const browser = await chromium.connectOverCDP(session.wsEndpoint);

  try {
    const context = browser.contexts()[0];
    const page = context.pages()[0] ?? await context.newPage();
    await page.goto("https://example.com");
    console.log(await page.title());
    await page.screenshot({ path: "page.png" });
  } finally {
    await browser.close();
  }
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});
```

Use the returned URLs directly. The regular SDK's `sessions.create`, `sessions.get`, and `sessions.stop` methods use account authentication and cannot be authenticated with this session token.

## Get session status and stop the browser

Use the `managementToken` from the purchase response as a bearer token. These endpoints are free and require no additional X402 payment or Hyperbrowser API key. The token authorizes only the purchased session and remains valid for 24 hours, including after the browser stops or times out.

Read the saved response with `jq`, then get the session's status:

```bash theme={null}
SESSION_ID=$(jq -er '.id' session.json)
MANAGEMENT_TOKEN=$(jq -er '.managementToken' session.json)

curl --fail-with-body -sS \
  "https://api.hyperbrowser.ai/x402/session/${SESSION_ID}" \
  -H "Authorization: Bearer ${MANAGEMENT_TOKEN}"
```

The response contains `id`, `status`, `startTime`, `endTime`, `timeoutMinutes`, and the original `expiresAt`. `startTime` and `endTime` are Unix timestamps in milliseconds, or `null` when unavailable. Get does not reissue connection credentials; keep the creation response to reconnect.

Stop the session using the same variables:

```bash theme={null}
curl --fail-with-body -sS -X PUT \
  "https://api.hyperbrowser.ai/x402/session/${SESSION_ID}/stop" \
  -H "Authorization: Bearer ${MANAGEMENT_TOKEN}"
```

A successful stop returns `{ "success": true }`. Stopping an already closed or errored session also succeeds.

The browser's `token` and the tokens in connection or live-view URLs cannot authorize these management endpoints. The `managementToken` cannot authorize browser connections or regular account APIs.

See the [get session reference](/docs/api-reference/get-an-x402-session) and [stop session reference](/docs/api-reference/stop-an-x402-session) for response codes.

## Supported options

All fields are optional. Only `timeoutMinutes` changes the price; the other supported preferences do not add a surcharge.

| Field | Default | Constraints |
| - | - | - |
| `screen` | `{ "width": 1280, "height": 720 }` | Width from 500 to 3840; height from 360 to 2160. An omitted dimension uses its default. |
| `viewOnlyLiveView` | `false` | Make the live-view link read-only. CDP, WebDriver, and the computer action endpoint still allow control. |
| `timeoutMinutes` | `30` | Integer from 5 to 60. Determines the session duration, upfront price, and connection token lifetime. |

Example request body:

```json theme={null}
{
  "screen": { "width": 1920, "height": 1080 },
  "viewOnlyLiveView": true,
  "timeoutMinutes": 5
}
```

Web recording is disabled. Other regular session parameters are not accepted, including proxy settings, CAPTCHA solving, profiles, extensions, static IPs, snapshots, saved downloads, browser arguments, memory sizes, and custom token lifetimes. Unknown fields and invalid option combinations return `400` before payment verification.

## Lifetime and retries

* The browser has a maximum lifetime set by `timeoutMinutes`. Values below `5` or above `60` are not supported.
* By default, disconnecting a CDP client stops the session. To reconnect later, add `keepAlive=true` to the WebSocket URL before connecting. This does not extend the timeout, and closing all browser pages can still stop the session. See [session lifecycle](/docs/sessions/lifecycle) for connection behavior.
* Use the X402 get and stop endpoints above to check status or end a session. There are no X402 list, update, or extend endpoints.
* One payment authorization can create only one session. Reusing a reserved authorization returns `409`, including while its first request is still running.
* If a request fails before settlement, such as a capacity rejection during creation, the unexpired authorization can be retried. After settlement has been attempted, the authorization stays reserved even if the response is an error. If settlement fails, the server attempts to stop the browser and does not return its connection details.

See the [X402 session API reference](/docs/api-reference/create-a-session-with-x402-payment) for headers and response codes, or the [X402 overview](/docs/integrations/x402/overview) for per-request Fetch and Search payments.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.