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.
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
Create Session
Create Session
Create a new session using the REST API with explicit timeout and configuration control:
- JavaScript
- Python
- cURL
// 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);import requests
import json
# Configure session with explicit timeout and browser options
session_config = {
"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
response = requests.post(
"https://production-sfo.browserless.io/session",
headers={
"Content-Type": "application/json",
"Authorization": "Bearer YOUR_API_TOKEN",
},
json=session_config
)
session = response.json()
print(f"Session created: {session['id']}")
print(f"Connect URL: {session['connect']}")# Create session via REST API
curl -X POST "https://production-sfo.browserless.io/session" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-d '{
"ttl": 180000,
"stealth": true,
"headless": false,
"args": [
"--no-sandbox",
"--disable-dev-shm-usage",
"--disable-background-timer-throttling"
]
}'Connect to Session
Connect to Session
Use the session connect URL to connect your automation library to the created session:
- Puppeteer
- Python
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());import asyncio
from playwright.async_api import async_playwright
# Use the connect URL from session creation
connect_url = session['connect'] # From previous step
async def main():
async with async_playwright() as p:
# Connect to the existing session
browser = await p.chromium.connect_over_cdp(connect_url)
context = browser.contexts[0] # Use existing browser context
page = await context.new_page()
await page.goto("https://example.com")
# Set up session state that will persist across connections
await page.evaluate("localStorage.setItem('sessionData', 'persistent-api-value')")
print(f"Connected to session: {session['id']}")
print(f"Current URL: {await page.url()}")
asyncio.run(main())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 thesessionCloseURL
:- Javascript
- Python
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');import requests
def stop_session(session_close_url):
try:
response = requests.delete(session_close_url)
if response.ok:
result = response.json()
print(f"Session {session_close_url} stopped:", result)
return True
else:
print(f"Failed to stop session {session_close_url}:", response.status_code)
return False
except Exception as error:
print(f"Error stopping session {session_close_url}:", error)
return False
# Usage
stop_session('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:
Plan | Persisted Session Duration |
---|---|
Free | 1 day |
Prototyping | 7 days |
Starter | 30 days |
Scale | 90 days |
Enterprise | Custom |
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
Parameter | Type | Default | Description |
---|---|---|---|
ttl | number | 300000 | Time-to-live in ms (When the session data will expire) |
stealth | boolean | false | Enable stealth mode to avoid detection |
headless | boolean | true | Run browser in headless mode |
args | string[] | [] | Additional Chrome launch arguments |
proxy | object | null | Proxy 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: