Authentication: Tokens, Test Accounts and storageState
On this page
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#
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#
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
409with{"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 mentions for apps where tests change server-side state.
The fixtures#
Create tests/fixtures.ts:
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:
-
accountis worker-scoped. The second type parameter ofextenddeclares 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 usesplaywright.request.newContext()rather than the test-scopedrequestfixture. -
tokenis 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, makingtokenworker-scoped too is a reasonable optimisation. -
apiis the logged-in client.extraHTTPHeaderson the context adds theAuthorizationheader to every call, so tests just callapi.get('/favorites'). -
Every context passes
baseURLexplicitly. 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?
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#
Create tests/api/auth.spec.ts. Note the import: tests now take test from the fixtures file.
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#
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 }:
// 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:
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?
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?#
For comparison, this is the same check through the login form, run with the same account:
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#
The setup project pattern (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.