Skip to content

Contexts

Reuse cookies, authentication, and application data across browser sessions.

Updated View as Markdown

Contexts allow you to persist user data across multiple browser sessions, enabling smoother automation, seamless authentication, and faster end-to-end workflows.

By default, each Browsers session starts with a fresh user data directory, so cookies and application data reset between sessions. With Contexts, you can reuse this data across sessions, making automation workflows more reliable and eliminating repeated logins. Browser cookies are stored in the user data directory.

Contexts are configured by:

  1. Creating a Context via the Contexts API
  2. Passing the Context ID into the Create Sessions API

Why use Contexts?

  • Reusing cookies & session data: Maintain login states across multiple sessions without needing to log in repeatedly.
  • Preserving authentication: Store and reuse authentication tokens, reducing the need to re-enter credentials.
  • Retaining application data: Persist localStorage, IndexedDB, and other site-specific data written by web applications.
  • Faster workflows: Skip login flows and re-authentication steps, reducing the total time of your automation runs.

Create a Context

To create a Context, use the Create Context API. This returns a unique Context ID that you can pass into new sessions to persist data.

You can optionally set a name to label the Context. Names are unique within an application (compared case-insensitively), and leading or trailing whitespace is trimmed.

import { Browsers } from "@agentmq/browsers";

const browsers = new Browsers({ apiKey: process.env.AGENTMQ_TOKEN! });
const context = await browsers.contexts.create({
  name: "my-context",
});

console.log("Context ID:", context.id);
from agentmq.browsers import Browsers
import os

browsers = Browsers(api_key=os.environ["AGENTMQ_TOKEN"])
context = browsers.contexts.create(name="my-context")

print("Context ID:", context.id)
curl -X POST https://api.agent.mq/v1/browsers/contexts \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer: $AGENTMQ_TOKEN" \
  -d '{"name": "my-context"}'

Use a Context

After creating a Context, use it in a new session to reuse cookies, authentication, and application data. This creates a returning user experience, speeding up your workflow and eliminating repeated logins.

Here’s an example of how to use a Context in a new session, this example uses the Context ID from the previous example.

import { Browsers } from "@agentmq/browsers";

const browsers = new Browsers({ apiKey: process.env.AGENTMQ_TOKEN! });

// Use the context ID from the previous example
const contextId = "<context-id>";

const session = await browsers.sessions.create({
  browserSettings: {
    context: {
      id: contextId,
      persist: true,
    },
  },
});

console.log("Session URL: https://agent.mq/sessions/" + session.id);
from agentmq.browsers import Browsers
import os

browsers = Browsers(api_key=os.environ["AGENTMQ_TOKEN"])

# Use the context ID from the previous example
context_id = "<context-id>"

session = browsers.sessions.create(
  browser_settings={
    "context": {
      "id": context_id,
      "persist": True
    }
  }
)

print("Session URL: https://agent.mq/sessions/" + session.id)

Set persist

If you need to store new cookies, authentication tokens, or application data, you must set persist: true when creating a session. This ensures that any changes made during the session (such as logging in or saving site preferences) are retained for future sessions instead of being lost when the session ends. The data will be saved when the session closes.

persist: false prevents changes from being saved to the Context. It’s useful for less common use cases, such as:

  • Read-only session: If you need to access saved cookies or data without modifying them.
  • Prevent session state changes: Avoids overwriting stored login tokens or user data.

Login workflow

A typical flow to persist a website login across Browsers sessions would be as follows:

  1. Create a Context (get a contextId).
  2. Start a first Browsers session with that contextId and persist: true.
  3. Log in to a website inside this first session, either manually through the live view feature or programmatically.
  4. End this session.
  5. Wait a few seconds to ensure that the Context is updated.
  6. Start a second Browsers session (and future sessions) with the same contextId and visit the same website. You should now be signed in automatically without having to repeat the login process.

Login best practices

Browsers Contexts don’t expire (see Context expiration), but sites can still force a log out. Here are a few additional best practices:

  • Avoid simultaneous logins: Avoid having multiple sessions using the same Context at once. Sites may force a log out.
  • Use a consistent geolocation: Some sites check user location. Use a geolocated proxy for these cases.
  • One Context per site, per login: Prevent an individual Context from becoming too large, which can slow down your session.

Context expiration

Contexts live indefinitely on Browsers’ infrastructure. Once created, a Context persists until you explicitly delete it or it becomes invalidated. You can create a Context once and reuse it across sessions for weeks or months.

However, there are several ways a Context can become invalid or unusable:

Client-side invalidation

  • Explicit deletion: Calling the Delete Context API permanently removes the Context
  • Application deletion: If the parent application is deleted, all associated Contexts are removed
  • Account changes: Account suspension or deletion will invalidate all Contexts

Application-level invalidation

While the context itself persists, the data stored within it can become stale or invalid due to external factors:

  • Session expiration: Websites may expire authentication cookies after a set period (e.g., 30 days), requiring re-authentication even with a persisted Context
  • Password changes: If you change your password on a website, stored session cookies may be invalidated by that website
  • Server-side logout: Websites can invalidate sessions server-side (e.g., “log out of all devices”)
  • Token revocation: OAuth tokens or API keys stored in cookies may be revoked by the service provider
  • Security events: Websites may force re-authentication after detecting suspicious activity

Delete a Context

When you no longer need a Context, delete it using the Delete Context API. Once deleted, a Context can’t be used to create new sessions.

import { Browsers } from "@agentmq/browsers";

const browsers = new Browsers({ apiKey: process.env.AGENTMQ_TOKEN! });

const contextId = "<context-id>";
await browsers.contexts.delete(contextId);

console.log("Context deleted");
from agentmq.browsers import Browsers
import os

browsers = Browsers(api_key=os.environ["AGENTMQ_TOKEN"])

context_id = "<context-id>"
browsers.contexts.delete(context_id)

print("Context deleted")
curl -X DELETE https://api.agent.mq/v1/browsers/contexts/<context-id> \
  -H "Authorization: Bearer: $AGENTMQ_TOKEN"

Handling authentication

Once you set up Contexts, follow the authentication guide to easily log into websites.
Navigation

Type to search…

↑↓ navigate↵ selectEsc close