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

# x402 quickstart

> Create pay-per-use browser sessions with crypto payments

## Quick start

<Steps>
  <Step title="Install dependencies">
    ```bash theme={null}
    npm install viem x402
    ```
  </Step>

  <Step title="Create a session">
    Run the following with your wallet's private key (requires USDC on Base):

    ```bash theme={null}
    PRIVATE_KEY=0x... npx tsx scripts/test-with-wallet.ts
    ```
  </Step>
</Steps>

## API reference

### Create session

Creates a new browser session with prepaid time.

```
POST /browser/session/create
```

**Request Body:**

```json theme={null}
{
  "estimatedMinutes": 30
}
```

<Tabs>
  <Tab title="First Response (402)">
    When you first make a request, you'll receive a 402 Payment Required response with payment details:

    ```json theme={null}
    {
      "x402Version": 1,
      "accepts": [{
        "scheme": "exact",
        "network": "base",
        "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
        "maxAmountRequired": "500000",
        "payTo": "0x...",
        "resource": "https://x402.browserbase.com/browser/session/create"
      }]
    }
    ```
  </Tab>

  <Tab title="With Payment (200)">
    After sending the payment header, you'll receive your session details:

    ```json theme={null}
    {
      "sessionId": "abc-123",
      "connectUrl": "wss://connect.browserbase.com/...",
      "paidMinutes": 30,
      "expiresAt": "2025-12-03T18:00:00Z",
      "pricing": {
        "ratePerHour": 0.12,
        "amountPaid": 0.06,
        "currency": "USDC"
      }
    }
    ```
  </Tab>
</Tabs>

### Get session status

Check the status of an active session.

```
GET /browser/session/:id/status
```

**Response:**

```json theme={null}
{
  "sessionId": "abc-123",
  "status": "active",
  "usage": {
    "minutesPaid": 30,
    "minutesUsed": 5,
    "minutesRemaining": 25
  },
  "expiresAt": "2025-12-03T18:00:00Z"
}
```

### Extend session

Add more time to an active session.

```
POST /browser/session/:id/extend
```

**Request Body:**

```json theme={null}
{
  "additionalMinutes": 15
}
```

<Note>
  Extending a session requires another x402 payment for the additional time.
</Note>

### Terminate session

End a session early. Unused time may be eligible for refund.

```
POST /browser/session/:id/terminate
```

**Response:**

```json theme={null}
{
  "sessionId": "abc-123",
  "finalStatus": "terminated",
  "usage": {
    "minutesPaid": 30,
    "minutesUsed": 10
  },
  "refund": {
    "eligible": true,
    "amount": 0.33,
    "currency": "USDC"
  }
}
```

## Making x402 payments

<Tabs>
  <Tab title="x402 Package (Recommended)">
    Use the x402 package for full control over the payment flow:

    ```typescript theme={null}
    import { privateKeyToAccount } from "viem/accounts";
    import { getAddress } from "viem";
    import { exact } from "x402/schemes";

    const account = privateKeyToAccount("0x...");

    // 1. Get payment requirements
    const res = await fetch("https://x402.browserbase.com/browser/session/create", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ estimatedMinutes: 30 }),
    });

    const { accepts } = await res.json();
    const req = accepts[0];

    // 2. Create payment header
    const paymentHeader = await exact.evm.createPaymentHeader(account, 1, {
      scheme: req.scheme,
      network: req.network,
      maxAmountRequired: req.maxAmountRequired,
      resource: req.resource,
      description: req.description,
      mimeType: req.mimeType,
      payTo: getAddress(req.payTo),
      maxTimeoutSeconds: req.maxTimeoutSeconds,
      asset: getAddress(req.asset),
      extra: req.extra,
    });

    // 3. Send with payment
    const session = await fetch("https://x402.browserbase.com/browser/session/create", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-PAYMENT": paymentHeader,
      },
      body: JSON.stringify({ estimatedMinutes: 30 }),
    }).then(r => r.json());

    console.log(session.connectUrl); // wss://connect.browserbase.com/...
    ```
  </Tab>

  <Tab title="x402-fetch (Automatic)">
    Use `x402-fetch` for automatic payment handling:

    ```typescript theme={null}
    import { wrapFetch } from "x402-fetch";
    import { privateKeyToAccount } from "viem/accounts";

    const account = privateKeyToAccount("0x...");
    const x402Fetch = wrapFetch(fetch, account);

    // Payments are handled automatically
    const session = await x402Fetch("https://x402.browserbase.com/browser/session/create", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ estimatedMinutes: 30 }),
    }).then(r => r.json());

    console.log(session.connectUrl); // wss://connect.browserbase.com/...
    ```

    <Tip>
      The `x402-fetch` wrapper automatically handles the 402 response, signs the payment, and retries the request with the payment header.
    </Tip>
  </Tab>
</Tabs>

## Using your session

Once you have a `connectUrl`, connect with Playwright or Puppeteer:

<CodeGroup>
  ```typescript Playwright theme={null}
  import { chromium } from "playwright";

  const browser = await chromium.connectOverCDP(session.connectUrl);
  const page = browser.contexts()[0].pages()[0];

  await page.goto("https://example.com");
  await page.screenshot({ path: "screenshot.png" });

  await browser.close();
  ```

  ```typescript Puppeteer theme={null}
  import puppeteer from "puppeteer-core";

  const browser = await puppeteer.connect({
    browserWSEndpoint: session.connectUrl,
  });
  const page = (await browser.pages())[0];

  await page.goto("https://example.com");
  await page.screenshot({ path: "screenshot.png" });

  await browser.close();
  ```
</CodeGroup>

## Further reading

<CardGroup cols={3}>
  <Card title="x402 Protocol" icon="globe" href="https://x402.org">
    Learn about the x402 payment protocol
  </Card>

  <Card title="Get USDC on Base" icon="coins" href="https://app.uniswap.org">
    Bridge or swap tokens to get USDC on Base
  </Card>

  <Card title="Browserbase Docs" icon="book" href="https://docs.browserbase.com">
    Explore more Browserbase features
  </Card>
</CardGroup>
