How to Isolate AI Agent Web Sessions: Cookies and IP

Published:

11 minute read

Enver Kaya
Written by: Enver Kaya
Threads from one agent core split into three channels, each with its own context and exit IP; the middle one is blue

Session isolation is the practice of keeping every task an AI agent runs separate, with its own cookies, storage, credentials and exit IP. In Playwright, the unit of that separation is the browser context. If the agent runs all its tasks in one context, the cookies are shared. One task's login leaks into another task's tab. This post covers opening a context per task, giving each context a sticky proxy session, cleaning up when a task ends and logging the exit IP.

Where tasks get mixed up

Cookies are stored per domain, not per task. If two tabs in the same context log in to the same site, the second login overwrites the first cookie. In our test, Alice's tab sent sid=bob to the server after Bob logged in. The agent thought it was working for Alice while acting on Bob's account.

On the proxy side, the same problem shows up as the IP. If two tasks use the same sticky session ID, they leave from the same exit IP. The site sees two different accounts behind one address. In your own logs, you can no longer tell which request belongs to which task.

Isolation is not about keeping the site from recognizing you. The goal is to stop one task's data, login and errors from carrying over into another task. If the agent works on behalf of several users, this is a security boundary.

One browser context per task

A browser context is a separate session opened inside the same browser process. The Playwright docs describe a context as an incognito-like profile. Each context has its own cookies, local storage and session storage. Contexts are cheap to open and do not need a new browser launch.

How strong the separation is depends on the setup you choose:

SetupWhat stays sharedFits
One context, many tabsCookies and storageOne task, one account
One context per taskOnly the browser processParallel tasks for one team
One browser process per taskNothingTasks for different customers
Persistent profileEverything stays on diskA single user's long-lived profile

A persistent profile (launch_persistent_context) is a trap for agent work. One task's cookie is written to disk and the next task starts with it. If the agent handles data for different users, start every task in a fresh context. For a harder boundary between customers, use a separate process or a separate container.

A sticky session per context

Playwright can set the proxy on the context instead of the browser. Every context opened with browser.new_context(proxy=...) carries its own username and password. When the session ID in the username changes, the gateway binds that context to a different exit IP. We covered the basic setup in What Is Playwright and How to Use It With a Proxy.

The rule is simple: one task, one session ID. Build the ID from the task name and a random suffix. Never give the same ID to two tasks, and never reuse the ID of a finished task. On Proxynet, you choose a sticky duration between 1 and 60 minutes. Pick it for the length of the whole flow, not the longest single step. The product's scope is on the Sticky Proxy page.

In our test on Windows, Chromium worked with per-context proxies without a global proxy at launch. Two concurrent contexts sent two different usernames to the test proxy and got two different exit addresses.

Sample code

The Python example below runs two tasks at once, each with its own context and sticky session. Each task first asks for its exit IP, logs it, then does its work. The context closes in finally even if the task fails.

python
import asyncio
import json
import logging
import os
import uuid

from playwright.async_api import async_playwright

PROXY_SERVER = os.environ.get("PROXY_SERVER", "http://pr.proxynet.io:8000")
# Your sticky username pattern, with {session} in place of the session
PROXY_USER_TEMPLATE = os.environ["PROXY_USER_TEMPLATE"]
PROXY_PASS = os.environ["PROXY_PASS"]
SITE = os.environ.get("SITE", "https://example.com")
IP_CHECK_URL = os.environ.get("IP_CHECK_URL", "https://api.ipify.org?format=json")

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")
log = logging.getLogger("agent")


async def run_task(browser, task_id, work):
    session = f"{task_id}-{uuid.uuid4().hex[:8]}"  # a new ID for every task
    context = await browser.new_context(proxy={
        "server": PROXY_SERVER,
        "username": PROXY_USER_TEMPLATE.format(session=session),
        "password": PROXY_PASS,
    })
    try:
        resp = await context.request.get(IP_CHECK_URL)  # goes through the context's proxy
        exit_ip = (await resp.json())["ip"]
        log.info(json.dumps({"task": task_id, "session": session,
                             "exit_ip": exit_ip, "event": "start"}))
        return await work(await context.new_page())
    finally:
        await context.close()  # cookies, storage and pages are discarded here
        log.info(json.dumps({"task": task_id, "session": session, "event": "closed"}))


def login_as(user):
    async def work(page):
        await page.goto(f"{SITE}/login?user={user}")
        await page.goto(f"{SITE}/me")
        return json.loads(await page.inner_text("body"))
    return work


async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch()
        results = await asyncio.gather(
            run_task(browser, "task-a", login_as("alice")),
            run_task(browser, "task-b", login_as("bob")),
        )
        print(results)
        await browser.close()


if __name__ == "__main__":
    asyncio.run(main())

PROXY_USER_TEMPLATE holds your account's sticky username pattern. Put {session} where the session ID goes. The code generates a separate ID for each task and drops it into the pattern. The /login and /me paths belong to our test site. In your own work, replace login_as with the task's steps.

The IP check uses context.request. In our test, this client went through the context's proxy with the same session ID. So the IP in the log matches the address the task's pages leave from.

Cleanup at the end of a task

Cleanup happens on two layers: the browser and the proxy. context.close() closes the context's pages and discards its cookies and storage. In our test, a new context opened after the close started without cookies. Its exit IP stayed the same, because it was given the same session ID.

This shows that the proxy side is cleaned up separately. A sticky session stays bound to its IP until the duration you chose runs out, even after the context closes. If the next task starts with a new ID, the old one drops on its own. There is nothing to do by hand, as long as you never reuse an ID.

If a task stops halfway and will resume later, context.storage_state(path=...) writes cookies and local storage to a file. The Playwright docs warn that this file may contain cookies sufficient to impersonate your account. Store it under a task-specific name and delete it when the work is done. Session storage is not included in this file. IndexedDB is included only with indexed_db=True.

Downloaded files and screenshots are task data too. Write them to a separate folder named after the task ID and delete it together with the context.

Credentials

Credential leaks usually come from a shared object. A shared context, a storage_state file passed between tasks or http_credentials given to the wrong context are the three most common sources. Give each task's password and cookie file only to that task's context.

The proxy password is per context too. Playwright sends each context's credentials in a Proxy-Authorization header on that context's own connections. In our test, the two contexts' requests reached the proxy with their own usernames and never mixed.

The model itself should never see the password. Let your code handle the login step, and pass only the result to the model. Also limit the domains the agent can visit. The allowlist and rate limit setup is in Safe Web Access for LLMs.

Task and IP log

The log's job is to tie every request to a task and an exit IP. Write one JSON line at the start and end of each task. When a complaint or an error comes in, these lines tell you which task left from which address.

FieldExampleWhy
tasktask-aWhose work
sessiontask-a-a77915a4Which sticky session
exit_ip198.51.100.7The address the site sees
eventstart, closedStart and end of the task

Do not log passwords, cookie values or the full proxy URL. An address like http://user:pass@pr.proxynet.io:8000 carries the password in plain text. The OWASP logging guide lists usernames and passwords in URLs, session values and access tokens among the data that should not be recorded directly.

Checking the IP once at the start of a task is enough for most work. For long tasks, check again at the end. If the two values differ, the session moved to another exit mid-task.

Troubleshooting

  • Two tasks leave from the same IP. The pattern has no {session}, or two tasks got the same ID. Compare the session fields in the log.
  • One task sees the other's account. The tasks share one context. Check that every task starts with new_context.
  • A new task starts with old cookies. A persistent profile or an old storage_state file is being loaded.
  • The proxy log shows 407 lines. In our test, Chromium sent each context's first page request without credentials, got a 407, then retried with them. If the following request goes through, there is no problem.
  • The IP changes mid-task. The sticky duration ran out or the exit device left the network. Extend the duration to fit the flow, or split the task.

How we tested

We ran the test on December 3, 2026, on Windows 11 with Python 3.13.17, Playwright 1.58.0 and Chromium 145.0.7632.6. The setup had two local servers. The test site set a cookie at /login and returned the incoming cookie and client address at /me. The local test proxy required Basic authentication and bound the session ID in the username to one of the 127.0.0.x loopback addresses. These addresses stood in for different exit IPs.

ScenarioResult
One context per task, two concurrent tasksEach task saw its own cookie and a separate exit IP
One context, two tabsAlice's tab sent sid=bob
New context with the same ID after closeNo cookies, same exit IP
IP check with context.requestWent through the context's proxy and session
Per-context proxy without a global proxy at launchWorked on Windows

On a real gateway, exit addresses, durations and the 407 flow may differ. What the test shows is the separation on the Playwright side.

The bottom line

Give each task its own context, its own sticky session ID and its own log line, and close the context in finally. For read-only tasks that need no login, you can use the Residential Proxy pool with rotation. Above all, never run tasks in a single context: the cookies mix silently and nothing throws an error.

Sources

Frequently asked questions

Can each Playwright context use a different proxy?

Yes. browser.new_context(proxy={...}) takes a separate server, username and password for each context. Contexts opened in the same browser process with different session IDs use different exit IPs. In our test on Windows, Chromium worked with per-context proxies without a global proxy at launch. If you run into problems on older versions, update Playwright.

Is a browser context the same as an incognito tab?

Largely, yes. Playwright describes a context as an incognito-like profile. Each context has separate cookies, local storage and session storage, and they are deleted when the context closes. The difference is that you can open as many contexts as you need in one process and give each one its own proxy.

How long should the sticky session be for an agent task?

Pick the task's total duration plus a little margin. On Proxynet, the duration ranges from 1 to 60 minutes. It is the upper limit for how long a session ID stays bound to the same IP. Split jobs that run longer than an hour into parts and give each part a new ID. If the parts need cookies from each other, use a task-specific storage_state file.

Do I need a new browser for every task?

Usually not. A context per task is enough to separate one team's tasks, and it is lighter than launching a new browser. For an agent that handles data from different customers, you may want a harder boundary. In that case, use a separate browser process or a separate container for each customer.

Can session state be shared between tasks?

Do not share it. A storage_state file carries logged-in cookies, and any context that loads it works as that account. If two tasks use the same file, isolation is gone. For a task that will resume, store the file under a task-specific name, restrict access and delete it when the task is done.

How do I verify which IP the agent leaves from?

At the start of the task, send a request to an IP echo service through the context. context.request.get(...) uses the context's proxy and session ID; log the returned address with the task ID. For long tasks, repeat the check at the end. If the two addresses differ, the session moved to another exit mid-task.

Ask ChatGPTAsk Claude