How to Handle Authentication in Playwright Tests: Complete TypeScript Tutorial for Beginners

Introduction

Learning how to handle authentication in Playwright tests is an essential skill for QA Automation Engineers, SDETs, Selenium engineers transitioning to Playwright, software testing students, QA engineers, and developers. Most modern web applications require users to authenticate before accessing dashboards, reports, APIs, or administrative features. If authentication is not handled efficiently, automated test suites become slow, repetitive, and difficult to maintain.

Playwright provides several powerful authentication mechanisms, including login automation, reusable authentication state, HTTP Basic Authentication, API-based login, and session management. These capabilities help teams reduce test execution time while creating reliable and scalable automation frameworks.

In this how to handle authentication in Playwright tests tutorial, you’ll learn:


What Is Authentication in Playwright Tests?

Authentication is the process of verifying a user’s identity before granting access to an application.

Common authentication methods include:

  • Username and password login
  • Session cookies
  • JWT tokens
  • OAuth
  • Single Sign-On (SSO)
  • HTTP Basic Authentication
  • API token authentication

Instead of logging in before every test, Playwright allows you to save the authenticated session and reuse it across multiple test cases.


Benefits of Handling Authentication in Playwright Tests

Understanding how to handle authentication in Playwright tests provides several benefits:


Step-by-Step Tutorial: How to Handle Authentication in Playwright Tests

Step 1: Automate User Login

Create a basic login test.

import { test, expect } from ‘@playwright/test’;

test(‘Login’, async ({ page }) => {

  await page.goto(‘https://example.com/login’);

  await page.getByLabel(‘Username’).fill(‘admin’);

  await page.getByLabel(‘Password’).fill(‘admin123’);

  await page.getByRole(‘button’, {

    name: ‘Login’

  }).click();

  await expect(page).toHaveURL(/dashboard/);

});

Explanation

This script:

  • Opens the login page
  • Enters credentials
  • Clicks the Login button
  • Verifies successful login

Use case: Basic login automation.


Step 2: Save Authentication State

Instead of logging in for every test, save the authenticated session.

import { chromium } from ‘@playwright/test’;

async function globalSetup() {

  const browser = await chromium.launch();

  const page = await browser.newPage();

  await page.goto(‘https://example.com/login’);

  await page.fill(‘#username’, ‘admin’);

  await page.fill(‘#password’, ‘admin123’);

  await page.click(‘#login’);

  await page.context().storageState({

    path: ‘playwright/.auth/user.json’

  });

  await browser.close();

}

export default globalSetup;

Why Use storageState?

The authentication state includes cookies and local storage, allowing future tests to start in an authenticated state without logging in again.


Step 3: Reuse storageState

Update your Playwright configuration.

import { defineConfig } from ‘@playwright/test’;

export default defineConfig({

  use: {

    storageState: ‘playwright/.auth/user.json’

  }

});

Practical Use Case

Every test automatically starts with a logged-in session, significantly reducing execution time for large test suites.


Step 4: Handle HTTP Basic Authentication

Some applications use HTTP Basic Authentication.

import { test } from ‘@playwright/test’;

test(‘Basic Authentication’, async ({ browser }) => {

  const context = await browser.newContext({

    httpCredentials: {

      username: ‘admin’,

      password: ‘password’

    }

  });

  const page = await context.newPage();

  await page.goto(‘https://example.com’);

});

Explanation

Playwright sends the credentials automatically with each request to protected resources.


Step 5: API Authentication

Many applications expose login APIs that return authentication tokens.

import { request, test } from ‘@playwright/test’;

test(‘API Login’, async () => {

  const apiContext = await request.newContext();

  const response = await apiContext.post(‘https://example.com/api/login’, {

    data: {

      username: ‘admin’,

      password: ‘admin123’

    }

  });

  const body = await response.json();

  console.log(body.token);

});

Practical Use Case

Authenticate through the API instead of the UI to speed up test execution.


Step 6: Session Management

Validate that the authenticated user can access protected pages.

import { test, expect } from ‘@playwright/test’;

test(‘Dashboard Access’, async ({ page }) => {

  await page.goto(‘https://example.com/dashboard’);

  await expect(page).toHaveURL(/dashboard/);

});

If storageState is configured, no login step is required.


Real-World Authentication Examples

1. Single Sign-On (SSO)

Many enterprise applications use providers such as Azure Active Directory or Okta.

Typical flow:

  • User selects Sign in
  • Redirects to identity provider
  • Authenticates
  • Returns to the application

Recommendation: Save the authenticated storageState after the first successful login to avoid repeating the SSO flow in every test.


2. OAuth Login

Applications using Google, GitHub, or Microsoft authentication typically rely on OAuth.

Best practice: Authenticate once and reuse the saved session rather than automating external login pages repeatedly.


3. JWT Token Authentication

Applications that use JWTs store tokens in local storage or cookies.

Use API authentication to retrieve a token and inject it into the browser context before opening the application.


4. Multi-User Testing

Create separate authentication state files for different roles.

Example:

playwright/.auth/

admin.json

manager.json

user.json

Scenario: Validate different permissions for administrators, managers, and standard users.


5. Role-Based Access Testing

Verify that each role can access only authorized features.

Examples:

  • Admin dashboard
  • Manager reports
  • User profile
  • Read-only access

Playwright Authentication vs Selenium

FeaturePlaywrightSelenium
Save authentication state✅ Built-inManual implementation
storageState support✅ Yes❌ No
API authenticationNative supportExternal libraries
Auto waitingBuilt-inMostly manual
Multi-user session handlingEasyMore complex
Test execution speedFasterSlower due to repeated logins

Why Playwright Is Better

Playwright simplifies authentication by providing built-in session reuse and API capabilities, reducing repetitive login steps and improving test stability.


CI/CD Integration

Authentication handling is particularly valuable in CI/CD environments.

Typical workflow:

Developer Commit

        │

        ▼

Global Setup

        │

        ▼

Save Authentication State

        │

        ▼

Execute Playwright Tests

        │

        ▼

Generate HTML Report

        │

        ▼

Publish Results

Best practices for CI/CD:

  • Store credentials as encrypted pipeline secrets.
  • Never commit authentication state files containing production credentials.
  • Refresh expired sessions automatically during pipeline setup.
  • Use separate authentication states for different environments (QA, staging, production-like).

Best Practices for Authentication Testing in Playwright

Follow these recommendations:


Common Issues & Troubleshooting Tips

ProblemSolution
Authentication state not reusedVerify the storageState file path in the Playwright configuration.
Session expiresRegenerate the authentication state during global setup.
Login fails in CI/CDCheck environment variables and secret configuration.
Protected page redirects to loginEnsure cookies and local storage were saved correctly.
API login returns 401Validate credentials, request headers, and authentication endpoint.

Playwright Authentication Interview Questions with Answers

1. What is storageState in Playwright?

storageState stores cookies and local storage so authenticated sessions can be reused across multiple tests.


2. Why should you reuse authentication state?

It speeds up test execution, reduces duplicate login steps, and improves test stability.


3. How do you handle HTTP Basic Authentication?

Create a browser context with the httpCredentials option.


4. When should you use API authentication instead of UI login?

Use API authentication when login functionality itself is not being tested and you want faster, more reliable test execution.


5. How do you test multiple user roles?

Create separate authentication state files for each role and configure tests to load the appropriate storageState.


FAQs

What are the benefits of how to handle authentication in Playwright tests?

Benefits include faster execution, reusable authenticated sessions, improved stability, easier multi-user testing, and seamless CI/CD integration.


How do I get started with how to handle authentication in Playwright tests?

Install Playwright, automate the login process, save the authenticated session using storageState, configure your tests to reuse it, and secure credentials using environment variables.


Is how to handle authentication in Playwright tests suitable for beginners?

Yes. Playwright provides simple APIs for login automation, session reuse, and HTTP authentication, making it approachable for beginners while supporting enterprise-scale automation.

Leave a Comment

Your email address will not be published. Required fields are marked *