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

# Long sessions

> Keep sessions running longer and survive disconnects with keep alive and custom timeouts

<CardGroup cols={2}>
  <Card title="Keep Alive" icon="plug" href="/platform/browser/long-sessions/keep-alive">
    Keep sessions available after disconnects so you can reconnect without starting over.
  </Card>

  <Card title="Timeout" icon="clock" href="/platform/browser/long-sessions/timeouts">
    Extend session duration beyond the default timeout for long-running tasks.
  </Card>
</CardGroup>

By default, Browserbase sessions automatically terminate in two scenarios:

1. When a session disconnects
2. When the session reaches its timeout

This behavior optimizes resource utilization and session management, but you may need sessions that run longer or survive disconnections.

Browserbase offers session keep alive and custom timeout to address this need.

## Two ways to extend sessions

| Feature                                                          | Problem it solves                                              |
| ---------------------------------------------------------------- | -------------------------------------------------------------- |
| [**Session Timeouts**](/platform/browser/long-sessions/timeouts) | "I need my session to run longer than the default"             |
| [**Keep Alive**](/platform/browser/long-sessions/keep-alive)     | "I need to disconnect and reconnect without ending my session" |

### When to use each

**Timeouts** extend how long a session can run before it automatically terminates. Use this when you have long-running tasks that exceed the default timeout.

**Keep Alive** lets you disconnect and reconnect to the same session. Use this when your workflow involves multiple connections, when you need resilience against network issues, or when you want to reuse the same session for multiple runs.

### Using both together

If you need a session that both survives disconnects and runs for an extended period, configure both options:

```typescript theme={null}
const session = await bb.sessions.create({
  keepAlive: true,
  timeout: 3600, // 1 hour
});
```

<Note>
  Session keep alive is only available on paid plans.
</Note>

## Why keep sessions alive?

Custom timeouts and session keep alive support a broad spectrum of use cases. Key benefits include:

* Avoid interrupting long-running tasks and workflows.
* Connect, disconnect, and reconnect to the same session.
* Keep working with a session without worrying about it timing out.
* Reusing existing sessions is more performant than creating new ones.

<Note>
  **Looking for cloud-deployed execution?** If you don't need persistent sessions or reconnection capabilities, consider [Functions](/platform/runtime/overview) for on-demand browser agents. Functions automatically manage session lifecycle and are ideal for webhooks, scheduled tasks, and API endpoints.
</Note>

## Keep alive sessions

The `keepAlive` feature allows you to keep sessions alive across disconnects, permitting you to continue using it as long as needed.

### Create a keep alive session

Setting `keepAlive` to `true` will keep the session available for later use. You can reconnect to the keep alive session using the same connection URL as the original session.

Here's an example of how to keep a session alive:

<Tabs>
  <Tab title="Node.js">
    ```typescript SDK theme={null}
    const bb = new Browserbase({ apiKey: process.env.BROWSERBASE_API_KEY! });
    const session = await bb.sessions.create({
      keepAlive: true,
    });
    ```
  </Tab>

  <Tab title="Python">
    ```python SDK theme={null}
    bb = Browserbase(api_key=os.environ["BROWSERBASE_API_KEY"])
    session = bb.sessions.create(
      keep_alive=True
    )
    ```
  </Tab>
</Tabs>

Next time you run the script, you can reconnect to the same session after a disconnect, reusing it for multiple runs.

### Stop a keep alive session

To stop the session, use the Browserbase API or SDK:

<Tabs>
  <Tab title="Node.js">
    <CodeGroup>
      ```typescript SDK theme={null}
      import Browserbase from "browserbase";

      const BROWSERBASE_API_KEY = process.env.BROWSERBASE_API_KEY!;

      const bb = new Browserbase({
        apiKey: BROWSERBASE_API_KEY,
      });

      // Create a session with keep alive set.
      // Then, end it by closing it.
      (async () => {
        const session = await bb.sessions.create({
          keepAlive: true,
        });

        await bb.sessions.update(session.id, {
          status: "REQUEST_RELEASE",
        });
      })();
      ```

      ```typescript API theme={null}
      const options = {
        method: "POST",
        headers: {
          "X-BB-API-Key": "<your-api-key>",
          "Content-Type": "application/json",
        },
        body: '{"keepAlive": true, "sessionId": "<your-session-id>", "status": "REQUEST_RELEASE"}',
      };

      fetch("https://api.browserbase.com/v1/sessions", options)
        .then((response) => response.json())
        .then((response) => console.log(response))
        .catch((err) => console.error(err));
      ```
    </CodeGroup>
  </Tab>

  <Tab title="Python">
    <CodeGroup>
      ```python SDK theme={null}
      from browserbase import Browserbase
      import os

      # Initialize the SDK
      BROWSERBASE_API_KEY = os.environ["BROWSERBASE_API_KEY"]

      bb = Browserbase(api_key=BROWSERBASE_API_KEY)

      # Create a session with keep alive set

      session = bb.sessions.create(keep_alive=True)

      # Manually complete the session to end it

      bb.sessions.update(session.id, status="REQUEST_RELEASE")
      ```

      ```python API theme={null}
      # Stop a session
      import os
      from pprint import pprint

      import requests

      API_KEY = os.environ["BROWSERBASE_API_KEY"]

      SESSION_ID = "<The id of the session to stop>"

      headers = {"x-bb-api-key": API_KEY}
      json = {
          "status": "REQUEST_RELEASE",
      }

      response = requests.post(
          f"https://api.browserbase.com/v1/sessions/{SESSION_ID}",
          json=json,
          headers=headers,
      )

      # Raise an exception if there wasn't a good response from the endpoint.
      response.raise_for_status()

      # print the response
      pprint(response.json())
      ```
    </CodeGroup>
  </Tab>
</Tabs>

<Note>
  Stop your keep alive sessions explicitly when no longer
  needed. They'll time out eventually, but you may be charged for the unneeded
  browser minutes.
</Note>

## Session timeouts

After the script exceeds the default timeout, you'll see a `TimeoutError`: `Timeout _____ms exceeded`

Browserbase has project-wide settings for session timeout. You can change the session timeout to a different value in the toggle.

<Frame>
  <img src="https://mintcdn.com/browserbase/Qn5OB0mYcUstQ-qY/images/long-running-sessions/defaulttimeout.png?fit=max&auto=format&n=Qn5OB0mYcUstQ-qY&q=85&s=ff72c98040cd5551fb643356b2d41a7b" alt="" width="2517" height="1533" data-path="images/long-running-sessions/defaulttimeout.png" />
</Frame>

<Frame>
  <img style={{ maxHeight:"300px" }} src="https://mintcdn.com/browserbase/m1Ny8qOvNHvtrY7y/images/long-running-sessions/toggle.png?fit=max&auto=format&n=m1Ny8qOvNHvtrY7y&q=85&s=be3ed147f0ea4bfa4b48f901aeb0a500" width="936" height="660" data-path="images/long-running-sessions/toggle.png" />
</Frame>

### Custom session timeout

You can also set a custom timeout for a created session through code.

If you'd like to set a custom timeout that isn't shown in the toggle, set it in the `createSession` function.

To set a custom timeout for your session, specify the `timeout` option in the API request body or
with the SDK.

<Tabs>
  <Tab title="Node.js">
    <CodeGroup>
      ```typescript SDK theme={null}
      import Browserbase from "browserbase";

      const BROWSERBASE_API_KEY = process.env.BROWSERBASE_API_KEY!;

      const bb = new Browserbase({
        apiKey: BROWSERBASE_API_KEY,
      });

      // Creates a session with a timeout of 3600 seconds
      (async () => {
        const session = await bb.sessions.create({
          timeout: 3600,
        });
      })();
      ```

      ```typescript API theme={null}
      const options = {
        method: "POST",
        headers: {
          "X-BB-API-Key": "<your-api-key>",
          "Content-Type": "application/json",
        },
        body: '{"timeout": 3600}',
      };

      fetch("https://api.browserbase.com/v1/sessions", options)
        .then((response) => response.json())
        .then((response) => console.log(response))
        .catch((err) => console.error(err));
      ```
    </CodeGroup>
  </Tab>

  <Tab title="Python">
    <CodeGroup>
      ```python SDK theme={null}
      from browserbase import Browserbase
      import os

      BROWSERBASE_API_KEY = os.environ["BROWSERBASE_API_KEY"]

      bb = Browserbase(
          api_key=BROWSERBASE_API_KEY,
      )

      # Creates a session with a timeout of 3600 seconds
      session = bb.sessions.create(
          api_timeout=3600
      )
      ```

      ```python API theme={null}
      import os
      from pprint import pprint

      import requests

      BROWSERBASE_API_KEY = os.environ["BROWSERBASE_API_KEY"]

      headers = {"x-bb-api-key": BROWSERBASE_API_KEY}
      json = {
          "api_timeout": 3600,
      }

      response = requests.post(
          "https://api.browserbase.com/v1/sessions", json=json, headers=headers
      )

      # Raise an exception if there wasn't a good response from the endpoint.
      response.raise_for_status()

      # print the response
      pprint(response.json())
      ```
    </CodeGroup>
  </Tab>
</Tabs>

Here the timeout has been set to 3600 seconds (1 hour), overriding the default. That means
that unless explicitly closed beforehand, the session will continue running for an hour before
terminating. At disconnect, it will end.

Setting a custom timeout won't keep the session alive after disconnecting. To reconnect
to a session after disconnecting, configure it for keep alive.

<Note>
  The maximum duration of a session is 6 hours. Once a session times out, it can
  no longer be used.
</Note>

## Related guides

<CardGroup cols="2">
  <Card title="Session timeouts" icon="clock" href="/platform/browser/long-sessions/timeouts">
    Extend session duration beyond the default
  </Card>

  <Card title="Keep alive" icon="plug" href="/platform/browser/long-sessions/keep-alive">
    Survive disconnects and reconnect to sessions
  </Card>

  <Card title="Session inspector" icon="network-wired" href="/platform/browser/observability/observability">
    Watch your session in real time and debug issues after the session has ended
  </Card>

  <Card title="Browserbase Functions" icon="bolt" href="/platform/runtime/overview">
    Deploy browser agents with automatic session management
  </Card>
</CardGroup>
