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.
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. You can also configure the timeout per session during session creation:
Don’t rely solely on automatic timeouts. Always explicitly stop sessions in your cleanup logic to avoid unexpected charges and ensure proper resource management.
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.
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.
Copy
Ask AI
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);