Playwright 09 ๐ญ Browser Contexts โ Isolation, Cookies, and Storage State
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
| Method | Purpose |
|---|---|
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
| Item | Detail |
|---|---|
| Saves | Cookies + localStorage |
| Format | JSON |
| Restores | newContext({ storageState }) |
| Config option | use.storageState |
Context Options
| Option | Purpose |
|---|---|
baseURL | Relative URL base |
viewport | Window size |
locale | Language |
timezoneId | Time zone |
colorScheme | Light/dark |
permissions | Browser 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
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Test logs in every time | No storageState | Save the state and reuse |
| State leaks between tests | Shared context | One context per test |
| Geolocation prompt hangs | No permission grant | permissions: ["geolocation"] |
| localStorage not restored | Different origin | Save 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
| Item | Value |
|---|---|
| Context | Isolated browser session |
| Created by | The test runner, per test |
| Isolates | Cookies, storage, cache, permissions |
| Save state | context.storageState({ path }) |
| Restore state | newContext({ storageState }) |
| Config option | use.storageState |
| Multi-user | One 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.
storageStatesaves and restores the session. The file contains the cookies and the localStorage of the origins the context visited. Passing it tonewContextstarts 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
dependenciesarray 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, andcontext.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.
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!