PRACTICAL GUIDE / playwright authentication interview questions

18 Playwright Authentication and storageState Interview Scenarios

Study 18 senior Playwright authentication scenarios covering storageState, multiple roles, parallel accounts, session risk, secrets, and isolation.

By The Testing AcademyUpdated July 11, 202610 min read
All field guides
In this guide8 sections
  1. Reason From the Authentication Constraint
  2. State Reuse and Login Coverage
  3. 1. Why would you use storageState for most authenticated tests?
  4. 2. Why should storage-state files be treated like credentials?
  5. 3. How would you decide whether to authenticate through UI or API?
  6. 4. How should a setup project prove that saved state is usable?
  7. Roles and Authorization Boundaries
  8. 5. Why does each role need a separate state file?
  9. 6. How would you test an admin approving a request created by a member?
  10. 7. Why is a positive admin test insufficient for role-based access control?
  11. Parallel Accounts and Mutable State
  12. 8. When can all tests safely share one authenticated account?
  13. 9. How would you allocate accounts to parallel workers?
  14. 10. Why might a test-scoped account be necessary despite higher setup cost?
  15. 11. How should retries affect an account strategy?
  16. Session Storage, Expiry, and Revocation
  17. 12. Why can a storageState restore fail for an application using sessionStorage?
  18. 13. How would you test an expired session without waiting in real time?
  19. 14. How would you verify logout invalidates the session rather than only clearing the UI?
  20. Context Isolation and Secret Safety
  21. 15. Why is a new browser context the correct boundary between identities?
  22. 16. How would you diagnose authentication that works through API setup but fails in the browser?
  23. 17. How can traces and screenshots leak authentication data?
  24. 18. How would you review a suite that logs in every test with one admin account?
  25. Authentication Review Checklist
  26. Conclusion: Reuse State Without Reusing Risk

What you will learn

  • Reason From the Authentication Constraint
  • State Reuse and Login Coverage
  • Roles and Authorization Boundaries
  • Parallel Accounts and Mutable State

Authentication interviews are architecture interviews in disguise. A candidate must balance realistic login coverage against suite speed, protect credentials and serialized sessions, and keep accounts isolated when workers run concurrently. The wrong shortcut can make a test fast while invalidating its permission model.

Each scenario below asks for a boundary: which authentication path is under test, which state may be reused, who owns the account, and what happens when the session expires or is revoked. Senior answers state the threat and mutation model before proposing a fixture or setup project.

Reason From the Authentication Constraint

The official Playwright authentication guide recommends saving authenticated browser state for tests that can safely reuse an account and provides different patterns for parallel mutation and multiple roles. Use that decision tree instead of treating storageState as a universal login bypass.

Animated field map

Authentication Strategy Interview Flow

A senior answer chooses reusable state only after accounting for role boundaries, parallel mutation, secret exposure, and session risk.

  1. 01 / auth constraint

    Authentication constraint

    Identify login coverage, roles, expiry, and identity provider rules.

  2. 02 / state strategy

    State strategy

    Choose UI login, API setup, or protected reusable state.

  3. 03 / parallel isolation

    Parallel isolation

    Allocate identities according to mutation and worker behavior.

  4. 04 / secret handling

    Secret handling

    Protect credentials, cookies, tokens, traces, and files.

  5. 05 / risk analysis

    Candidate risk analysis

    Defend realism, revocation, cleanup, and evidence.

An interview answer should also say what is intentionally not covered. API-assisted sign-in for an order test is reasonable only when separate tests prove the login UI, redirects, error states, and identity-provider integration.

State Reuse and Login Coverage

1. Why would you use storageState for most authenticated tests?

It lets a fresh browser context start with previously established authentication, avoiding repeated UI login in scenarios that do not test login. This improves focus and reduces dependency on an external identity flow. I would generate the state through a controlled setup project, confirm the account is suitable for sharing, and keep dedicated tests for the real login experience. Reuse is an optimization, not a substitute for authentication coverage.

2. Why should storage-state files be treated like credentials?

They can contain cookies and origin data that allow the browser to act as the user without knowing the password. I would keep them under an ignored directory, restrict CI artifacts, prevent accidental attachments, and regenerate rather than commit them. File names may identify roles but should not include personal information. Cleanup should delete temporary state when the run's retention policy does not require it.

3. How would you decide whether to authenticate through UI or API?

Use UI authentication when the login journey, redirects, validation, or identity-provider integration is the behavior under test. Use a documented API or setup endpoint when authentication is only a prerequisite and the resulting browser state is equivalent. I would verify cookie domain, flags, origin storage, and post-login bootstrap behavior. Directly injecting a guessed token is weaker because it can skip application initialization.

4. How should a setup project prove that saved state is usable?

After completing authentication, it should assert a stable signed-in signal before writing state, such as an account menu or authenticated API response. It should fail with safe diagnostics if the expected identity is wrong. The setup test should not merely save whatever cookies happen to exist after navigation. Dependent projects then consume a state file whose role and successful login were explicitly verified.

TypeScript
const adminState = 'playwright/.auth/admin.json'

setup('authenticate admin', async ({ page }) => {
  await page.goto('/login')
  await page.getByLabel('Email').fill(process.env.ADMIN_EMAIL!)
  await page.getByLabel('Password').fill(process.env.ADMIN_PASSWORD!)
  await page.getByRole('button', { name: 'Sign in' }).click()

  await expect(page.getByRole('button', { name: 'Admin menu' })).toBeVisible()
  await page.context().storageState({ path: adminState })
})

Roles and Authorization Boundaries

5. Why does each role need a separate state file?

A state file represents one authenticated identity and permission set. Separate files make the selected role visible in project or context configuration and prevent an admin session from leaking into a member test. I would generate each role independently, verify its identity, and use names that reveal role but no secrets. Authorization assertions should still test allowed and denied operations, not infer permissions from the file name.

6. How would you test an admin approving a request created by a member?

I would create two isolated contexts from separate member and admin states within one test. The member creates the request, the admin observes and approves it, and the member verifies the resulting status. Each context retains its own cookies and storage. I would close both contexts in finally or fixture teardown and use a unique request ID so parallel scenarios do not cross-talk.

TypeScript
test('admin approves a member request', async ({ browser }) => {
  const member = await browser.newContext({ storageState: 'playwright/.auth/member.json' })
  const admin = await browser.newContext({ storageState: 'playwright/.auth/admin.json' })

  try {
    const memberPage = await member.newPage()
    const adminPage = await admin.newPage()
    const requestId = await createRequestFrom(memberPage)
    await approveRequestFrom(adminPage, requestId)
    await expect(memberPage.getByTestId(`request-${requestId}`)).toContainText('Approved')
  } finally {
    await member.close()
    await admin.close()
  }
})

7. Why is a positive admin test insufficient for role-based access control?

It proves only that one privileged identity can perform an operation. I would pair it with a lower-privilege UI and API denial check, direct URL navigation, and server response validation where relevant. Hiding a button is not authorization. The application must reject the operation at its trusted boundary. The test data should identify which role, resource owner, and action form the expected policy.

Parallel Accounts and Mutable State

8. When can all tests safely share one authenticated account?

Only when tests are effectively read-only and do not change server or session state that another test observes. Even apparently harmless actions can mutate recent items, notifications, preferences, or last-login metadata. I would inventory those side effects and monitor for collisions. If uncertainty remains, use one account per worker or test. Sharing should be a proven constraint, not the default because state generation is inconvenient.

9. How would you allocate accounts to parallel workers?

I would lease a unique account using workerInfo.parallelIndex or a CI-aware external pool, authenticate it once for that worker, and ensure tests within the worker respect the allowed mutation model. The lease includes a run identifier and cleanup policy. Retries may recreate workers, so acquisition must be repeatable and abandoned leases recoverable. A static modulo operation without exclusive leasing can collide across shards.

10. Why might a test-scoped account be necessary despite higher setup cost?

Use it when a scenario changes credentials, permissions, subscription, destructive data, or session validity. Those mutations can invalidate every other test sharing the identity. A test-scoped account gives the failure a clean initial state and allows decisive cleanup. I would optimize creation through approved APIs and parallel-safe data factories rather than weakening isolation. The extra cost buys deterministic ownership of the tested state.

11. How should retries affect an account strategy?

Each attempt must begin from a valid known state. A test-scoped account can be recreated with a new unique key. A worker account may survive or be re-leased if the worker restarts, so correctness cannot depend on persistence. I would make mutations idempotent where possible and record attempt identity in created data. A retry that passes only because it gets a different account exposes contamination.

Session Storage, Expiry, and Revocation

12. Why can a storageState restore fail for an application using sessionStorage?

Standard saved authentication state does not persist browser sessionStorage. If the application relies on it, cookies and local storage alone may not establish the session. I would first question whether session storage is truly the auth boundary, then use a documented initialization approach if needed. Any init script must be origin-scoped and should not become a secret-dumping workaround. The limitation belongs in the framework design notes.

13. How would you test an expired session without waiting in real time?

I would control the boundary the application actually uses. For client timers, Playwright's clock can advance page time; for server token expiry, use a test-issued short-lived session, a controlled backend clock, or revoke the token through an API. Then attempt a protected action and assert refresh or rejection. Changing only browser time is insufficient when the server independently validates timestamps.

14. How would you verify logout invalidates the session rather than only clearing the UI?

After logout, I would attempt a protected API call and direct navigation in the same context, then expect an unauthorized response or login redirect. I would also consider copying the pre-logout cookie into an isolated controlled request to confirm server-side invalidation when that is the product contract. Merely checking that the avatar disappeared proves presentation, not revocation. The test must avoid printing the token.

Context Isolation and Secret Safety

15. Why is a new browser context the correct boundary between identities?

Contexts isolate cookies and browser storage while sharing the browser process efficiently. Two pages in one context share session data, so they are not independent users. For multi-role interaction, I would create one context per identity using the correct state. The browser-context guidance also makes the resulting topology explicit and easier to close after the scenario.

16. How would you diagnose authentication that works through API setup but fails in the browser?

I would compare cookie domain, path, secure and same-site behavior, target origin, local storage, redirects, and application bootstrap calls. I would confirm the request context used the expected base URL and that state was captured after the final response. Then inspect browser network and console traces without exposing cookie values. The failure usually indicates the API state is not equivalent to a browser-completed session.

17. How can traces and screenshots leak authentication data?

Login fields, one-time codes, query parameters, response payloads, local storage, and visible account details can all enter artifacts. I would minimize tracing around credential entry when policy requires it, redact application logs, use synthetic accounts, and restrict artifact access and retention. Masking a password input alone is not enough. Security review should cover reporter attachments and custom debugging output as well as Playwright defaults.

18. How would you review a suite that logs in every test with one admin account?

I would separate login coverage from authenticated prerequisites, inventory which tests truly need admin, and identify shared mutations. Then introduce role-specific setup states for safe read-only lanes and isolated accounts for mutating cases. Authorization tests receive least-privilege identities. I would measure reliability through parallel and retry runs, protect generated state, and remove credentials from helper arguments and logs. The migration improves both speed and policy confidence.

Authentication Review Checklist

  • State which login path is tested and which is only prerequisite setup.
  • Give every role and mutable identity an explicit owner.
  • Verify saved state only after the expected signed-in identity is observable.
  • Keep state files, credentials, tokens, and traces out of source control and public artifacts.
  • Use separate contexts for users who interact in one scenario.
  • Test server-side authorization and revocation, not only visible navigation.
  • Exercise expiry, retry, and parallel behavior with deterministic test data.

Conclusion: Reuse State Without Reusing Risk

An effective authentication strategy skips redundant login steps without skipping security boundaries. Reuse state only for identities proven safe to share, isolate roles in separate contexts and files, and use fresh accounts whenever a test mutates the session or permission model. The senior answer always includes artifact protection, expiry behavior, and a denial path. Fast authentication setup is valuable only when the resulting test still represents the right user and the right trust boundary.

// LIVE COURSE / THE TESTING ACADEMY

Playwright Automation Mastery

Go beyond Selenium. Master Playwright with JS/TS in 90 days.

From the instructor behind this guide.

Playwright jobs are growing 8x faster than Selenium. 90 days / 75+ live hrs / Tue-Thu-Sat 7 AM IST.

Code PROMODE / 10% offJoin the batch

The Testing Academy editorial desk

Practical QA guidance built around test evidence, production tradeoffs, and interview-ready explanations.

Published July 11, 2026 / Reviewed July 11, 2026

PRIMARY REFERENCES

Verify the details at the source

QABattle guides are practical explanations. Product behavior, standards, and APIs can change, so use these primary references for the canonical details.

  1. 01
    Playwright documentation

    Microsoft

    Canonical API, locator, fixture, browser, and test-runner behavior.

  2. 02
    Playwright best practices

    Microsoft

    Official guidance for resilient tests, isolation, and user-facing locators.

  3. 03
    Web Security Testing Guide

    OWASP Foundation

    Primary testing scenarios for identity, authorization, input validation, and web security controls.

  4. 04
    OWASP Top 10

    OWASP Foundation

    Current high-level web application security risk taxonomy.

FAQ / QUICK ANSWERS

Questions testers ask

What is storageState used for in Playwright authentication?

It serializes reusable browser authentication state such as cookies and supported origin storage so a new context can begin signed in. The file is sensitive and must be generated, protected, refreshed, and scoped deliberately.

Should every Playwright test sign in through the UI?

No. Keep focused login tests for the UI contract and reuse trusted authenticated state for scenarios whose purpose begins after login. This reduces repeated setup while preserving dedicated authentication coverage.

Can one storageState file serve every user role?

It should not. Each role needs its own state and account identity so permission boundaries remain explicit. Tests requiring two roles should create separate contexts from the corresponding files.

Why can a shared authenticated account cause flaky tests?

Parallel tests may mutate the same profile, permissions, cart, notifications, or session. One test can invalidate assumptions held by another. Use read-only sharing or allocate isolated accounts by test or worker.

How should authentication artifacts be secured in CI?

Keep credentials in the CI secret store, write state only to ignored protected paths, limit artifact upload, redact logs, and delete temporary files. Treat a state file as capable of impersonating its user.