QA Interview Hub · Knowledge base · Quizzes · Українська

Playwright › Authentication and storageState

Several roles and the logged-out state

Each role gets its own state file, and two users in one test live in two separate contexts, each with its own storageState. Contexts in one browser are isolated, so the cookies and localStorage of one role are invisible to the other. A guest is checked with an empty state. Session isolation does not isolate data, so every test creates its own entities and closes the contexts it created.

Playwright · Authentication

A client submits an application, an admin approves it. How do you hold two users in one test without mixing sessions?

A real application has a client, a manager, an administrator. Most tests need one role, but the most interesting scenarios involve two: a client submitted an application, an administrator approved it, the client saw the new status. Switching the user in the middle of a test through sign-out and sign-in again is slow and breaks the state of both. This lesson is about how to give each role its own session, how to put two users in one test, and how to check the unauthenticated state.

How it works and why. One role is one state file, and a state file acts at the context level. Contexts in one browser are fully isolated: one cannot see the other's cookies and localStorage. So two users at the same time means two contexts, each with its own storageState. That they work in one browser does not matter: it is the same as two different profiles.

Two roles in one test

one browser adminPageadmin.json clientPageclient.json cookies do not mix one backend: the admin's approvalshows to the client after reload
Figure 1. Isolated sessions, a shared backend: the roles are connected by state on the server, just like two real users.

One role per file or project. If a file checks only one role, test.use at the start of the file or describe is enough:

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

test.use({ storageState: 'playwright/.auth/admin.json' });

test('the administrator sees the list of requests', async ({ page }) => {
  await page.goto('/admin/requests');
  await expect(page.getByRole('heading', { name: 'Requests' })).toBeVisible();
});

A role can also be assigned to a project in the config: an admin project with its own state file and testMatch: /.*\.admin\.spec\.ts/, a client project with another. Then the role is determined by the test file name, and the report groups results by role.

Example: from switching the user to two contexts. The original version: one context, sign-out and sign-in in the middle of the test.

// before: the test goes through the form three times and holds one context
await loginAs(page, 'client');
await page.getByRole('button', { name: 'Submit request' }).click();
await logout(page);
await loginAs(page, 'admin');
await approveFirstRequest(page);
await logout(page);
await loginAs(page, 'client');   // one more login just to see the status

Three passes through the form, and if a sign-out ends the session on the server, there is also a risk of affecting another user. After: two fixtures, each with its own context.

import { test as base, type Page } from '@playwright/test';

type Roles = { adminPage: Page; clientPage: Page };

export const test = base.extend<Roles>({
  adminPage: async ({ browser }, use) => {
    const ctx = await browser.newContext({ storageState: 'playwright/.auth/admin.json' });
    await use(await ctx.newPage());
    await ctx.close();
  },
  clientPage: async ({ browser }, use) => {
    const ctx = await browser.newContext({ storageState: 'playwright/.auth/client.json' });
    await use(await ctx.newPage());
    await ctx.close();
  },
});
test('the administrator approves a client request', async ({ adminPage, clientPage }) => {
  await clientPage.goto('/loans/new');
  await clientPage.getByRole('button', { name: 'Submit request' }).click();

  await adminPage.goto('/admin/requests');
  await adminPage.getByRole('row').first().getByRole('button', { name: 'Approve' }).click();

  await clientPage.reload();
  await expect(clientPage.getByText('Approved')).toBeVisible();
});

A fixture creates its context only when a test asks for it and closes it after use. The order in the test stays natural: the actions of two people alternate, as in life. Note row.first(): in a shared environment the "first row" may be someone else's application, so it is more reliable to look for the row by data created by this test.

The logged-out state. The opposite situation: the project has a shared state configured, but you need to check a guest (a redirect to login, public pages). Then the state is reset with an empty snapshot:

test.describe('guest', () => {
  test.use({ storageState: { cookies: [], origins: [] } });

  test('a protected page redirects to login', async ({ page }) => {
    await page.goto('/account');
    await expect(page).toHaveURL(/login/);
  });
});

The same rule applies to your own contexts: browser.newContext() inherits the settings from use, including the project's storageState. To get a clean context, pass storageState: undefined.

SessionStorage. It does not end up in the snapshot. If the application keeps the session there, it is read in setup through page.evaluate(() => JSON.stringify(sessionStorage)), saved to a separate file and restored through context.addInitScript, which runs before the page's scripts. In the script it is worth checking window.location.hostname, so the values do not leak to third-party domains (for example, to an SSO page).

Limits. Two contexts give session isolation, but not data isolation: if the roles act in a shared environment, tests must still create their own entities. The role state files have to be prepared beforehand, usually by several setup tests. Each role adds a file and a login, so a role used by a single test is often simpler to create right in the fixture. In Cypress the analogue would be cy.session per role, but two users at once in one test are not an option there: Cypress drives a single tab and a single browser, so roles are switched one after another.

Common mistakes.

  • One context and switching the user through sign-out and sign-in in the middle of a test: slow, and the state of both roles gets spoiled.
  • A role baked into the state file while the test expects another: the error shows up as "element not found" rather than as a permissions problem.
  • A forgotten ctx.close() in your own fixtures: contexts pile up, and traces and videos are not finalised.
  • Resetting the state for a guest in one test only, while the neighbouring one expects a guest under the global state.
  • Approving the "first row" in a shared table: the test acts on someone else's data.

Check yourself

The project sets a user's storageState, and the test "a guest is redirected to login" opens the profile instead of login. What is wrong and how do you fix it?

Answer

The project's state applies to all tests, so the "guest" is actually logged in. Reset it in the describe or file: test.use({ storageState: { cookies: [], origins: [] } }).

Why does the clientPage fixture close the context after await use(...) instead of handing out the page and forgetting about it?

Answer

A context created by hand does not close itself. Without ctx.close() contexts pile up, and the traces and videos of these contexts are not finalised. The code after use runs after the test, so cleanup happens even when the test failed.

Why, in a two-role test, do admin and client not see each other's cookies although it is one browser?

Answer

The cookie and localStorage store belongs to a context, not to the browser. Each fixture creates its own context with a separate snapshot, so the sessions are isolated, like two different profiles.

In an interview. Junior: For scenarios with two roles I create two contexts, each with its own storageState, for example the fixtures adminPage and clientPage. For guest tests I reset the state with an empty storageState. Middle/Senior: Contexts isolate sessions but not data, so each test creates its own entities and does not rely on the "first row" of a shared table. I split roles of separate files by projects through testMatch, and I restore sessionStorage, which is not in the file, through addInitScript. I close my own contexts in the fixture so that traces finish.

More articles in this chapter