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();
});
APIRequestContext can keep tests faster and more focused when you only need to exercise backend logic.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.