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

# Session Lifecycle

> Manage the lifecycle of your Hyperbrowser sessions

Every Hyperbrowser session follows a predictable lifecycle from creation to termination. Understanding this lifecycle helps you build reliable automation workflows and manage resources effectively.

## Session States

Sessions transition through these states:

* **`active`** - Session is running and ready to accept connections
* **`closed`** - Session has been terminated normally
* **`error`** - Session encountered an error and terminated unexpectedly

## Creating a Session

Create a new session with optional configuration.

<CodeGroup>
  ```typescript Node.js theme={null}
  import { Hyperbrowser } from "@hyperbrowser/sdk";

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

  // Create a new session
  const session = await client.sessions.create({
    screen: {
      width: 1920,
      height: 1080,
    }
  });

  console.log(`Session ${session.id} is ${session.status}`);
  console.log(`WebSocket endpoint: ${session.wsEndpoint}`);
  console.log(`Live view: ${session.liveUrl}`);
  ```

  ```python Python theme={null}
  from hyperbrowser import Hyperbrowser
  from hyperbrowser.models import CreateSessionParams, ScreenConfig

  client = Hyperbrowser(api_key="your-api-key")

  # Create a new session
  session = client.sessions.create(
      params=CreateSessionParams(
          screen=ScreenConfig(width=1920, height=1080)
      )
  )

  print(f"Session {session.id} is {session.status}")
  print(f"WebSocket endpoint: {session.ws_endpoint}")
  print(f"Live view: {session.live_url}")
  ```

  ```bash cURL theme={null}
  curl -X POST https://api.hyperbrowser.ai/api/session \
    -H "x-api-key: YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "timeoutMinutes": 30,
      "useUltraStealth": true
    }'
  ```
</CodeGroup>

## Getting Session Details

Retrieve current information about a specific session:

<CodeGroup>
  ```typescript Node.js theme={null}
  const session = await client.sessions.get("session-id");

  console.log("Session details:", {
    id: session.id,
    status: session.status,
    createdAt: session.createdAt,
    wsEndpoint: session.wsEndpoint,
    liveUrl: session.liveUrl,
  });
  ```

  ```python Python theme={null}
  session = client.sessions.get("session-id")

  print(f"Session details: {session.id} - {session.status}")
  print(f"Created at: {session.created_at}")
  print(f"WebSocket endpoint: {session.ws_endpoint}")
  print(f"Live view: {session.live_url}")
  ```

  ```bash cURL theme={null}
  curl -X GET https://api.hyperbrowser.ai/api/session/SESSION_ID \
    -H "x-api-key: YOUR_API_KEY"
  ```
</CodeGroup>

## Listing Sessions

Query all your sessions with optional filtering by status:

<CodeGroup>
  ```typescript Node.js theme={null}
  // List all sessions
  const response = await client.sessions.list({
    status: "active",
    page: 1,
  });

  console.log(`Total sessions: ${response.totalCount}`);
  console.log(`Showing page ${response.page} of ${Math.ceil(response.totalCount / response.perPage)}`);

  response.sessions.forEach((session) => {
    console.log(`- ${session.id} (${session.status})`);
  });
  ```

  ```python Python theme={null}
  # List all sessions
  from hyperbrowser.models import SessionListParams

  response = client.sessions.list(
      params=SessionListParams(
          status="active",
          page=1,
      )
  )

  print(f"Total sessions: {response.total_count}")
  print(f"Showing page {response.page}")

  for session in response.sessions:
      print(f"- {session.id} ({session.status})")
  ```

  ```bash cURL theme={null}
  # List active sessions
  curl -X GET "https://api.hyperbrowser.ai/api/sessions?status=active&page=1" \
    -H "x-api-key: YOUR_API_KEY"
  ```
</CodeGroup>

## Stopping a Session

Always stop sessions when you're done to free up resources:

<CodeGroup>
  ```typescript Node.js theme={null}
  // Stop a specific session
  await client.sessions.stop("session-id");

  console.log("Session stopped successfully");
  ```

  ```python Python theme={null}
  # Stop a specific session
  client.sessions.stop("session-id")

  print("Session stopped successfully")
  ```

  ```bash cURL theme={null}
  curl -X PUT https://api.hyperbrowser.ai/api/session/SESSION_ID/stop \
    -H "x-api-key: YOUR_API_KEY"
  ```
</CodeGroup>

<Tip>
  Stopping a session is idempotent - you can safely call it multiple times without errors.
</Tip>

## Complete Lifecycle Example

Here's a complete example demonstrating best practices for session management:

<CodeGroup>
  ```typescript Node.js theme={null}
  import { Hyperbrowser } from "@hyperbrowser/sdk";
  import { chromium } from "playwright-core";
  import { config } from "dotenv";

  config();

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

  const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

  async function runAutomation() {
    // 1. Create session with configuration
    console.log("Creating session...");
    const session = await client.sessions.create({
      acceptCookies: true,
    });
    console.log(`Session created: ${session.id}`);
    console.log(`Watch live: ${session.liveUrl}`);

    try {
      // 2. Connect with Playwright
      const browser = await chromium.connectOverCDP(session.wsEndpoint);
      const context = browser.contexts()[0];
      const page = context.pages()[0];

      // 3. Use the session
      console.log("Waiting 5 seconds before navigating to example.com");
      await sleep(5000);
      await page.goto("https://example.com");
      const title = await page.title();
      console.log(`Page title: ${title}`);
      console.log("Waiting 5 seconds before stopping the session");
      await sleep(5000);
    } catch (error) {
      console.error("Automation failed:", error);
    } finally {
      // 4. Always stop the session
      console.log("Stopping session...");
      await client.sessions.stop(session.id);
      console.log("Session stopped");
    }
  }

  runAutomation().catch(console.error);
  ```

  ```python Python theme={null}
  from hyperbrowser import Hyperbrowser
  from hyperbrowser.models import CreateSessionParams
  from playwright.sync_api import sync_playwright
  from dotenv import load_dotenv
  import os
  import time

  load_dotenv()

  client = Hyperbrowser(api_key=os.getenv("HYPERBROWSER_API_KEY"))


  def run_automation():
      # 1. Create session with configuration
      print("Creating session...")
      session = client.sessions.create(
          params=CreateSessionParams(
              accept_cookies=True,
          )
      )
      print(f"Session created: {session.id}")
      print(f"Watch live: {session.live_url}")

      try:
          # 2. Connect with Playwright
          with sync_playwright() as p:
              browser = p.chromium.connect_over_cdp(session.ws_endpoint)
              context = browser.contexts[0]
              page = context.pages[0]

              # 3. Use the session
              print("Waiting 5 seconds before navigating to example.com")
              time.sleep(5)
              page.goto("https://example.com")
              title = page.title()
              print(f"Page title: {title}")
              print("Waiting 5 seconds before stopping the session")
              time.sleep(5)

      except Exception as error:
          print(f"Automation failed: {error}")
      finally:
          # 4. Always stop the session
          print("Stopping session...")
          client.sessions.stop(session.id)
          print("Session stopped")


  if __name__ == "__main__":
      run_automation()
  ```
</CodeGroup>

## Automatic Timeout

Sessions automatically stop after some time based on their timeout. By default, this is based on your team's default Session Timeout setting which you can change on the [Settings page](https://app.hyperbrowser.ai/settings). You can also configure the timeout per session during session creation:

<CodeGroup>
  ```typescript Node.js theme={null}
  const session = await client.sessions.create({
    timeoutMinutes: 15,
  });
  ```

  ```python Python theme={null}
  from hyperbrowser.models import CreateSessionParams

  session = client.sessions.create(
      params=CreateSessionParams(
          timeout_minutes=15
      )
  )
  ```

  ```bash cURL theme={null}
  curl -X POST https://api.hyperbrowser.ai/api/session \
    -H "x-api-key: YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{"timeoutMinutes": 15}'
  ```
</CodeGroup>

<Warning>
  Don't rely solely on automatic timeouts. Always explicitly stop sessions in your cleanup logic to avoid unexpected charges and ensure proper resource management.
</Warning>

## Error Handling

Use try-finally blocks to guarantee sessions are stopped, even when errors occur:

<CodeGroup>
  ```typescript Node.js theme={null}
  async function safeAutomation() {
    let session;
    
    try {
      session = await client.sessions.create();
      
      // Your automation code here
      await doSomething(session);
      
    } catch (error) {
      console.error("Automation failed:", error);
    } finally {
      // This always runs, whether success or failure
      if (session) {
        await client.sessions.stop(session.id);
      }
    }
  }
  ```

  ```python Python theme={null}
  def safe_automation():
      session = None
      
      try:
          session = client.sessions.create()
          
          # Your automation code here
          do_something(session)

      except Exception as error:
          print(f"Automation failed: {error}")
      finally:
          # This always runs, whether success or failure
          if session:
              client.sessions.stop(session.id)
  ```
</CodeGroup>

## Long Running Sessions

By default, when you disconnect from a session with an automation library like Playwright or Puppeteer, your session will automatically stop. To keep your session alive across disconnects, you can add the `&keepAlive=true` query parameter to your session's WebSocket endpoint when you connect via CDP. This will keep your session alive until it times out based on the session's timeout value (default team setting or `timeoutMinutes` parameter passed in when you create the session) or if you stop the session manually via the API.

<Note>
  The `keepAlive` won't work if all the pages in the browser are closed. If all pages get closed, then the session will automatically stop.
</Note>

<CodeGroup>
  ```typescript Node.js theme={null}
  import { Hyperbrowser } from "@hyperbrowser/sdk";
  import { chromium } from "playwright-core";
  import { config } from "dotenv";

  config();

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

  const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

  async function runAutomation() {
    // 1. Create session with configuration
    console.log("Creating session...");
    const session = await client.sessions.create({
      acceptCookies: true,
    });
    console.log(`Session created: ${session.id}`);
    console.log(`Watch live: ${session.liveUrl}`);

    try {
      // 2. Connect with Playwright and add the keepAlive parameter
      const browser = await chromium.connectOverCDP(
        `${session.wsEndpoint}&keepAlive=true`
      );
      const context = browser.contexts()[0];
      const page = context.pages()[0];

      // 3. Use the session
      console.log("Waiting 5 seconds before navigating to example.com");
      await sleep(5000);
      await page.goto("https://example.com");
      const title = await page.title();
      console.log(`Page title: ${title}`);
      console.log("Waiting 5 seconds before disconnecting from the browser");
      await sleep(5000);
      await browser.close();
    } catch (error) {
      console.error("Automation failed:", error);
    }
  }

  runAutomation().catch(console.error);
  ```

  ```python Python theme={null}
  from hyperbrowser import Hyperbrowser
  from hyperbrowser.models import CreateSessionParams
  from playwright.sync_api import sync_playwright
  from dotenv import load_dotenv
  import os
  import time

  load_dotenv()

  client = Hyperbrowser(api_key=os.getenv("HYPERBROWSER_API_KEY"))


  def run_automation():
      # 1. Create session with configuration
      print("Creating session...")
      session = client.sessions.create(
          params=CreateSessionParams(
              accept_cookies=True,
          )
      )
      print(f"Session created: {session.id}")
      print(f"Watch live: {session.live_url}")

      try:
          # 2. Connect with Playwright and add the keepAlive parameter
          with (
              sync_playwright() as p
          ):  # Python's context manager automatically disconnects from the browser once the code inside has been executed
              browser = p.chromium.connect_over_cdp(
                  f"{session.ws_endpoint}&keepAlive=true"
              )
              context = browser.contexts[0]
              page = context.pages[0]

              # 3. Use the session
              print("Waiting 5 seconds before navigating to example.com")
              time.sleep(5)
              page.goto("https://example.com")
              title = page.title()
              print(f"Page title: {title}")
              print("Waiting 5 seconds before disconnecting from the browser")
              time.sleep(5)

      except Exception as error:
          print(f"Automation failed: {error}")


  if __name__ == "__main__":
      run_automation()
  ```
</CodeGroup>

## Best Practices

Follow these patterns to build reliable, cost-effective automation:

### 1. Always Use Try-Finally

Wrap session usage in try-finally blocks to guarantee cleanup:

```typescript theme={null}
let session;
try {
  session = await client.sessions.create();
  // ... use session
} finally {
  if (session) await client.sessions.stop(session.id);
}
```

### 2. Set Appropriate Timeouts

Match timeout to task duration. Add a buffer for unexpected delays:

* **Quick tasks**: 5-10 minutes
* **Data scraping**: 15-30 minutes
* **Long workflows**: 30-60 minutes

### 3. Monitor Session State

Check session status before long-running operations:

```typescript theme={null}
const session = await client.sessions.get(sessionId);
if (session.status !== 'active') {
  throw new Error('Session is no longer active');
}
```

### 4. Clean Up Orphaned Sessions

Periodically audit for abandoned sessions:

```typescript theme={null}
const response = await client.sessions.list({ status: 'active' });
// Review and stop any unexpected active sessions
```

### 5. Handle Network Failures

Network issues can leave sessions running. Always implement cleanup:

```typescript theme={null}
process.on('SIGTERM', async () => {
  if (session) await client.sessions.stop(session.id);
  process.exit(0);
});
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Connect with Puppeteer" icon="code" href="/sessions/puppeteer">
    Control sessions with Puppeteer
  </Card>

  <Card title="Connect with Playwright" icon="code" href="/sessions/playwright">
    Control sessions with Playwright
  </Card>

  <Card title="Profiles" icon="user" href="/sessions/profiles">
    Persist browser state across sessions
  </Card>

  <Card title="Recordings" icon="video" href="/sessions/recordings">
    Record and replay session activity
  </Card>
</CardGroup>
