Working with Auth Tokens and Headers

๐Ÿ“‹ Table of Contents โ–พ
  1. Inspecting and Modifying Auth Headers
  2. Common Mistakes

Many secure flows depend on auth tokens, cookies and custom headers. Being able to inspect and manipulate these values in Playwright tests helps you model real security constraints and edge cases.

Inspecting and Modifying Auth Headers

You can use page.request, APIRequestContext or routing to work with headers and tokens. For browser flows, you often rely on cookies or local storage; for API-level calls, you can add headers directly.

// auth-tokens-headers.spec.ts
import { test, expect, request } from '@playwright/test';

-test('calls API with auth token', async ({ page }) => {
+test('calls API with auth token', async ({ page }) => {
  const apiContext = await request.newContext({
    baseURL: 'https://api.demo.myshop.com',
    extraHTTPHeaders: {
      Authorization: 'Bearer test-token-123',
    },
  });

  const response = await apiContext.get('/profile');
  expect(response.ok()).toBeTruthy();
});
Note: Separating browser-based tests from direct API calls with APIRequestContext can keep tests faster and more focused when you only need to exercise backend logic.
Tip: Store test tokens and secrets in CI secrets or environment variables, not hard-coded in the repo.
Warning: Never paste real production tokens or user data into test code or logs; use dedicated test accounts and keys.

For browser scenarios, you can also seed cookies or local storage before navigating, which simulates a user who is already authenticated.

Common Mistakes

Mistake 1 โ€” Hard-coding sensitive tokens in tests

This is a security risk.

โŒ Wrong: Committing real API keys to version control.

โœ… Correct: Use environment variables and dedicated test credentials.

Mistake 2 โ€” Ignoring auth behaviour in tests

This leaves gaps in coverage.

โŒ Wrong: Assuming auth will always work and only testing post-auth screens.

โœ… Correct: Include tests that verify login flows, token refresh and access control.

🧠 Test Yourself

How should you handle auth tokens in Playwright tests?