</>

Technology

Playwright

Difficulty

Intermediate

Interview Question

How do you manage cookies in Playwright?

Answer

Cookie Management in Playwright

Cookies in Playwright are managed at the BrowserContext level, not at the page level.

Read Cookies

TypeScript
// Get all cookies for the current context
const cookies = await context.cookies();
console.log(cookies);
// [{ name: 'session', value: 'abc123', domain: 'myapp.com', ... }]

// Get cookies for a specific URL
const cookies = await context.cookies(['https://myapp.com']);

// Find a specific cookie
const sessionCookie = cookies.find(c => c.name === 'session_id');
console.log(sessionCookie?.value);

Set Cookies

TypeScript
await context.addCookies([
  {
    name: 'auth_token',
    value: 'test-jwt-token-123',
    domain: 'myapp.com',
    path: '/',
    httpOnly: true,
    secure: true,
    sameSite: 'Lax',
  },
  {
    name: 'user_preference',
    value: 'dark_mode',
    domain: 'myapp.com',
    path: '/',
  }
]);

Clear Cookies

TypeScript
// Clear all cookies
await context.clearCookies();

// Clear cookies for a specific domain (Playwright v1.43+)
await context.clearCookies({ domain: 'ads.example.com' });

In Test Fixtures

TypeScript
import { test, expect } from '@playwright/test';

test('set auth cookie before test', async ({ page, context }) => {
  // Set auth cookie before navigating (bypasses login UI)
  await context.addCookies([{
    name: 'session_id',
    value: 'valid-session-token',
    domain: 'localhost',
    path: '/',
  }]);

  // Navigate directly to authenticated page
  await page.goto('/dashboard');
  await expect(page.getByRole('heading')).toHaveText('Dashboard');
});

Cookie-based Authentication Test

TypeScript
test('authenticated via cookie', async ({ context, page }) => {
  // Set the session cookie
  await context.addCookies([{
    name: 'connect.sid',
    value: 'valid_session_value',
    domain: 'localhost',
    path: '/',
    httpOnly: true,
  }]);

  await page.goto('/protected-page');
  // Should access the page without being redirected to login
  await expect(page).not.toHaveURL('/login');
  await expect(page.locator('.user-profile')).toBeVisible();
});

Verify Cookie is Set After Action

TypeScript
test('login sets session cookie', async ({ page, context }) => {
  await page.goto('/login');
  await page.getByLabel('Email').fill('user@test.com');
  await page.getByLabel('Password').fill('password');
  await page.getByRole('button', { name: 'Sign in' }).click();
  await expect(page).toHaveURL('/dashboard');

  // Verify the session cookie was set
  const cookies = await context.cookies();
  const sessionCookie = cookies.find(c => c.name === 'session_id');
  expect(sessionCookie).toBeTruthy();
  expect(sessionCookie!.httpOnly).toBe(true);
});

Follow AutomateQA

Related Topics