| | |

Playwright 09 ๐ŸŽญ Browser Contexts โ€” Isolation, Cookies, and Storage State

โฑ๏ธ Estimated read: 9 min | |

A browser context is an isolated browser session inside a running browser. It is the Playwright equivalent of an incognito window: its own cookies, localStorage, sessionStorage, cache, and permissions. The test runner creates one per test by default, which is why test isolation is automatic; the context is created in milliseconds and discarded after the test. The same mechanism is what makes multi-user tests possible, and it is the object that storageState serializes to skip a login flow.

This chapter covers the context lifecycle, the storageState mechanism for persisting cookies and localStorage, and the multi-context patterns that test multi-user scenarios. The sections that follow walk through the isolation model, the storage state save and reuse, and the context creation that the test runner does automatically.

Key point: A BrowserContext is an isolated session with its own cookies and storage; the test runner creates one per test, context.storageState() saves the cookies and localStorage to a file, and browser.newContext({ storageState }) restores them to skip the login.


a. The isolation model and the context lifecycle

A browser context is created from a browser instance. The browser process is shared across contexts, which is why the isolation is cheap. Each context has its own cookie jar, its own localStorage and sessionStorage, its own cache, and its own permission grants.

import { test, expect } from "@playwright/test";

test("isolated session", async ({ page, context }) => {
  await page.goto("/");
  await context.addCookies([{ name: "session", value: "abc", url: "http://localhost:3000" }]);

  // The cookie is visible in this context
  const cookies = await context.cookies();
  expect(cookies).toHaveLength(1);
});

test("the next test has no cookies", async ({ page, context }) => {
  await page.goto("/");
  const cookies = await context.cookies();
  expect(cookies).toHaveLength(0); // fresh context
});

The test runner creates the context before the test and closes it after. The context fixture is available alongside page, and it exposes the methods for cookies, permissions, routes, and storage state. The browser fixture is the shared instance, and a test that needs a second context creates it from the browser.

The context options control the environment. The baseURL, viewport, locale, timezoneId, colorScheme, and permissions are set at creation, and they apply to every page in the context.

const context = await browser.newContext({
  baseURL: "http://localhost:3000",
  viewport: { width: 1280, height: 720 },
  locale: "en-US",
  timezoneId: "America/New_York",
  colorScheme: "dark",
  permissions: ["geolocation"],
});

The permissions option is the way to grant a browser permission that the application requestsโ€”geolocation, notifications, clipboard. Without the grant, the permission prompt appears and the test hangs or the API rejects.


b. storageState and the login reuse

context.storageState() returns an object with the context’s cookies and the localStorage of its origins. The object can be written to a file and passed to browser.newContext({ storageState }) to restore the session, which is the mechanism for skipping the login in every test.

// Save the state after logging in
await page.goto("/login");
await page.getByLabel("Email").fill("user@example.com");
await page.getByLabel("Password").fill("password123");
await page.getByRole("button", { name: "Sign in" }).click();
await page.waitForURL("/dashboard");

await context.storageState({ path: "auth.json" });

The auth.json file contains the cookies and the localStorage entries. A test that passes storageState: "auth.json" to the context starts with the session already active, and the login flow is not repeated.

// Reuse the state in another context
const context = await browser.newContext({ storageState: "auth.json" });
const page = await context.newPage();
await page.goto("/dashboard"); // already logged in

The storageState option is also available at the config level, which is the pattern for a project where every test needs the same session. The setup project runs the login once, saves the state, and the test projects depend on it.

// playwright.config.ts
export default defineConfig({
  projects: [
    { name: "setup", testMatch: /global\.setup\.ts/ },
    {
      name: "chromium",
      use: { ...devices["Desktop Chrome"], storageState: "auth.json" },
      dependencies: ["setup"],
    },
  ],
});

The dependencies: ["setup"] line is what makes the setup project run before the test project. The setup project’s test file logs in and saves the state; the test project reads the state and starts authenticated.

The localStorage part of the state is saved per origin. A context that visits two origins saves the localStorage of both, and the restored context has both. The cookies are saved with their domain, path, and expiration, and they are restored as they were.


c. Multi-context and multi-user patterns

A test that needs two usersโ€”a chat application with a sender and a receiverโ€”creates two contexts from the browser. Each context has its own session, and the two pages interact with the application as separate users.

test("two users can chat", async ({ browser }) => {
  const aliceContext = await browser.newContext();
  const bobContext = await browser.newContext();

  const alice = await aliceContext.newPage();
  const bob = await bobContext.newPage();

  await alice.goto("/chat");
  await bob.goto("/chat");

  await alice.getByLabel("Message").fill("Hello Bob");
  await alice.getByRole("button", { name: "Send" }).click();

  await expect(bob.getByText("Hello Bob")).toBeVisible();

  await aliceContext.close();
  await bobContext.close();
});

The two contexts are independent, and the test can assert that Alice’s message appears in Bob’s page without the two sessions interfering. The contexts are closed at the end of the test, and the browser is closed by the runner.

The browser.newPage() shortcut creates a page in a new context, which is equivalent to creating a context and a page. The explicit browser.newContext() is the form for a test that needs to configure the context or keep a reference to it.

The context is also the object for route interception. context.route() applies to every page in the context, which is the pattern for mocking an API for a multi-page flow. The page.route() is the per-page version.


Complete Example Session

// ============================================
// PART 1: THE ISOLATION
// ============================================
import { test, expect } from "@playwright/test";

test("sets a cookie", async ({ page, context }) => {
  await page.goto("/");
  await context.addCookies([
    { name: "theme", value: "dark", url: "http://localhost:3000" },
  ]);
  await page.reload();
  await expect(page.locator("html")).toHaveAttribute("data-theme", "dark");
});

test("starts without the cookie", async ({ context }) => {
  const cookies = await context.cookies();
  expect(cookies).toHaveLength(0);
});

// ============================================
// PART 2: THE STORAGE STATE
// ============================================
// auth.setup.ts
import { test as setup } from "@playwright/test";

setup("authenticate", async ({ page, context }) => {
  await page.goto("/login");
  await page.getByLabel("Email").fill("user@example.com");
  await page.getByLabel("Password").fill("password123");
  await page.getByRole("button", { name: "Sign in" }).click();
  await page.waitForURL("/dashboard");
  await context.storageState({ path: "auth.json" });
});

// ============================================
// PART 3: THE CONFIG
// ============================================
// playwright.config.ts
// projects: [
//   { name: "setup", testMatch: /.*\.setup\.ts/ },
//   {
//     name: "chromium",
//     use: { ...devices["Desktop Chrome"], storageState: "auth.json" },
//     dependencies: ["setup"],
//   },
// ]

// ============================================
// PART 4: MULTI-USER
// ============================================
test("two users", async ({ browser }) => {
  const aliceContext = await browser.newContext();
  const bobContext = await browser.newContext();

  const alice = await aliceContext.newPage();
  const bob = await bobContext.newPage();

  await alice.goto("/chat");
  await bob.goto("/chat");
  // ...

  await aliceContext.close();
  await bobContext.close();
});

The parts covered the isolation, the storage state setup, the config dependency, and the multi-user pattern.


Quick Reference

Context Methods

MethodPurpose
context.cookies()Read cookies
context.addCookies(cookies)Set cookies
context.clearCookies()Clear cookies
context.storageState({ path })Save state
context.route(url, handler)Intercept requests
context.grantPermissions(perms)Grant permissions
context.close()Close the context

Storage State

ItemDetail
SavesCookies + localStorage
FormatJSON
RestoresnewContext({ storageState })
Config optionuse.storageState

Context Options

OptionPurpose
baseURLRelative URL base
viewportWindow size
localeLanguage
timezoneIdTime zone
colorSchemeLight/dark
permissionsBrowser grants

Best Practices

โœ… Do This:

// Let the runner create the context
test("...", async ({ page }) => { ... });                     // โœ…

// Save and reuse the storage state
await context.storageState({ path: "auth.json" });            // โœ…

// Use a new context for a second user
const other = await browser.newContext();                     // โœ…

โŒ Don’t Do This:

// Launch a browser per test
const browser = await chromium.launch(); // slow               // โŒ

// Share a context across tests
// (state leaks)                                              // โŒ

// Skip the permission grant
// (prompt hangs the test)                                    // โŒ

Common Pitfalls

PitfallWhy It HappensFix
Test logs in every timeNo storageStateSave the state and reuse
State leaks between testsShared contextOne context per test
Geolocation prompt hangsNo permission grantpermissions: ["geolocation"]
localStorage not restoredDifferent originSave the state after visiting the origin

Real-World Examples

1. Read cookies

const cookies = await context.cookies();

2. Set a cookie

await context.addCookies([{ name: "session", value: "abc", url: "http://localhost:3000" }]);

3. Save the state

await context.storageState({ path: "auth.json" });

4. Restore the state

const context = await browser.newContext({ storageState: "auth.json" });

5. Config storage state

use: { storageState: "auth.json" }

6. Multi-user

const aliceContext = await browser.newContext();
const bobContext = await browser.newContext();

7. Grant permission

await context.grantPermissions(["geolocation"]);

8. Clear cookies

await context.clearCookies();

9. Route interception

await context.route("**/api/**", (route) => route.fulfill({ json: {} }));

10. Close the context

await context.close();

Visual

Context Isolation

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  BROWSER (one per worker)                               โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”   โ”‚
โ”‚  โ”‚ Context A    โ”‚  โ”‚ Context B    โ”‚  โ”‚ Context C    โ”‚   โ”‚
โ”‚  โ”‚ Test 1       โ”‚  โ”‚ Test 2       โ”‚  โ”‚ Test 3       โ”‚   โ”‚
โ”‚  โ”‚ cookies: {}  โ”‚  โ”‚ cookies: {}  โ”‚  โ”‚ cookies: {}  โ”‚   โ”‚
โ”‚  โ”‚ storage: {}  โ”‚  โ”‚ storage: {}  โ”‚  โ”‚ storage: {}  โ”‚   โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜   โ”‚
โ”‚                                                         โ”‚
โ”‚  The browser is shared; the contexts are not.           โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Storage State Flow

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  Setup project                                          โ”‚
โ”‚    login โ†’ context.storageState({ path: "auth.json" })  โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  auth.json (cookies + localStorage)                     โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  Test project                                           โ”‚
โ”‚    newContext({ storageState: "auth.json" })            โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  already logged in                                      โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Multi-User

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  browser                                                โ”‚
โ”‚    โ”œโ”€โ”€ context A โ†’ page (Alice)                         โ”‚
โ”‚    โ””โ”€โ”€ context B โ†’ page (Bob)                           โ”‚
โ”‚                                                         โ”‚
โ”‚  Alice sends a message โ†’ Bob's page sees it             โ”‚
โ”‚  The sessions are independent.                          โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Context Options

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  newContext({                                           โ”‚
โ”‚    baseURL, viewport, locale, timezoneId,               โ”‚
โ”‚    colorScheme, permissions, storageState               โ”‚
โ”‚  })                                                     โ”‚
โ”‚                                                         โ”‚
โ”‚  The options apply to every page in the context.        โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
ContextIsolated browser session
Created byThe test runner, per test
IsolatesCookies, storage, cache, permissions
Save statecontext.storageState({ path })
Restore statenewContext({ storageState })
Config optionuse.storageState
Multi-userOne context per user

Key takeaways:

  • A context is an isolated session. It has its own cookies, localStorage, and permissions, and the test runner creates one per test. The browser is shared, so the isolation is cheap.
  • storageState saves and restores the session. The file contains the cookies and the localStorage of the origins the context visited. Passing it to newContext starts the test already logged in.
  • The setup project is the config pattern. A setup project logs in once and saves the state; the test projects depend on it and read the state. The dependencies array is what orders the run.
  • Multi-user tests use multiple contexts. Each user gets a context, and the pages interact with the application as separate sessions. The contexts are closed at the end of the test.
  • The context is the routing and permission scope. context.route() applies to every page in the context, and context.grantPermissions() is how the test grants a browser permission the application requests.

Remember: The context is the unit of isolation in Playwright. The browser is shared, the context is not. Every test gets a fresh one, and every multi-user test creates its own. The storage state is the mechanism that makes a logged-in session reusable across tests, and the setup project is the pattern that runs the login once. When a test leaks state into the next, the cause is a shared context; when a test repeats a login, the cause is a missing storage state.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!