> ## 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.

> ## Agent Instructions
> Authenticate REST, SDK, and CLI requests with the `x-api-key` header using the `HYPERBROWSER_API_KEY` environment variable (create keys at https://app.hyperbrowser.ai).
> Always stop browser sessions (`sessions.stop(id)` / `PUT /api/session/{id}/stop`) and sandboxes (`sandboxes.stop(id)` / `PUT /api/sandbox/{id}/stop`) in `try`/`finally` blocks to avoid idle billing.
> Choose the right surface: use Web API (`/api/web/fetch`, `batch-fetch`, `crawl`, `search`) for stateless reading and extraction (prefer it over legacy `/api/scrape`); Browser Sessions (`/api/session`) for interactive, authenticated, or Playwright/Puppeteer workflows; Cloud Agents (`/api/task/*`) for autonomous browser tasks; and Sandboxes (`/api/sandbox`) for isolated Linux or macOS code execution.
> Use `@hyperbrowser/sdk` for Node.js/TypeScript, `hyperbrowser` 1.0+ typed-dict request params for Python (avoid legacy Pydantic request classes), the unified `hx` CLI for terminal workflows, and hosted OAuth MCP at `https://mcp.hyperbrowser.ai/mcp/web` (web tools; use `https://mcp.hyperbrowser.ai/mcp` only when browser, sandbox, admin, and usage tools are needed).

# Authenticated Playwright Scraping

> Log in once, persist browser state in a Hyperbrowser Profile, and reuse it across Stealth Playwright scraping runs

This recipe creates a persistent [Profile](https://hyperbrowser.ai/docs/sessions/profiles.md), logs in once with [Stealth](https://hyperbrowser.ai/docs/sessions/stealth.md) and managed proxies, and reuses the saved cookies and storage on subsequent scraping runs without re-authenticating.

**Required API key scopes:** `profiles.create`, `browser.sessions.create`, `browser.sessions.stop`.

## Prerequisites

* `HYPERBROWSER_API_KEY`, `PORTAL_EMAIL`, and `PORTAL_PASSWORD` exported in your shell.
* `@hyperbrowser/sdk` + `playwright-core` (TypeScript) or `hyperbrowser` + `playwright` (Python) installed.

***

## Step 1: Seed an Authenticated Profile

Run an initial session with `persistChanges: true`.

```typescript TypeScript theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { Hyperbrowser } from "@hyperbrowser/sdk";
import { chromium } from "playwright-core";

const client = new Hyperbrowser({ apiKey: process.env.HYPERBROWSER_API_KEY });

async function seedProfile() {
  const profile = await client.profiles.create({ name: "portal-auth" });
  const session = await client.sessions.create({
    useStealth: true,
    useProxy: true,
    proxyCountry: "US",
    profile: {
      id: profile.id,
      persistChanges: true,
    },
  });

  try {
    const browser = await chromium.connectOverCDP(session.wsEndpoint);
    const page = browser.contexts()[0].pages()[0];
    await page.goto("https://app.example.com/login", { waitUntil: "networkidle" });
    await page.fill('input[name="email"]', process.env.PORTAL_EMAIL!);
    await page.fill('input[name="password"]', process.env.PORTAL_PASSWORD!);
    await page.click('button[type="submit"]');
    await page.waitForURL("**/dashboard");
    console.log("Profile seeded:", profile.id);
    return profile.id;
  } finally {
    // Stopping cleanly flushes the persisted profile archive
    await client.sessions.stop(session.id);
  }
}
```

```python Python theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import os
from hyperbrowser import Hyperbrowser
from playwright.sync_api import sync_playwright

client = Hyperbrowser(api_key=os.environ["HYPERBROWSER_API_KEY"])


def seed_profile() -> str:
    profile = client.profiles.create({"name": "portal-auth"})
    session = client.sessions.create({
        "use_stealth": True,
        "use_proxy": True,
        "proxy_country": "US",
        "profile": {
            "id": profile.id,
            "persist_changes": True,
        },
    })

    try:
        with sync_playwright() as p:
            browser = p.chromium.connect_over_cdp(session.ws_endpoint)
            page = browser.contexts[0].pages[0]
            page.goto("https://app.example.com/login", wait_until="networkidle")
            page.fill('input[name="email"]', os.environ["PORTAL_EMAIL"])
            page.fill('input[name="password"]', os.environ["PORTAL_PASSWORD"])
            page.click('button[type="submit"]')
            page.wait_for_url("**/dashboard")
            print("Profile seeded:", profile.id)
            return profile.id
    finally:
        client.sessions.stop(session.id)
```

***

## Step 2: Fan Out Read-Only Workers

For concurrent scraping, mount the seeded profile with `persistChanges: false` so parallel sessions never overwrite each other's saved state:

```typescript TypeScript theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
async function scrapePage(profileId: string, url: string) {
  const session = await client.sessions.create({
    useStealth: true,
    useProxy: true,
    profile: { id: profileId, persistChanges: false },
  });

  try {
    const browser = await chromium.connectOverCDP(session.wsEndpoint);
    const page = browser.contexts()[0].pages()[0];
    await page.goto(url, { waitUntil: "domcontentloaded" });
    return await page.locator("main").innerText();
  } finally {
    await client.sessions.stop(session.id);
  }
}
```

```python Python theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
def scrape_page(profile_id: str, url: str) -> str:
    session = client.sessions.create({
        "use_stealth": True,
        "use_proxy": True,
        "profile": {"id": profile_id, "persist_changes": False},
    })

    try:
        with sync_playwright() as p:
            browser = p.chromium.connect_over_cdp(session.ws_endpoint)
            page = browser.contexts[0].pages[0]
            page.goto(url, wait_until="domcontentloaded")
            return page.locator("main").inner_text()
    finally:
        client.sessions.stop(session.id)
```

> [!TIP]
>
> Want to keep credentials out of your application environment completely? Store them in [Secrets & Vaults](https://hyperbrowser.ai/docs/sandboxes/secrets.md) and use [Credential Fill](https://hyperbrowser.ai/docs/sessions/credentials.md) during Step 1.

## Expected output

* `seedProfile()` logs `Profile seeded: <profile-id>` and flushes the authenticated cookies and local storage into the profile when the session stops cleanly.
* Each `scrapePage()` worker boots already logged in and returns the rendered `<main>` text without overwriting the shared profile.

## Next Steps

* [Browser Profiles](https://hyperbrowser.ai/docs/sessions/profiles.md) — profile lifecycle, forking, and cleanup.
* [Credential Fill](https://hyperbrowser.ai/docs/sessions/credentials.md) — inject stored logins without exposing plaintext secrets to your app.


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