Custom contexts are still in beta and may be incompatible with some versions of Chrome.

Browser cookies are stored in the user data directory. By default, Browserbase creates a new user data directory for each session.

For some use cases, such as authentication or caching, it can be helpful to preserve the user data directory and reuse it across sessions. With contexts, it’s easy.

Sharing Contexts across Sessions

One benefit of using contexts is that all the data generated during one session can be used in the next. This is especially useful to improve load times, as the network cache is also preserved.

For more performance tips, check out our performance tuning guide.

Contexts are configured by creating a context via the Contexts API. Then, pass the context’s ID to every Create Sessions API call.

Make sure to set context.persist to true when creating a session if you want the context to be updated with the session’s state.

Here’s the steps:

To share contexts across sessions, follow these steps:

  1. Use the Contexts API to create a new context. You’ll need the context ID for the next step.
  2. Use the Sessions API to create a new session. You’ll need to add "browserSettings": { "context": { "id": YOUR_CONTEXT_ID, "persist": true } } to the body.

context.persist isn’t required for each session. A workflow might involve enabling it for the first session (to fill the cache) and then disabling it on subsequent ones.

Context data can include stored credentials and other sensitive browsing data. Because of this, contexts are uniquely encrypted at rest.

Uploading your own custom user data directory

In some scenarios, it may make sense to upload a custom user data directory. That’s why the Create Contexts API returns an authenticated uploadUrl that enables this. The uploaded file must follow a specific pattern in order to work with sessions.

  1. The uploaded context must have a filename of ${context.id}.zip
  2. The ZIP must be encrypted using details from the Context API response

Below are code examples showing how to compress and encrypt a user data directory:

Deleting Contexts

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 and any attempts to do so will fail.

Here’s how to delete a context:

  1. Use the Delete Context API with the context ID
  2. The API will return a 204 status code on success
  3. Any subsequent attempts to use this context ID will fail with a 404 error

Deleting a context is permanent and cannot be undone. Make sure you no longer need the context before deleting it.

Here’s an example of deleting a context:

Handling Authentication

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