---
title: 'Authentication: Tokens, Test Accounts and storageState'
description: Real APIs sit behind a login. This chapter gets a token through the API,
  wraps it in fixtures so tests never repeat the login code, gives every parallel…
source_url:
  html: https://testingbot.com/resources/courses/playwright-api-testing/authentication-and-tokens
  md: https://testingbot.com/resources/courses/playwright-api-testing/authentication-and-tokens.md
---

Course

[Playwright API Testing Tutorial](https://testingbot.com/resources/courses/playwright-api-testing)

Chapter 4 of 9

1. [1 Playwright API Testing: a Hands-On Course](https://testingbot.com/resources/courses/playwright-api-testing)
2. [2 The request Fixture and APIRequestContext](https://testingbot.com/resources/courses/playwright-api-testing/the-request-fixture)
3. [3 Asserting Status, Headers and JSON](https://testingbot.com/resources/courses/playwright-api-testing/asserting-status-headers-and-json)
4. [4 Authentication: Tokens, Test Accounts and storageState](https://testingbot.com/resources/courses/playwright-api-testing/authentication-and-tokens)
5. [5 Test Data Setup and Teardown Through the API](https://testingbot.com/resources/courses/playwright-api-testing/test-data-setup-through-the-api)
6. [6 Schema Validation with zod and ajv](https://testingbot.com/resources/courses/playwright-api-testing/schema-validation)
7. [7 Mocking APIs with page.route](https://testingbot.com/resources/courses/playwright-api-testing/mocking-with-page-route)
8. [8 Running API and UI Tests in CI and on a Cloud Grid](https://testingbot.com/resources/courses/playwright-api-testing/ci-and-the-cloud-grid)
9. [9 Knowledge Check](https://testingbot.com/resources/courses/playwright-api-testing/knowledge-check)

[Exit course](https://testingbot.com/resources/courses)

 Chapter 4 of 9 Intermediate 10 min read 2 quick checks Updated Nov 2026 

# Authentication: Tokens, Test Accounts and storageState
On this page
1. [What the shop's API expects](https://testingbot.com#what-the-shop-s-api-expects)
2. [Why one account per worker](https://testingbot.com#why-one-account-per-worker)
3. [The fixtures](https://testingbot.com#the-fixtures)
4. [API tests that use the fixtures](https://testingbot.com#api-tests-that-use-the-fixtures)
5. [Starting the browser logged in](https://testingbot.com#starting-the-browser-logged-in)
6. [How much faster is it?](https://testingbot.com#how-much-faster-is-it)
7. [When a saved state file is the better fit](https://testingbot.com#when-a-saved-state-file-is-the-better-fit)

Real APIs sit behind a login. This chapter gets a token through the API, wraps it in fixtures so tests never repeat the login code, gives every parallel worker its own account, and then reuses the same token to start browser tests already logged in. That last step is where API testing starts paying for your UI suite.

## What the shop's API expects[#](https://testingbot.com#what-the-shop-s-api-expects)

The Toolshop uses bearer tokens. `POST /users/login` with an email and password returns a token, and protected endpoints expect it in an `Authorization: Bearer ...` header. The login response looks like this:

```
{"access_token":"<JWT>","token_type":"bearer","expires_in":300}
```

`expires_in: 300` means the token is valid for **five minutes**. Short-lived tokens are common, and they decide the design below: a token saved at the start of a long run may be dead before the last test uses it.

Without a token, protected endpoints answer `401`. That is worth a test of its own, because "the endpoint forgot to check auth" is a serious bug that no happy-path test catches.

## Why one account per worker[#](https://testingbot.com#why-one-account-per-worker)

The shop has a few public demo customers, and the obvious move is to log in as one of them. Two problems with that:

- **Your own parallel tests collide.** With four workers, four tests add and remove favorites on the same account at the same time. A test that asserts "my favorites list is empty" fails whenever another worker's favorite is in the list. The API even refuses duplicates: adding the same product twice answers `409` with `{"message":"Duplicate Entry"}`.
- **Everyone else collides with you.** On a public demo, other people use the same customer.

The fix is an account per worker, created through the API when the worker starts. Workers run tests one at a time, so within a worker there is no collision, and no two workers share data. This is the same idea the [Playwright course](https://testingbot.com/resources/courses/playwright/fixtures-hooks-and-authentication) mentions for apps where tests change server-side state.

## The fixtures[#](https://testingbot.com#the-fixtures)

Create `tests/fixtures.ts`:

```typescript
import { test as base, expect, type APIRequestContext } from '@playwright/test';
import { API_URL, UI_URL } from '../lib/env';

type Account = { id: string; email: string; password: string };

export const test = base.extend<
  { token: string; api: APIRequestContext },
  { account: Account }
>({
  // One fresh shop customer per worker: parallel workers never share data.
  account: [async ({ playwright }, use, workerInfo) => {
    const anon = await playwright.request.newContext({ baseURL: API_URL });
    const email = `pw-api-${Date.now()}-${workerInfo.workerIndex}@example.com`;
    const password = 'Str0ng!Passw0rd-42';
    const response = await anon.post('/users/register', {
      data: {
        first_name: 'Course', last_name: 'Worker', email, password,
        dob: '1990-01-01', phone: '0612345678',
        address: { street: 'Main 1', city: 'Brussels', country: 'BE', postal_code: '1000' },
      },
    });
    expect(response.status(), await response.text()).toBe(201);
    const { id } = await response.json();
    await anon.dispose();
    await use({ id, email, password });
  }, { scope: 'worker' }],

  // Shop tokens expire after five minutes, so log in per test.
  token: async ({ account, playwright }, use) => {
    const anon = await playwright.request.newContext({ baseURL: API_URL });
    const response = await anon.post('/users/login', {
      data: { email: account.email, password: account.password },
    });
    await expect(response).toBeOK();
    const { access_token } = await response.json();
    await anon.dispose();
    await use(access_token);
  },

  // An API client that is already logged in as this worker's customer.
  api: async ({ playwright, token }, use) => {
    const api = await playwright.request.newContext({
      baseURL: API_URL,
      extraHTTPHeaders: {
        Accept: 'application/json',
        Authorization: `Bearer ${token}`,
      },
    });
    await use(api);
    await api.dispose();
  },
});

export { expect };
```

(The file grows two more exports later in this chapter and in chapter 7.)

How the pieces fit:

- **`account` is worker-scoped.** The second type parameter of `extend` declares worker fixtures, and `{ scope: 'worker' }` makes it run once per worker process. Worker fixtures can only depend on other worker fixtures, which is why it uses `playwright.request.newContext()` rather than the test-scoped `request` fixture.
- **`token` is test-scoped** , so every test gets a token that is seconds old. One extra login call per test costs a few hundred milliseconds, which buys you a suite that does not break when a run takes longer than five minutes. If your tokens live for hours, making `token` worker-scoped too is a reasonable optimisation.
- **`api` is the logged-in client.** `extraHTTPHeaders` on the context adds the `Authorization` header to every call, so tests just call `api.get('/favorites')`.
- **Every context passes `baseURL` explicitly.** As chapter 1 showed, contexts created inside a test inherit the project's options, and in a browser project that would be the UI host.
- `expect(response.status(), await response.text())` means a failed registration shows the API's validation errors in the report instead of a bare "expected 201".

One limitation of the demo: a customer cannot delete their own account (`DELETE /users/{id}` answers `403`), so these accounts stay behind. In your own application, delete the account after `use()` in the worker fixture, or point the suite at a test environment that is reset regularly.

The API's tokens expire after five minutes. You log in once in a setup project, save the token, and the suite takes eight minutes. What do you expect?

 Nothing changes: Playwright refreshes tokens automatically The setup project fails after five minutes Tests that run after the five-minute mark start failing with `401`, so the failures depend on test order and timing The suite gets faster because no test logs in

The saved token is just a string; nothing renews it. Late tests fail with 401 while early ones pass, which looks like flakiness. Logging in per test (or per worker, if tokens live long enough) avoids it.

## API tests that use the fixtures[#](https://testingbot.com#api-tests-that-use-the-fixtures)

Create `tests/api/auth.spec.ts`. Note the import: tests now take `test` from the fixtures file.

```typescript
import { test, expect } from '../fixtures';

test('favorites need a token', async ({ request }) => {
  const response = await request.get('/favorites');
  expect(response.status()).toBe(401);
});

test('the token identifies the customer', async ({ api, account }) => {
  const response = await api.get('/users/me');

  await expect(response).toBeOK();
  expect(await response.json()).toMatchObject({ id: account.id, email: account.email });
});

test('a new customer starts with no favorites', async ({ api }) => {
  const response = await api.get('/favorites');

  await expect(response).toBeOK();
  expect(await response.json()).toEqual([]);
});
```

```
✓ 3 [api] › tests/api/auth.spec.ts:8:1 › the token identifies the customer (341ms)
  ✓ 1 [api] › tests/api/auth.spec.ts:15:1 › a new customer starts with no favorites (384ms)
  ✓ 4 [api] › tests/api/auth.spec.ts:3:1 › favorites need a token (389ms)
```

The first test uses the plain `request` fixture on purpose: it has no `Authorization` header, which is exactly the case under test. The third test can assert an empty list with `toEqual([])` only because the account is fresh and owned by this worker; on a shared account it would be flaky.

## Starting the browser logged in[#](https://testingbot.com#starting-the-browser-logged-in)

To reuse the token in the browser you need to know where the front end keeps its session. Log in through the UI once and look at the saved state, for example with `await page.context().storageState()` printed to the console. For the Toolshop it contains no session cookie, but this:

```
"origins":[{"origin":"https://practicesoftwaretesting.com","localStorage":[{"name":"auth-token","value":"eyJ0eXAiOiJKV1Qi..."}]}]
```

The Angular app reads its token from `localStorage` under `auth-token`. So a browser context created with that entry starts logged in, and `storageState` accepts an object as well as a file path. Add this to `tests/fixtures.ts`, above `export { expect }`:

```typescript
// For UI tests of the logged-in shop: the token lives in localStorage.
export const uiTest = test.extend({
  storageState: async ({ token }, use) => {
    await use({
      cookies: [],
      origins: [{ origin: UI_URL, localStorage: [{ name: 'auth-token', value: token }] }],
    });
  },
});
```

`storageState` is a Playwright option, and options are fixtures too, so you can override it with a function that depends on your own `token` fixture. Every browser context in a test that uses `uiTest` now starts with a fresh token in place.

Why a separate `uiTest` instead of putting the override into `test`? Playwright resolves `storageState` for every test, even one that only uses `request`, because the built-in context options are set up automatically. With the override in the base `test`, each API test would also log in (and, in its first test, register a worker account) for a browser it never opens. A quick experiment with a `console.log` in the `token` fixture shows it running for a test that only asks for `request`. Keep fixtures with side effects off the path of tests that do not need them.

Now the test, `tests/ui/login.spec.ts`:

```typescript
import { uiTest as test, expect } from '../fixtures';

test('starts logged in with an API token', async ({ page, account }) => {
  await page.goto('/account/profile');

  await expect(page.getByTestId('email')).toHaveValue(account.email);
});
```

```
✓ 1 [chromium] › tests/ui/login.spec.ts:3:1 › starts logged in with an API token (1.7s)
  ✓ 2 [firefox] › tests/ui/login.spec.ts:3:1 › starts logged in with an API token (2.3s)
```

The profile page shows the email of the worker's own account, which proves the browser is logged in as the user the API created.

You inject an API token into the browser through `storageState`, but the app still shows the login page. What do you check first?

 Where the app really keeps its session (cookie name, localStorage key, origin), by saving the state after a manual UI login and comparing Whether the test needs `page.waitForTimeout()` before `goto` Whether the API token is longer than 255 characters

storageState only helps if you put the token exactly where the front end looks for it, under the right origin. Saving the state after a real login shows you the cookie or storage key to copy. Waiting changes nothing.

## How much faster is it?[#](https://testingbot.com#how-much-faster-is-it)

For comparison, this is the same check through the login form, run with the same account:

```typescript
test('log in through the form', async ({ page, account }) => {
  await page.goto('/auth/login');
  await page.getByTestId('email').fill(account.email);
  await page.getByTestId('password').fill(account.password);
  await page.getByTestId('login-submit').click();

  await expect(page.getByTestId('page-title')).toHaveText('My account');
});
```

On a local Chromium run, three repetitions of each took 1.3 to 1.8 seconds through the form and 0.95 to 1.5 seconds with the injected token. Under a second per test is a modest saving on a form this simple; on a login with redirects, single sign-on or a second factor it is much larger. The bigger gains are elsewhere: tests that are not about login no longer fail when the login page breaks or changes, and the next chapter applies the same idea to the data a test needs, which is usually far more expensive to create through the UI than a login.

Keep a few real UI login tests, of course. The login form is a feature, and it deserves tests that use it.

## When a saved state file is the better fit[#](https://testingbot.com#when-a-saved-state-file-is-the-better-fit)

The [setup project pattern](https://testingbot.com/resources/courses/playwright/fixtures-hooks-and-authentication) (log in once, save `storageState` to a file, reuse it in every test) is the right default when sessions last longer than a run, typically cookie-based sessions. You can do that login through the API as well: a `request` context collects the cookies from a login response, and `request.storageState({ path })` writes them to the same kind of file a browser login would. Choose per test or per worker logins, as in this chapter, when tokens are short-lived or when each worker needs its own user.

[Previous · Chapter 3 Asserting Status, Headers and JSON](https://testingbot.com/resources/courses/playwright-api-testing/asserting-status-headers-and-json) [Next · Chapter 5 Test Data Setup and Teardown Through the API](https://testingbot.com/resources/courses/playwright-api-testing/test-data-setup-through-the-api)

On this page

1. [What the shop's API expects](https://testingbot.com#what-the-shop-s-api-expects)
2. [Why one account per worker](https://testingbot.com#why-one-account-per-worker)
3. [The fixtures](https://testingbot.com#the-fixtures)
4. [API tests that use the fixtures](https://testingbot.com#api-tests-that-use-the-fixtures)
5. [Starting the browser logged in](https://testingbot.com#starting-the-browser-logged-in)
6. [How much faster is it?](https://testingbot.com#how-much-faster-is-it)
7. [When a saved state file is the better fit](https://testingbot.com#when-a-saved-state-file-is-the-better-fit)

Certification

Earn the free, resume-worthy TestingBot Playwright API Testing Certification for this course.

[How it works](https://testingbot.com/resources/courses/playwright-api-testing/certification)
