Authentication, Network and APIs in Playwright

Authentication, Network and APIs is the fifth chapter of the free Playwright tutorial. It covers what happens behind the page: logins, network calls and the API itself.

What each lesson covers:

  • Authentication and Storage State: Log in once and reuse the session. Storage state files, the setup project pattern, API logins, several user roles, logged-out tests and keeping session files safe.
  • Network Interception and Mocking: Watch and wait for network calls, then take control with page.route(). Mock answers, block trackers, change requests, edit real data, and test error, empty, slow and offline states.
  • API Testing: Test the server directly with the request fixture. Status codes, JSON checks, tokens and cookies, a full create, read, update and delete flow, error cases, and API setup for UI tests.

Every test box runs in the Playwright lab in your browser, in TypeScript or JavaScript. The lab includes a small practice API, so nothing touches a real server.

Lessons in this section

  1. Authentication and Storage State

    Why logging in before every test is slow, what storage state holds (cookies and local storage), saving and reusing a login with storageState, the setup project pattern, logging in through the API, several user roles, logged-out tests, and keeping test accounts and session files safe.

    • Explain why tests should not log in through the form every time
    • Save and reuse a login with storageState
    • Log in once with a setup project and project dependencies
    • Use different roles in different tests, or in one test
  2. Network Interception and Mocking

    Watching requests and responses, waiting for a call with waitForRequest and waitForResponse, intercepting calls with page.route, URL patterns, mocking with route.fulfill, blocking with route.abort, changing requests with route.continue, chaining with route.fallback, editing real responses with route.fetch, error, empty, slow and offline states, context-wide routes, and HAR files.

    • Watch and wait for the network calls a page makes
    • Replace an API answer with test data using route.fulfill
    • Block, change and chain requests with abort, continue and fallback
    • Test error, empty, slow and offline states that are hard to make for real
  3. API Testing

    Why test APIs directly, the request fixture, sending GET, POST, PUT, PATCH and DELETE requests with JSON, form data, query params and headers, checking status, headers and JSON with toBeOK and toMatchObject, API authentication with tokens and cookies, a full create-read-update-delete flow, error cases, separate request contexts, and mixing API and UI steps in one test.

    • Send API requests with the request fixture
    • Check status codes, headers and JSON bodies
    • Authenticate API calls with a token or a login cookie
    • Test a full create, read, update and delete flow and its error cases