All Products
Search
Document Center

AgentBay:Browser persistence

Last Updated:Jun 04, 2026

Browser persistence lets you carry browser state—cookies, cache, local storage, and more—across AgentBay sessions, so each new session picks up where the last one left off instead of starting fresh.

How browser persistence works

Browser persistence creates a persistent browser environment by attaching a named context to your sessions. The context stores and restores the following data between sessions:

  • Cookies

  • Cache — HTTP response cache for faster page loads

  • Local storage — per-origin key-value storage (localStorage)

  • Session storage (sessionStorage)

  • Browser preferences — site-level settings and permissions

  • Installed extensions — when used with extension management

Benefits

  1. Reduces anti-bot detection: Sites see a returning user, not a fresh visitor, which makes automated sessions harder to detect and block.

  2. Faster page loads: Cached resources and cookies carry over, so pages load faster across sessions.

  3. Session continuity: Logged-in state, preferences, and in-progress workflows resume automatically across sessions.

  4. Consistent user experience: Site preferences and settings remain consistent across sessions.

Python examples

Create a session with persistence

The following example creates a named context and attaches it to a browser session with auto_upload=True. When the session ends, the browser state is automatically written back to the context.

from agentbay import AgentBay
from agentbay.session_params import CreateSessionParams, BrowserContext

# Initialize the AgentBay client
agent_bay = AgentBay(api_key="your_api_key")

# Create or get a persistence context
context_result = agent_bay.context.get("my-browser-context", create=True)
context = context_result.context

# Create a browser session with persistence
browser_context = BrowserContext(
    context_id=context.id,
    auto_upload=True
)

session_params = CreateSessionParams(
    image_id="browser-image-id",
    browser_context=browser_context
)

session_result = agent_bay.create(session_params)
session = session_result.session

Cookie persistence

This example uses two sessions to show cookie persistence end to end. The first session sets a cookie and then calls delete with sync_context=True to flush state back to the context. The second session reads back the same cookie.

import time
from agentbay import AgentBay
from agentbay.session_params import CreateSessionParams, BrowserContext
from agentbay.browser.browser import BrowserOption
from playwright.sync_api import sync_playwright

# Initialize AgentBay
agent_bay = AgentBay(api_key="your_api_key")

# Create a persistence context
context_result = agent_bay.context.get("cookie-demo-context", create=True)
context = context_result.context

# First session - set a cookie
browser_context = BrowserContext(
    context_id=context.id,
    auto_upload=True
)

params = CreateSessionParams(
    image_id="browser-image-id",
    browser_context=browser_context
)

session1 = agent_bay.create(params).session

# Set a cookie in the first session
session1.browser.initialize(BrowserOption())
endpoint_url = session1.browser.get_endpoint_url()

with sync_playwright() as p:
    browser = p.chromium.connect_over_cdp(endpoint_url)
    context_p = browser.contexts[0] if browser.contexts else browser.new_context()
    page = context_p.new_page()
    
    # Navigate and set the cookie
    page.goto("https://example.com")
    context_p.add_cookies([
        {
            "name": "session_cookie",
            "value": "session_value",
            "domain": "example.com",
            "path": "/",
        }
    ])
    
    browser.close()

# Delete the first session with context synchronization
agent_bay.delete(session1, sync_context=True)

# Second session - verify that the cookie is persisted
session2 = agent_bay.create(params).session

# Check the cookie in the second session
session2.browser.initialize(BrowserOption())
endpoint_url2 = session2.browser.get_endpoint_url()

with sync_playwright() as p:
    browser = p.chromium.connect_over_cdp(endpoint_url2)
    context_p = browser.contexts[0] if browser.contexts else browser.new_context()
    
    # Verify that the cookie is persisted
    cookies = context_p.cookies()
    print(f"Persisted cookies: {cookies}")
    
    browser.close()

TypeScript examples

Create a session with persistence

import { AgentBay, CreateSessionParams, BrowserContext } from 'wuying-agentbay-sdk';

// Initialize the AgentBay client
const agentBay = new AgentBay({ apiKey: "your_api_key" });

// Create or get a persistence context
const contextResult = await agentBay.context.get("my-browser-context", true);
const context = contextResult.context;

// Create a browser session with persistence
const browserContext: BrowserContext = {
    contextId: context.id,
    autoUpload: true
};

const params = new CreateSessionParams()
    .withImageId("browser-image-id")
    .withBrowserContext(browserContext);

const sessionResult = await agentBay.create(params);
const session = sessionResult.session;

Cookie persistence

import { AgentBay, CreateSessionParams, BrowserContext, BrowserOption } from 'wuying-agentbay-sdk';
import { chromium } from 'playwright';

// Initialize AgentBay
const agentBay = new AgentBay({ apiKey: "your_api_key" });

// Create a persistent context
const contextResult = await agentBay.context.get("cookie-demo-context", true);
const context = contextResult.context;

// First session - set a cookie
const browserContext: BrowserContext = {
    contextId: context.id,
    autoUpload: true
};

const params = new CreateSessionParams()
    .withImageId("browser-image-id")
    .withBrowserContext(browserContext);

const session1 = (await agentBay.create(params)).session;

// Set a cookie in the first session
await session1.browser.initializeAsync(new BrowserOption());
const endpointUrl = session1.browser.getEndpointUrl();

const browser = await chromium.connectOverCDP(endpointUrl);
const contextP = browser.contexts()[0] || await browser.newContext();
const page = await contextP.newPage();

// Navigate and set the cookie
await page.goto("https://example.com");
await contextP.addCookies([
    {
        name: "session_cookie",
        value: "session_value",
        domain: "example.com",
        path: "/",
    }
]);

await browser.close();

// Delete the first session with context synchronization
await agentBay.delete(session1, true);

// Second session - verify that the cookie is persisted
const session2 = (await agentBay.create(params)).session;

// Check the cookie in the second session
await session2.browser.initializeAsync(new BrowserOption());
const endpointUrl2 = session2.browser.getEndpointUrl();

const browser2 = await chromium.connectOverCDP(endpointUrl2);
const contextP2 = browser2.contexts()[0] || await browser2.newContext();

// Verify that the cookie is persisted
const cookies = await contextP2.cookies();
console.log(`Persisted cookies: ${JSON.stringify(cookies)}`);

await browser2.close();

Best practices

  1. Use descriptive context names: Name contexts based on their purpose, such as ecommerce-scraping and social-media-automation.

  2. Enable automatic uploads: Set auto_upload=True so browser state syncs back to the context when the session ends. Without this, changes made during the session are lost.

  3. Clean up resources: Delete sessions after operations are complete to release cloud resources.

  4. Handle errors: Check context_result.success and session_result.success before proceeding. Implement proper error handling for context operations.

  5. Reuse contexts across sessions: Pass the same context ID to multiple sessions to share state—logins, cookies, and preferences carry over to maintain continuity.

Advanced features

Context synchronization policies

Use SyncPolicy to control which files are uploaded or extracted during synchronization. The white_list parameter selects specific paths to sync; black_list excludes paths from sync.

from agentbay.context_sync import SyncPolicy

# Create a custom synchronization policy
policy = SyncPolicy(
    upload=True,
    extract=True,
    white_list=["/cookies.json", "/storage/"],
    black_list=["/cache/large_files/"]
)

# Use context synchronization
context_sync = ContextSync.new(
    context_id=context.id,
    path="/browser-data",
    policy=policy
)

Multiple contexts

Create a separate context for each site or workflow so their state stays isolated. This prevents cookies or storage from one site leaking into sessions for another.

# Create separate contexts for different websites
ecommerce_context = agent_bay.context.get("ecommerce-site", create=True).context
social_context = agent_bay.context.get("social-media", create=True).context

# Use different contexts for different sessions
ecommerce_session_params = CreateSessionParams(
    browser_context=BrowserContext(ecommerce_context.id, True)
)

social_session_params = CreateSessionParams(
    browser_context=BrowserContext(social_context.id, True)
)

Error handling

Always check the success field on results before using the returned objects. The following example shows a basic error-handling pattern for context and session creation.

try:
    context_result = agent_bay.context.get("my-context", create=True)
    if not context_result.success:
        print(f"Failed to create context: {context_result.error_message}")
        
    session_result = agent_bay.create(session_params)
    if not session_result.success:
        print(f"Failed to create session: {session_result.error_message}")
        
except Exception as e:
    print(f"An error occurred: {e}")