Skip to main content

Overview

Contexts allow you to persist user data across multiple browser sessions, enabling smoother automation, authentication, and performance optimizations. By default, each Browserbase session starts with a fresh user data directory, meaning cookies, cache, and session storage are wiped between sessions. With Contexts, you can reuse stored data across sessions, making automation workflows faster, more reliable, and more efficient. 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
View or run the example template here

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.
  • Speeding Up Page Loads: Cache assets, API responses, and other browser data to decrease load times.
Context data can include stored credentials and other sensitive browsing data. Because of this, contexts are uniquely encrypted at rest to ensure security.

Create a Context

To create a context, use the Create Context API. This will return a unique context ID, which you can pass into new sessions to persist data.
import { Browserbase } from "@browserbasehq/sdk";

const bb = new Browserbase({ apiKey: process.env.BROWSERBASE_API_KEY! });
const context = await bb.contexts.create({
  projectId: process.env.BROWSERBASE_PROJECT_ID!,
});

console.log("Context ID:", context.id);

Use a Context

After creating a context, you can use it in a new session to reuse cookies, authentication, and cached data. This allows you to create a returning user experience, reducing load times and eliminating the need to log in again.
After closing a session with persist: true, wait a few seconds before reusing the context to ensure data is synchronized.
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 { Browserbase } from "@browserbasehq/sdk";

const bb = new Browserbase({ apiKey: process.env.BROWSERBASE_API_KEY! });

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

const session = await bb.sessions.create({
  projectId: process.env.BROWSERBASE_PROJECT_ID!,
  browserSettings: {
    context: {
      id: contextId,
      persist: true,
    },
  },
});

console.log("Session URL: https://browserbase.com/sessions/" + session.id);

Set Persist

If you need to store new cookies, authentication tokens, or cached data, you must set persist: true when creating a session. This ensures that any changes made during the session—such as logging in, saving site preferences, or caching assets—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. This is useful for less common use cases, such as:
  • Read-only session: If you need to access saved cookies or cache 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 Browserbase sessions would be as follows:
  1. Create a context (get a contextId).
  2. Start a first Browserbase session with that contextId and persist: true.
  3. Log in to a website inside this first session, either manually through our 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 Browserbase 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

Browserbase Contexts have no expiration on our end (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 are designed to live indefinitely on Browserbase’s infrastructure. Once created, a context will persist until you explicitly delete it or it becomes invalidated. This means you can create a context once and reuse it across sessions for weeks or months without worrying about expiration. 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
  • Project deletion: If the parent project 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
To handle application-level invalidation, implement checks in your automation to detect logged-out states and re-authenticate when necessary.

Delete a Context

When you no longer need a context, you can delete it using the Delete Context API. Once deleted, a context cannot be used to create new sessions.
Deleting a context is permanent and cannot be undone.
const contextId = "<context-id>";

const response = await fetch(
  `https://api.browserbase.com/v1/contexts/${contextId}`,
  {
    method: "DELETE",
    headers: {
      "X-BB-API-Key": process.env.BROWSERBASE_API_KEY!,
    },
  }
);

console.log("Context deleted:", response.status);

Handling Authentication

Once you set up contexts, follow our authentication guide to easily log into websites.