Skip to main content
Free plan, no cardStart free

EngineeringHow-to guide

How to Test Login Flows and Authenticated Pages: Sign In Once, Save the State, Know When It Goes Stale

Logging in through the form in every test is slow and tests the wrong thing. Log in once, save the session, reuse it, and test the form on its own. We ran all three paths in three engines, and the stale-session case too.

Summarise with AI

Opens a new chat with only this request: Summarise the key points of this article: https://dokimore.com/blog/how-to-test-login-flows-and-authenticated-pages

118–608 msA login through the form, page load to the account page, in WebKit, Chromium and Firefox
160–313 msThe same account page from a saved session in a fresh context, no form
73–279 msLogin through the API with a CSRF token, cookie carried into a browser context
0 cookiesLeft in the saved state once the session’s Max-Age had passed; the page landed on /login

In short

  • Test the login form once, with its own assertions, then stop using it: sign in, call context.storageState({ path }), and start every other test from that file with new context({ storageState }). In our run the form took 118 to 608 ms per login across three engines and the saved session 160 to 313 ms, with no form, no password and no flakiness from a field that had not rendered.
  • When the login page is slow or protected, log in through the API: fetch the form for its CSRF token, post the credentials with request.post, and hand request.storageState() to a browser context. The server answered 302 and the cookie reached the browser in 73 to 279 ms.
  • A saved session expires. After the cookie’s Max-Age passed, a context started from the old file landed on /login with no cookie left in its state, and the page answered 200 for the login form, not an error. A test that reuses sessions must assert it is on the page it asked for, and a setup step must re-create the file when that assertion fails.

About this article

Format
How-to guide: a procedure to follow, step by step.
Written for
SDETs and automation engineers · Developers who own their tests · QA leads and test managers
Where it applies
Every market. The rules that differ by country are on the country pages.

A suite that logs in through the form before every test pays for it twice: in the seconds per test, and in the flakiness of a form that is the least-tested part of most applications. The pattern that works is to separate the two concerns. One test proves the form: wrong password refused, right password accepted, redirect to the right page. Every other test starts already signed in, from a session saved once.

This guide was run before it was written: a fixture login server with a CSRF token, an HttpOnly session cookie with a three-second Max-Age, and an account page that redirects to /login without a live session, driven by Playwright 1.62.1 in Chromium 151, Firefox 153 and WebKit 26.5. The cookie attributes, the timings and the stale-session behaviour below are from that run; scripts and raw output are linked at the end.

Path one: sign in through the form once, save the state

The first test is the one that exercises the form. It also does the saving: after the account page is reached, context.storageState writes the cookies and local storage to a file. The saved file in our run held one cookie, session, with HttpOnly true, SameSite Lax, Secure false (the fixture ran over plain HTTP; a production cookie should be Secure) and an expiry three seconds away, and no local-storage origins.

auth.setup.ts — the only test that touches the form
import { test as setup, expect } from '@playwright/test';

const STATE = 'playwright/.auth/user.json';

setup('sign in through the form and save the session', async ({ page, context }) => {
  await page.goto('/login');
  await page.getByLabel('User').fill('qa');
  await page.getByLabel('Password').fill(process.env.QA_PASSWORD ?? '');
  await Promise.all([
    page.waitForURL('**/account'),
    page.getByRole('button', { name: 'Sign in' }).click(),
  ]);
  await expect(page.locator('#who')).toHaveText('Signed in as qa');

  const state = await context.storageState({ path: STATE });
  const session = state.cookies.find((c) => c.name === 'session');
  expect(session?.httpOnly).toBe(true);          // the browser's script cannot read it
  expect(session?.sameSite).toBe('Lax');
});

Path two: every other test starts signed in

With the file saved, a new context created with storageState starts with the cookie already in its jar. Our fixture’s account page loaded with status 200 and the text "Signed in as qa" in 160 ms in Chromium, 283 ms in Firefox and 313 ms in WebKit, against 328, 608 and 118 ms for the form in the same engines. The saving is modest on a local fixture; on a real login page with a password manager prompt, a redirect to an identity provider and a second factor, it is the difference between a suite that runs and one that does not.

playwright.config.ts — a setup project, then projects that depend on it
export default defineConfig({
  projects: [
    { name: 'setup', testMatch: /.*\.setup\.ts/ },
    {
      name: 'chromium',
      use: { ...devices['Desktop Chrome'], storageState: 'playwright/.auth/user.json' },
      dependencies: ['setup'],
    },
  ],
});

// account.spec.ts — no form, no password
test('the account page shows the signed-in user', async ({ page }) => {
  const response = await page.goto('/account');
  expect(response?.status()).toBe(200);
  await expect(page).toHaveURL(/\/account$/);        // NOT /login: the session is live
  await expect(page.locator('#who')).toHaveText('Signed in as qa');
});

Path three: log in through the API

Some login pages are slow, behind a bot check, or owned by an identity provider you cannot script. If the login endpoint takes a form post, the test can post it directly. Our fixture required a CSRF token from the form; the test fetched the login page with a request context, read the token, posted the credentials with maxRedirects: 0, and received a 302 with the Set-Cookie. request.storageState() then carried that cookie into a browser context, where a call to /api/me answered 200 with the signed-in user, in 73 ms in Chromium, 212 ms in Firefox and 279 ms in WebKit.

api-login.setup.ts — the form post without the form
import { request } from '@playwright/test';

const api = await request.newContext({ baseURL: process.env.BASE_URL });
const loginHtml = await (await api.get('/login')).text();
const csrf = /name="csrf" value="([^"]+)"/.exec(loginHtml)?.[1] ?? '';

const response = await api.post('/login', { form: { csrf, user: 'qa', pass: process.env.QA_PASSWORD ?? '' }, maxRedirects: 0 });
expect(response.status()).toBe(302);               // the server set the cookie and redirected

await api.storageState({ path: 'playwright/.auth/user.json' });   // the cookie, for the browser projects
await api.dispose();

The case that catches everyone: the session goes stale

The fixture’s session lived three seconds, so the run could show what happens when a saved state outlives its session. A context created from the old file after that time requested /account, was redirected, and landed on /login. Two details matter. The response status was 200, because the login page loaded fine: nothing in the HTTP layer says "your session expired". And the context’s own storage state had zero cookies afterwards, because the expired cookie was dropped, so a test that checks "do I have a cookie" sees the problem only after the fact. The assertion that catches it is the URL: a test that asked for /account must assert it is on /account.

The practical arrangement: the setup project re-creates the state file at the start of every run, or checks the saved file’s cookie expiry and re-creates it when it is close; the tests assert their URL; and a login page that appears where an account page was expected is reported as "session expired", not as a locator timeout on #who.

In the product

Cookie attributes a login test should assert

  • HttpOnly: true, so a script on the page cannot read the session; our fixture set it and the saved state shows it.
  • Secure: true on any HTTPS site. The fixture ran on HTTP and the saved state recorded false, which is what a production test should flag.
  • SameSite: Lax or Strict, which blocks the cookie from most cross-site requests.
  • An expiry that matches the product’s policy. Max-Age must be a whole number of seconds: the first run of our script sent Max-Age=2.5 and every engine ignored it and kept a session cookie, exactly as RFC 6265 says a non-digit value must be treated.
  • For a token in local storage instead of a cookie, the state file holds it under origins, and the same expiry test applies to the token’s exp claim; the JWT decoder reads it.

How Dokimore handles a login in a recording

A login typed during a recording is kept, encrypted, so the replay can sign in; credentials for scheduled runs belong in the credential vault rather than in the test. The replay engine runs on Playwright, so a recorded login followed by a protected page is the first path above, with the session reuse handled per run, and a step that lands on the login page instead of the page it expected fails with that page in its screenshot.

What to do next

  1. Split your suite into one login-form test and everything else starting from a saved storageState; measure the run time before and after.
  2. Add toHaveURL to every test that opens a protected page, so an expired session reports as "landed on /login" rather than as a timeout on an element.
  3. Re-create the state file in a setup project on every run, or check its cookie expiry first; a stale file is the commonest cause of a whole suite failing at once.
  4. Assert HttpOnly, Secure and SameSite on the session cookie in the login test; the saved state file carries all three.
  5. Where the login page is slow or protected, post to the login endpoint with its CSRF token and carry the cookie in through request.storageState().

Questions people ask

How do I reuse a login across Playwright tests?

Sign in once in a setup project, save the session with context.storageState({ path }), and give every other project that file as its storageState. A new context then starts with the cookie in its jar; in our run the account page loaded signed-in in 160 to 313 ms with no form, against 118 to 608 ms through the form.

How do I log in with Playwright without using the login page?

Post the form to the login endpoint from a request context: fetch the login page for its CSRF token, request.post the credentials with maxRedirects: 0, check for the 302, then request.storageState() to carry the cookie into a browser context. The fixture answered 302 and the browser’s /api/me call returned the signed-in user in 73 to 279 ms.

Why do all my tests suddenly fail at the login page?

The saved session expired. After the cookie’s Max-Age passed in our run, a context from the old file was redirected to /login with status 200 and no cookie left in its state. Re-create the state file in a setup project each run and assert the URL in every test so the failure says "session expired", not "element not found".

Which cookie attributes should a login test check?

HttpOnly true, Secure true on HTTPS, SameSite Lax or Strict, and an expiry that matches the product’s policy. The saved state file exposes all four. Max-Age must be a whole number of seconds; a fractional value was ignored by all three engines in our first run, as RFC 6265 requires.

How we measured this

  • Run on 2026-11-04 with Playwright 1.62.1 and its pinned builds (Chromium 151.0.7922.34, Firefox 153.0, WebKit 26.5), networking disabled, fixture server on 127.0.0.1 with a CSRF-protected form, an HttpOnly SameSite=Lax session cookie with a three-second Max-Age, and server-side expiry. Scripts and raw output: docs/marketing/keyword-research/research/playwright-guides-2026-11-04 (e5-login.js, out/e5-login.json).
  • Two runs. The first set Max-Age=2.5; all three engines ignored it and recorded a session cookie with no expiry, so the stale-session case could not be measured from the cookie’s side. The second run set Max-Age=3 and is the one reported. Timings are Date.now() around each path as seen by the test, one run per path per engine.
  • The measurements used the library API; the snippets show the same calls as a Playwright Test setup project and config, which is how a reader would arrange them.
  • Dokimore’s behaviour is the product code on the article date: a login typed during a recording is kept encrypted for the replay, and credentials for scheduled runs live in the vault.

Sources

  1. Playwright documentation, Authentication: sign in once in a setup project, storageState per project, and the note that stored state must be deleted when it expires read
  2. Playwright documentation, APIRequestContext: request contexts, storageState() with cookies and local storage read
  3. RFC 6265, HTTP State Management Mechanism: the Max-Age attribute is digits only and the HttpOnly attribute keeps a cookie from scripts read
  4. Playwright documentation, Browsers: each release pins its own browser builds read

See it on your own project

Every new account starts a 14-day Solo Pro trial, then 14 days on the Free plan. No card. Record one flow and measure the difference on your own numbers.

  • Free plan, no card
  • 14-day Solo Pro trial
  • Demo replies within one business day
  • Data hosted in India