Authentication and state

Sign in once, save the storage state, and load it into later browser contexts that need authentication.

  • Save Cookies and local storage, written to a file
  • Isolation Several roles in one script
  • Other doors HTTP basic auth, cookies, headers
Save

Cookies and local storage, written to a file

Run the login form once, then serialise the context. Treat the JSON as sensitive by default: rebuild it in CI, or commit only a deliberately sanitised fixture.

Reuse a login session →
// after logging in, once
$context->storageState(['path' => 'auth.json']);

// in later authenticated tests
$context = $browser->newContext([
    'storageState' => 'auth.json',
]);
Isolation

Several roles in one script

One state file per role, one context per state. An admin and a visitor can act on the same page in the same test without logging each other out.

Core concepts →
Other doors

HTTP basic auth, cookies, headers

Not every application logs in through a form. Credentials, cookies set before the first navigation, and carefully-scoped context options keep authentication setup explicit.

HTTP basic authentication →
Next step

Move from the tour to working code.

Choose the explanation, recipe, or runnable example that matches what you need next.

Common questions

Before you wire it into a suite.

Should every test log in through the UI?
No. Keep one login test for the login flow, then reuse storage state for tests where authentication is only setup.
Can I test several users at once?
Yes. Create one context per role or account. Context isolation keeps cookies and storage from leaking between users.
Is storage state safe to commit?
Only commit state that contains no secrets and can be regenerated. For real credentials, rebuild the state in CI and keep secrets in the CI secret store.