Skip to main content
Version: v2

Persisting State

For more control over session lifecycle, you can use the REST API to explicitly create and manage sessions through HTTP endpoints. This approach provides programmatic session management with advanced control over session configuration and monitoring, and is designed for use cases requiring persistent state across longer periods of time. This method allows you to persist data for multiple days, depending on your plan, even when the browser is closed.

Sessions API Only

This document covers the Sessions API (REST API for explicit session management). For Browser Sessions using Browserless.reconnect CDP command, see Standard Sessions.

Persisting State Workflow

  1. Create Session

    Create Session

    Create a new session using the REST API with explicit timeout and configuration control:

    // Configure session with explicit timeout and browser options
    const sessionConfig = {
    ttl: 180000, // Session timeout: 3 minutes (180,000ms)
    stealth: true, // Enable stealth mode for bot detection bypass
    headless: false, // Run in headed mode for debugging
    args: [
    "--no-sandbox", // Required for containerized environments
    "--disable-dev-shm-usage", // Prevent shared memory issues
    "--disable-background-timer-throttling", // Maintain performance
    ],
    };

    // Create session via REST API
    const response = await fetch("https://production-sfo.browserless.io/session", {
    method: "POST",
    headers: {
    "Content-Type": "application/json",
    "Authorization": `Bearer YOUR_API_TOKEN`,
    },
    body: JSON.stringify(sessionConfig),
    });

    const session = await response.json();
    console.log("Session created:", session.id);
    console.log("Connect URL:", session.connect);
  2. Connect to Session

    Connect to Session

    Use the session connect URL to connect your automation library to the created session:

    import puppeteer from "puppeteer-core";

    // Use the connect URL from session creation
    const connectUrl = session.connect; // From previous step

    // Connect to the existing session
    const browser = await puppeteer.connect({
    browserWSEndpoint: connectUrl,
    });

    const pages = await browser.pages();
    const page = pages[0] || await browser.newPage();
    await page.goto("https://example.com");

    // Set up session state that will persist across connections
    await page.evaluate(() => {
    localStorage.setItem("sessionData", "persistent-api-value");
    });

    console.log("Connected to session:", session.id);
    console.log("Current URL:", await page.url());
  3. Close Session

    Close Session

    When you're finished with your session, properly close it to free up resources. Use the session.connect URL from the previous steps as the sessionCloseURL:

    const stopSession = async (sessionCloseURL) => {
    try {
    const response = await fetch(
    // https://production-sfo.browserless.io/e/123456/session/123456?token=YOUR_API_TOKEN
    sessionCloseURL,
    {
    method: 'DELETE',
    }
    );

    if (response.ok) {
    const result = await response.json();
    console.log(`Session ${sessionCloseURL} stopped:`, result);
    return true;
    } else {
    console.error(`Failed to stop session ${sessionCloseURL}:`, response.status);
    return false;
    }
    } catch (error) {
    console.error(`Error stopping session ${sessionCloseURL}:`, error);
    return false;
    }
    };

    // Usage
    await stopSession('https://production-sfo.browserless.io/e/123456/session/123456?token=YOUR_API_TOKEN');

Persisted session data duration

The data that can be persisted includes cache, cookies, localStorage, and session data. The length of time this data can be persisted depends on your plan:

PlanPersisted Session Duration
Free1 day
Prototyping7 days
Starter30 days
Scale90 days
EnterpriseCustom

You can also limit the time you want the data to be persisted by passing a ttl option to the session API, which will expire the session data before the plan limit if desired.

Session Configuration Options

ParameterTypeDefaultDescription
ttlnumber300000Time-to-live in ms (When the session data will expire)
stealthbooleanfalseEnable stealth mode to avoid detection
headlessbooleantrueRun browser in headless mode
argsstring[][]Additional Chrome launch arguments
proxyobjectnullProxy configuration

For the complete list of all available session configuration parameters, see the Session API documentation.

Next Steps

Ready to take your session management to the next level? Explore these key areas: