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

Playwright › Authentication and storageState

Login through the API in a setup project

In a setup project the session is obtained with a direct request to the login API and saved with request.storageState(). A token in localStorage needs more: it is written on a page of the app before the state is saved. When tests change account data, one shared user causes flaky failures in parallel, so use one user per worker. API login does not test the login form.

Playwright · Authentication

Logging in through the form in setup takes seconds and sometimes fails on an animation. Can you get a session without a browser?

The login form is already covered by separate tests, and going through it again in setup checks nothing new, but adds seconds and fragility: a selector, an animation, a cookie banner. If the application has a login API, the session can be obtained with a direct request. This lesson is about how to do that for a cookie session and for a token in localStorage, and what breaks when all parallel workers share one user.

How it works and why. The login form is just one way to send the server an "email, password" pair. The server replies with a Set-Cookie header or a body with a token, and the browser simply stores it. The request context (request) has a cookie store too and, on receiving Set-Cookie, keeps it the way a browser does. So request.storageState() produces a file in the same format as context.storageState(), and tests pick it up with no difference.

Two ways to get a session

Typical

Login through the UI

A browser starts, a page renders, a form is filled. It depends on selectors, animations and banners. Needed when the form itself is what is being tested.

Better

Login through the API

One POST with no rendering. Faster and more stable, while the login form gets its own tests. Does not fit when sign-in goes through SSO or 2FA without a test bypass.

Figure 1. Setup only prepares the session. Checking the login form itself stays a separate set of tests.

Example 1: a cookie session. If the application keeps its session in cookies, the request fixture is enough:

// auth.setup.ts
import { test as setup, expect } from '@playwright/test';

setup('admin login', async ({ request }) => {
  const res = await request.post('/api/auth/login', {
    data: { email: process.env.ADMIN_EMAIL, password: process.env.ADMIN_PASSWORD },
  });
  await expect(res).toBeOK();
  await request.storageState({ path: 'playwright/.auth/admin.json' });
});

The relative path works thanks to baseURL in the config. The cookie from the response lands in the request context, and request.storageState() saves it to a file.

Example 2: a token in localStorage. Here the API login alone is not enough, because the browser never received the token. It has to be written into localStorage of the right origin, and a browser page is needed only as a container for that origin:

setup('login with a token in localStorage', async ({ page, request }) => {
  const res = await request.post('/api/auth/login', {
    data: { email: process.env.USER_EMAIL, password: process.env.USER_PASSWORD },
  });
  await expect(res).toBeOK();
  const { token } = await res.json();

  await page.goto('/'); // the app's origin is needed to write into its localStorage
  await page.evaluate((t) => localStorage.setItem('token', t), token);
  await page.context().storageState({ path: 'playwright/.auth/user.json' });
});

There is also a variant without a page: write the state file yourself, in the format from the schema in the first lesson, with the app's origin and a token pair in origins. It is faster, but then the format is your responsibility: after a Playwright upgrade it is worth checking.

Example 3: one user for all workers breaks tests. A shared state file means one user for all parallel workers. While tests only read data, there is no problem. But suppose one test tops up a balance and another checks the cart total: alone they pass, together they sometimes fail because of someone else's changes. Such flaky tests do not reproduce in a single thread, and that is the main sign of a shared account.

One account or an account per worker

Typical

One file for all workers

Workers 0, 1 and 2 act as one user: they change the same balance, cart and settings. A test may see someone else's data and fail. A sign-out in one worker may log the others out on the server.

Better

An account per worker

Worker 0 works as user0, worker 1 as user1. The data does not overlap and failures reproduce. The price: the users must be created beforehand.

Figure 2. If tests change account state, isolation comes from a separate user per worker.

Implementation: a worker fixture logs in a user by parallelIndex and caches the state in a file with that index.

import { test as base, expect } from '@playwright/test';
import fs from 'node:fs';
import path from 'node:path';

export const test = base.extend<{}, { workerStorageState: string }>({
  // every test in a worker starts with the state of "its own" user
  storageState: ({ workerStorageState }, use) => use(workerStorageState),

  workerStorageState: [
    async ({ browser }, use) => {
      const id = test.info().parallelIndex;
      const file = path.resolve(test.info().project.outputDir, '.auth/' + id + '.json');
      if (!fs.existsSync(file)) {
        const ctx = await browser.newContext({ storageState: undefined });
        const res = await ctx.request.post('/api/auth/login', {
          data: { email: 'user' + id + '@test.app', password: process.env.USER_PASSWORD },
        });
        expect(res.ok()).toBeTruthy();
        await ctx.storageState({ path: file });
        await ctx.close();
      }
      await use(file);
    },
    { scope: 'worker' },
  ],
});

The users user0…userN must exist beforehand (created by seeding) or be created by this same fixture through the API. There must be at least as many as workers. Why storageState: undefined in newContext: a context created by hand inherits the settings from use, so without an explicit reset it would start with the project's state.

Token lifetime. If the session lives 15 minutes and a run takes 40, the tests at the end will start failing with 401, although everything was green at the start. The ways out: increase the TTL on the test environment, log in again in a fixture when needed, or write short tests with their own API login.

Limits. An API login does not check the login form, so it does not replace its tests. It is possible only when there is a stable login endpoint; for SSO and 2FA you usually need a test bypass on the environment's side, or a UI login once. It also ties the tests to the endpoint's contract: changing its format breaks setup.

Common mistakes.

  • An API login for an application with a token in localStorage without writing the token to a page: the state is saved but empty, and tests are logged out.
  • The user's password in code or in a file in the repository instead of environment variables.
  • One shared account for tests that change data: they pass alone and fail in parallel.
  • Fewer test users than workers: two workers share an account, and the flaky tests come back.
  • Ignoring the TTL: a long run ends with a wave of 401s.

Check yourself

After an API login, an application that keeps its token in localStorage opens logged out, although the state file is not empty. What was missed?

Answer

The file holds only the cookies from the response, while the browser never received the token, so it is not in localStorage. You need to open the application's page, write the token through page.evaluate and only then save the context state (or put the token into the file's origins).

Tests pass with --workers=1 and sometimes fail with four workers. All of them use admin.json. What is the hypothesis and what do you check first?

Answer

The hypothesis: parallel tests change shared data of one account. Check whether the failing tests read data that other tests write to this user's state (balance, cart, settings). The cure: a user per worker through parallelIndex, or data of its own for each test.

In an interview. Junior: In a setup project I can log in through the API and save storageState: it is faster and more stable than the form. If the application keeps its token in localStorage, I add it through page.evaluate. Middle/Senior: When tests change account data, a shared state file produces flaky tests only in parallel, so I make a user per worker with a worker fixture and parallelIndex. Separately I compare the session TTL with the run length and leave the login form to its own tests, because an API login does not check it.

More articles in this chapter