Playwright drives the browser from outside: the test runs in a separate Node.js process and sends commands over a protocol (CDP for Chromium). Isolation has three levels: Browser (the process, one per worker), BrowserContext (its own cookies, localStorage and cache, created in milliseconds) and Page (a tab). Every test gets a new context, so the previous test's session never reaches it.
Playwright · Architecture
One test logged in, and the next one is already a guest. Where did the session go?
The first test logs in and sees the dashboard. The second one runs right after it in the same worker, opens /cabinet and lands on the sign-in page. The session did not "vanish": Playwright deliberately gave the second test a clean page. This lesson answers two questions: where Playwright lives relative to the browser, and why isolation between tests costs milliseconds instead of seconds.
How it works and why. Playwright is not embedded in the page. The test runs in a separate Node.js process and sends the browser commands (click, navigation, script evaluation), and the browser returns a result or an event. For Chromium this is the Chrome DevTools Protocol (CDP); for Firefox and WebKit Playwright ships its own patched builds with a similar protocol. So the downloaded browser is not an exact copy of a regular Firefox or Safari but a build tied to a specific library version.
Control from outside gives what in-browser tools lack: several tabs, windows and origins in one test, iframes, shadow DOM, file downloads. And browsers already have the idea of a "profile with no shared state" (like an incognito window). Playwright made it the basic unit of isolation:
Browser: a running browser process. Launching takes seconds, so there is one per worker.
BrowserContext: an isolated session with its own cookies, localStorage, cache, permissions, viewport, locale and time zone. Creating one takes milliseconds.
Page: a single tab inside a context.
What is nested in what
Figure 1. One browser, contexts inside it as isolated sessions, tabs inside each. Tabs of one context share cookies.
In the runner this layout works without your involvement: browser is one per worker, while context and page are new for every test. That is why the first test's session never reached the second: the first context was destroyed along with its cookies. To avoid logging in through the UI in every test, a saved session (storageState) is plugged into the context in advance.
Example: two users in one test. An admin must see a message a user has just sent. The typical attempt: one page, two logins in turn.
// before: one page, one sessiontest('admin sees the message', async ({ page }) => {
awaitlogin(page, 'user');
await page.getByRole('textbox').fill('Hello');
await page.getByRole('button', { name: 'Send' }).click();
awaitlogin(page, 'admin'); // replaces the user's cookiesawaitexpect(page.getByText('Hello')).toBeVisible();
});
The test may pass, but it checks the wrong thing: the admin opened the chat after a fresh login, not at the same time as the user, so live behaviour (real-time updates, notifications) is invisible to it. Two contexts model two people side by side:
Why it is written this way: contexts created by hand through browser.newContext() are not closed by the runner until the worker ends, so you close them explicitly (otherwise, for example, the video of that context is not saved). The auth/*.json files are produced by a separate setup step, covered in another lesson.
One tab or two contexts
Typical
One page, re-login
Cookies of the second login replace the first. The user and the admin are never "in the system" at the same time, so live updates are not verified.
Better
Two contexts
Two independent sessions side by side, like two people on different devices. The "one sends, the other sees" scenario is really verified.
Figure 2. Two roles in one test: separate contexts, not separate logins on one page.
Limits and comparison. Context isolation covers browser state, not the world around it:
Shared data on the server (the DB, one test account) is not isolated by a context. Two parallel tests with one account can corrupt each other's data.
Contexts of one browser share a process: if the browser crashes, all its contexts crash. Browser extensions need launchPersistentContext, not a regular context.
A context does not change the engine: Chromium, Firefox and WebKit are different browsers, run as separate projects.
The difference from Cypress follows from where the code runs:
Aspect
Playwright
Cypress
Where the test runs
A Node.js process outside the browser
Test code runs inside the browser next to the app
Several tabs and origins
Supported natively, including multiple contexts
Tabs are not controlled natively (only through the @cypress/puppeteer plugin), another origin needs cy.origin()
Test isolation
A new BrowserContext in milliseconds
State is cleared between tests (testIsolation)
Common mistakes.
Sharing state between tests through module variables or leftovers in the DB: the test passes only in a certain order or only in one worker, because the next test gets a clean context.
Launching a new browser in every test: seconds of wasted time, when only a context is needed.
Treating a tab as a separate session: pages of one context share cookies and storage. Two users need two contexts.
Not closing hand-made contexts: memory grows, and the video of such a context is not saved.
Assuming Playwright WebKit equals Safari on a device: it is a close engine, not a substitute for a real check.
Check yourself
Test A puts an item in the cart; test B in the same worker opens the cart and finds it empty. Why is this correct behaviour and not a bug?
Answer
Every test gets a new BrowserContext, so cookies and localStorage from test A were destroyed with its context. This is isolation by design: test B must not depend on order. Prepare the cart you need yourself, for example through the API or a fixture.
A test calls context.newPage() twice. Will the second tab see the first one's session?
Answer
Yes: both pages belong to one context and share cookies and storage. If you need an independent session, create a second context with browser.newContext().
Why does Playwright start one browser per worker but a new context per test?
Answer
Launching a browser process takes seconds, a context takes milliseconds. A context gives the same clean state, so the process can be reused and isolation is almost free.
Related lessons: "What happens under the hood of the runner", "Packages, browsers and channels", "Built-in fixtures and manual creation", "Authentication: storageState and a setup project".
In an interview.Junior: Playwright runs in Node.js and drives the browser over a protocol. The hierarchy is Browser, then BrowserContext as an isolated session, then Page. Every test gets a fresh context, so tests do not share state. Middle/Senior: A context is cheap, so isolation and parallelism are almost free, and I model two users in one test with two contexts. I never pass state between tests through variables or order: authentication is prepared through storageState, data through the API or fixtures. Isolation covers the browser, not the server, so shared accounts and data in parallel tests remain my responsibility.
What happens under the hood of the runner
The runner is a main process that collects the tests and a pool of workers: separate Node.js processes, each with its own browser. Different files run in parallel, while tests of one file run in order in one worker. After a failure the worker exits and a new one starts, so beforeAll runs again and module variables are not shared between workers.
Playwright · Architecture
A test failed and beforeAll created the test user a second time. Is that a bug?
CI logs after one red test show the account created twice, and a variable written by one test is empty in the neighbouring one. This is not a glitch but a consequence of how the Playwright Test runner distributes work: a main process and a pool of workers. The lesson explains that layout, what happens after a failure, and how to write data setup that survives it.
How it works and why.npx playwright test starts the main process. It reads the config, finds the test files, builds the list of tests and hands them out to workers. A worker is a separate Node.js process: it imports the test files itself, launches its own browser, runs the tests it got and sends results back, and the main process passes them to reporters. The default number of workers is half of the logical cores; change it with the workers option or the --workers flag.
Who does what
Figure 1. The main process only coordinates. Workers run the tests, each in its own process with its own browser.
By default, different files run in parallel in different workers, while tests inside one file run sequentially in one worker. To parallelise tests of a single file too, enable fullyParallel: true or test.describe.configure({ mode: 'parallel' }) for a group: then neighbouring tests of one file can land in different processes.
// playwright.config.tsimport { defineConfig } from'@playwright/test';
exportdefaultdefineConfig({
fullyParallel: true, // parallelise tests inside a file too
workers: process.env.CI ? 4 : undefined, // undefined = half of the cores
retries: process.env.CI ? 2 : 0,
});
What happens after a failure. When a test fails or hits its timeout, the worker is shut down and a new process starts for the following tests. This keeps "broken" state (a hung process, a half-cleaned context, corrupted global state) from leaking into other tests. A side effect: beforeAll/afterAll and worker fixtures run again, now in the new worker. Retries follow the same principle: a failed test is repeated in a new worker with a clean browser.
Worker lifecycle around one failure
Figure 2. A failure destroys the worker, and a new one runs the following tests and the retry. The "retry, then the rest" order is approximate: what matters is that the process is new.
Example: expensive setup in beforeAll. A test user is created through the API, and its id lives in a module variable.
// beforelet userId: string; // every worker has its own copy
test.beforeAll(async ({ request }) => {
const res = await request.post('/api/test-users');
userId = (await res.json()).id;
});
There are two problems: after every failure the user is created again, and the link "several tests need the user" rests on a variable that exists only inside this worker. It is sturdier to move setup into a worker fixture: it is created once per worker, has explicit cleanup and unique data:
Why this is better: the data is unique per worker (workerIndex differs for every process, even a restarted one), cleanup sits next to creation, and a test simply asks for account in its arguments. parallelIndex, by contrast, is a slot from 0 to workers - 1 that is reused after a restart, so it suits picking an account from a pre-prepared pool.
When tests must stay together. Sometimes steps really are dependent, such as a multi-step form. For that there is test.describe.configure({ mode: 'serial' }): tests of the group run in order in one worker, after the first failure the rest are skipped, and a retry restarts the group from the first test. This is an exception: serial groups parallelise badly, and one red step hides the results of the next ones. Alternatives: one test with test.step, or independent tests with data from fixtures or the API.
Limits. Workers scale execution on one machine. For several machines there is sharding (--shard=1/4), where each machine runs its own part of the tests with its own pool of workers. Workers do not isolate the server: if they all use one account, they fight over the same data. A retry does not cure instability caused by server data, it only masks it in the summary, so flaky tests in the report should be investigated, not counted as green. This is where Playwright differs from setups in which one process runs all tests in a row: there, state drifts between tests unnoticed, while here processes cut it off.
Common mistakes.
Writing a module variable in one test and reading it in another: the second may land in another worker and see nothing.
Doing expensive setup in beforeAll without accounting for it re-running after every failure. A worker fixture with cleanup is better.
Relying on file order: the distribution across workers is not guaranteed.
One shared test account for all workers: parallel tests change the same data. Split data with workerIndex or parallelIndex.
Putting mode: 'serial' everywhere "for reliability": instead of isolation you get a chain where the first failure removes the rest.
Check yourself
A file has three tests and beforeAll creates a user. The second test fails, no retries. How many times does beforeAll run, and why?
Answer
Twice: after the failure the worker is shut down, and the third test runs in a new worker, which runs beforeAll again. For one-time setup with cleanup, use a worker fixture.
Test A writes to a module variable token, test B reads it and gets undefined. Under what conditions does this happen even if A runs first?
Answer
If B lands in another worker (fullyParallel, another file or a restart after a failure): every process has its own copy of the variable. Data cannot be passed between tests through module variables: use a fixture or the API.
Why does a retry not mask leftovers of the previous run in the browser, yet it can mask a data problem on the server?
Answer
The retry runs in a new worker with a clean browser, so cookies and storage do not carry over. Server data survives the restart: instability caused by it slips through the retry, and the test is marked flaky instead of green.
Related lessons: "Playwright architecture and test isolation", "Packages, browsers and channels", "Fixtures and scopes", "Parallelism, workers and sharding".
In an interview.Junior: The runner distributes tests across workers: separate processes, each with its own browser. Tests of one file run sequentially by default, and parallelism is between files. Middle/Senior: After a failure the worker is restarted, so beforeAll can run several times, and module variables are not shared between workers. I keep no shared state in variables: I prepare data with worker fixtures that clean up and use unique data through workerIndex, and I use a serial group only for truly dependent steps. To scale across several machines I use sharding.
Packages, browsers and channels
Playwright consists of the package, the browser builds and the system libraries, and a channel (channel) picks which browser runs. Every package version expects its own Chromium, Firefox and WebKit builds, which npx playwright install downloads; on a bare Linux CI image --with-deps is added. channel: 'chrome' or 'msedge' runs the Google Chrome or Edge installed on the machine instead of the bundled Chromium.
Playwright · Architecture
Green locally, but in CI: "Executable doesn't exist". What was not installed?
A developer bumped the version of @playwright/test, ran the install locally and everything passed. In CI the tests failed before the first step: the browser was not found. The package was updated, but the browsers in the cache were left from the old version. This is the classic mix-up between the package, the browsers and system libraries. The lesson splits them into layers and shows what breaks where.
How it works and why. Playwright does not use browsers from the system. Each package version expects specific builds of Chromium, Firefox and WebKit: this guarantees the library's protocol matches the browser, and tests do not depend on which Chrome version the OS updated. npx playwright install downloads the builds into the user cache (change the path with the PLAYWRIGHT_BROWSERS_PATH variable). So a project has three layers at once, and each is installed by its own command.
Three layers and what installs each
Figure 1. Each layer is installed separately: upgrading the package does not upgrade the browsers, and a bare Linux image has no libraries to start a browser.
Which package.playwright is a browser automation library without a runner: chromium.launch(), newContext(), newPage(). Use it for scripts, screenshots, PDF generation or integration with someone else's runner (Jest, Mocha). @playwright/test is the full runner: fixtures, expect with retries, reporters, parallelism, retries, trace. For tests, use the second. The scaffold comes from npm init playwright@latest: it adds the dependency, a config and an example test, and offers to download browsers.
Which package to take
Better
@playwright/test
Runner and library together: fixtures, expect with retries, parallelism, reporters, trace. The usual choice for tests.
playwright
Only browser control: scripts, screenshots, PDF, someone else's runner. It has no runner or expect.
Figure 2. Tests need the runner; scripts are fine with the library.
Example: "works for me, fails in CI". After a package upgrade the pipeline fails:
Error: browserType.launch: Executable doesn't exist at
…/ms-playwright/chromium-…/…
Looks like Playwright Test or Playwright was just installed or updated.
Please run the following command to download new browsers:
npx playwright install
The log is shortened, but the shape is the same. The error points straight at layer 2: the new package version expects a build that is not in the cache. The usual cause: a browser cache between runs whose key does not include the Playwright version, or an install step missing altogether. The fix:
# before: only the package in the pipeline
npm ci
npx playwright test
# after: package, browsers and system libraries
npm ci
npx playwright install --with-deps chromium
npx playwright test --project=chromium
Why it works: --with-deps also installs the Linux system packages without which a browser does not start on a bare image (layer 3), and chromium limits the download to one browser when that is all the project uses. If you cache browsers, the key must include the Playwright version, otherwise after an upgrade the runner finds outdated builds. The official documentation actually advises against caching them: restoring a cache takes almost as long as downloading, and the cache does not cover system dependencies. Another route: the official Docker image of the same version as the package, where browsers are already installed.
Channel: branded browsers. Besides the builds Playwright downloads itself (Chromium, which since version 1.57 uses Chrome for Testing builds, plus Firefox and WebKit), you can run an installed Google Chrome or Microsoft Edge through channel:
channel needs the browser installed: npx playwright install chrome or the one already on the machine. Separate projects with channel make sense when the business needs the branded browser verified: codecs, corporate policies, extensions. The price: Chrome updates itself, so tests stop being tied to the Playwright version. Regular tests are fine on Playwright's own builds.
Limits: what WebKit means. WebKit in Playwright is an engine close to the one in Safari, not Safari itself. It catches differences in rendering, CSS and API behaviour well, including on Linux and in CI, but it does not replace a real iPhone, gestures, the on-screen keyboard or mobile Safari specifics. The devices['iPhone 15'] emulation sets the viewport, user agent and touch, while the engine stays the same. Compared with other tools: Selenium drives a driver and a browser from the system (Selenium Manager can fetch them automatically), Cypress runs browsers from the system or its bundled Electron (the default, but already marked as deprecated). In Playwright the browser is part of the project's dependencies, which buys reproducibility at the cost of a download.
Common mistakes.
Upgrading @playwright/test without running npx playwright install: the "Executable doesn't exist" error.
Forgetting --with-deps in CI on a bare Linux image: the browser fails to start because of missing system libraries.
Caching browsers with a key that has no Playwright version: after a package upgrade the cache returns old builds.
Using a Docker image of a different version than the package: its browser builds do not match the expected ones.
Switching every project to channel: 'chrome' "for realism": tests depend on the Chrome version on a particular machine instead of the Playwright version.
Treating a green WebKit project as proof that everything works in Safari on an iPhone.
Check yourself
CI fails at launch with "Executable doesn't exist at …/chromium-…". Locally everything works. Which layer is the problem in, and what do you check first?
Answer
Layer 2 (browser builds). Check whether the pipeline runs npx playwright install and whether the browser cache is tied to an old package version. It works locally because the needed build is already installed there.
The browser is downloaded, but on a bare Linux image it does not start because of missing libraries. Which command fixes it, and why does npm ci not help here?
Answer
npx playwright install --with-deps: the flag installs the system packages. npm ci installs only JavaScript dependencies and does not touch OS libraries.
Does a green webkit project prove the app works in Safari on an iPhone?
Answer
No. It is a close engine that catches rendering and CSS differences well, but it is not a real device: gestures, the on-screen keyboard and mobile Safari behaviour stay unverified.
Related lessons: "Playwright architecture and test isolation", "What happens under the hood of the runner", "Configuration and projects", "CI: sharding, Docker and fast reruns".
In an interview.Junior: For tests I use @playwright/test. I install browsers with npx playwright install, because they are tied to the package version, and on Linux in CI I add --with-deps. Middle/Senior: I tell three layers apart: the package, the browser builds and the system libraries, and I know that upgrading the package without reinstalling browsers gives "Executable doesn't exist". If there is a cache or a Docker image, I tie its version to the package. I add channel projects when Google Chrome or Edge matter, and I treat WebKit as an approximation of Safari, not a replacement for a real device.