Saturday, November 28, 2026

Working with Cookies in Playwright using JavaScript

Working with Cookies in Playwright using JavaScript

Cookies are small pieces of data stored by a web browser. They help websites maintain user sessions, remember login information, store user preferences, and manage authentication.

Playwright provides built-in methods to create, read, update, delete, and manage browser cookies. In Playwright, cookies are managed through the BrowserContext object.

Working with Cookies in Playwright using JavaScript



1. Common Playwright Cookie Methods

Method Description
context.addCookies() Add cookies to the browser context.
context.cookies() Retrieve cookies.
context.clearCookies() Delete all cookies or matching cookies.
context.storageState() Capture cookies and local storage.
browserContext.newPage() Create a new page in the context.

2. Add Cookies in Playwright

Use context.addCookies() to add cookies before navigating to a website.

Example

const { chromium } = require('playwright');

(async () => {
    const browser = await chromium.launch({
        headless: false
    });

    const context = await browser.newContext();

    // Add cookies
    await context.addCookies([
        {
            name: 'username',
            value: 'sumit',
            domain: 'example.com',
            path: '/',
            expires: -1,
            httpOnly: false,
            secure: false,
            sameSite: 'Lax'
        }
    ]);

    const page = await context.newPage();

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

    console.log('Cookie added successfully');

    await browser.close();
})();

Output

Cookie added successfully

Explanation

  • name: Cookie name.
  • value: Cookie value.
  • domain: Website domain associated with the cookie.
  • path: Cookie path.
  • expires: Expiration timestamp in Unix seconds. -1 means a session cookie.
  • httpOnly: Prevents JavaScript from accessing the cookie.
  • secure: Sends the cookie only over secure HTTPS connections.
  • sameSite: Controls cross-site cookie behavior.

Note: Use the correct domain when adding cookies. The cookie must match the website you intend to access.


3. Get All Cookies in Playwright

Use context.cookies() to retrieve cookies stored in the browser context.

Example

const { chromium } = require('playwright');

(async () => {
    const browser = await chromium.launch({
        headless: false
    });

    const context = await browser.newContext();

    await context.addCookies([
        {
            name: 'username',
            value: 'sumit',
            domain: 'example.com',
            path: '/'
        }
    ]);

    const page = await context.newPage();

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

    // Get all cookies
    const cookies = await context.cookies();

    console.log(cookies);

    await browser.close();
})();

Output

[
  {
    name: 'username',
    value: 'sumit',
    domain: 'example.com',
    path: '/',
    expires: -1,
    httpOnly: false,
    secure: false,
    sameSite: 'Lax'
  }
]

4. Get a Specific Cookie

You can retrieve cookies and filter them based on their name.

Example

const cookies = await context.cookies();

const usernameCookie = cookies.find(
    cookie => cookie.name === 'username'
);

console.log('Username:', usernameCookie?.value);

Output

Username: sumit

5. Update an Existing Cookie

To update a cookie, use context.addCookies() again with the same cookie name, domain, and path but a different value.

Example

const { chromium } = require('playwright');

(async () => {
    const browser = await chromium.launch({
        headless: false
    });

    const context = await browser.newContext();

    await context.addCookies([
        {
            name: 'username',
            value: 'sumit',
            domain: 'example.com',
            path: '/'
        }
    ]);

    // Update existing cookie
    await context.addCookies([
        {
            name: 'username',
            value: 'john',
            domain: 'example.com',
            path: '/'
        }
    ]);

    const cookies = await context.cookies();

    console.log(cookies);

    await browser.close();
})();

Output

[
  {
    name: 'username',
    value: 'john',
    domain: 'example.com',
    path: '/'
  }
]

Explanation: When a cookie with the same name, domain, and path is added again, its value is updated.

6. Delete Cookies in Playwright

Playwright provides context.clearCookies() to remove cookies from the browser context.

Example: Delete All Cookies

const { chromium } = require('playwright');

(async () => {
    const browser = await chromium.launch();

    const context = await browser.newContext();

    await context.addCookies([
        {
            name: 'username',
            value: 'sumit',
            domain: 'example.com',
            path: '/'
        }
    ]);

    console.log('Before deletion:', await context.cookies());

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

    console.log('After deletion:', await context.cookies());

    await browser.close();
})();

Output

Before deletion: [
  {
    name: 'username',
    value: 'sumit',
    domain: 'example.com',
    path: '/'
  }
]

After deletion: []

Delete Cookies by Name

await context.clearCookies({
    name: 'username'
});

Delete Cookies by Domain

await context.clearCookies({
    domain: 'example.com'
});

Delete Cookies Using Multiple Filters

await context.clearCookies({
    name: 'username',
    domain: 'example.com',
    path: '/'
});

7. Get Cookies for a Specific URL

You can retrieve cookies associated with a particular URL by passing the URL to context.cookies().

Example

const { chromium } = require('playwright');

(async () => {
    const browser = await chromium.launch();

    const context = await browser.newContext();

    await context.addCookies([
        {
            name: 'username',
            value: 'sumit',
            url: 'https://example.com'
        },
        {
            name: 'token',
            value: 'abc123',
            url: 'https://example.com'
        }
    ]);

    const cookies = await context.cookies(
        'https://example.com'
    );

    console.log(cookies);

    await browser.close();
})();

Output

[
  {
    name: 'username',
    value: 'sumit',
    domain: 'example.com',
    path: '/',
    ...
  },
  {
    name: 'token',
    value: 'abc123',
    domain: 'example.com',
    path: '/',
    ...
  }
]

8. Access Cookies Using document.cookie

You can also access cookies through JavaScript using document.cookie. However, JavaScript cannot access cookies marked as HttpOnly.

Example

const { chromium } = require('playwright');

(async () => {
    const browser = await chromium.launch();

    const page = await browser.newPage();

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

    // Create a cookie using JavaScript
    await page.evaluate(() => {
        document.cookie = 'username=sumit; path=/';
    });

    // Read cookies using JavaScript
    const cookies = await page.evaluate(() => {
        return document.cookie;
    });

    console.log(cookies);

    await browser.close();
})();

Output

username=sumit

Important: document.cookie cannot read HttpOnly cookies. Use Playwright's context.cookies() to inspect those cookies.

9. Save Cookies Using storageState()

Playwright allows you to save cookies and local storage information using context.storageState().

This is useful when you want to reuse an authenticated browser session without logging in repeatedly.

Example: Save Authentication State

const { chromium } = require('playwright');

(async () => {
    const browser = await chromium.launch({
        headless: false
    });

    const context = await browser.newContext();

    await context.addCookies([
        {
            name: 'auth_token',
            value: 'test_token_123',
            url: 'https://example.com'
        }
    ]);

    // Save authentication state
    await context.storageState({
        path: 'auth.json'
    });

    console.log('Authentication state saved');

    await browser.close();
})();

Output

Authentication state saved

The generated auth.json file contains the browser storage state.

Example auth.json

{
  "cookies": [
    {
      "name": "auth_token",
      "value": "test_token_123",
      "domain": "example.com",
      "path": "/",
      "expires": -1,
      "httpOnly": false,
      "secure": false,
      "sameSite": "Lax"
    }
  ],
  "origins": []
}

10. Reuse Cookies Using storageState()

You can reuse previously saved cookies by providing the storageState file while creating a new browser context.

Example

const { chromium } = require('playwright');

(async () => {
    const browser = await chromium.launch({
        headless: false
    });

    // Load previously saved authentication state
    const context = await browser.newContext({
        storageState: 'auth.json'
    });

    const page = await context.newPage();

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

    console.log('Cookies loaded successfully');

    console.log(await context.cookies());

    await browser.close();
})();

Output

Cookies loaded successfully

[
  {
    name: 'auth_token',
    value: 'test_token_123',
    domain: 'example.com',
    path: '/',
    ...
  }
]

11. Working with Cookies in Playwright Test

You can also manage cookies inside Playwright Test using the built-in browser, context, and page fixtures.

Example: cookie.spec.js

const { test, expect } = require('@playwright/test');

test('Verify browser cookies', async ({ browser }) => {

    const context = await browser.newContext();

    await context.addCookies([
        {
            name: 'username',
            value: 'sumit',
            url: 'https://example.com'
        }
    ]);

    const page = await context.newPage();

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

    // Get cookies
    const cookies = await context.cookies();

    // Verify cookie exists
    const username = cookies.find(
        cookie => cookie.name === 'username'
    );

    expect(username).toBeDefined();
    expect(username.value).toBe('sumit');

    console.log('Cookie validation successful');

    await context.close();
});

Run the Test

npx playwright test cookie.spec.js

Output

Running 1 test using 1 worker

✓ cookie.spec.js
  ✓ Verify browser cookies

1 passed (3.2s)

12. Real-Time Example: Login Using Cookies

In automation testing, cookies are frequently used to bypass the login UI when a valid authentication session is already available.

For example, you can add an authentication cookie and directly open a protected application page.

Example

const { chromium } = require('playwright');

(async () => {
    const browser = await chromium.launch({
        headless: false
    });

    const context = await browser.newContext();

    // Add authentication cookie
    await context.addCookies([
        {
            name: 'auth_token',
            value: 'valid_test_token',
            url: 'https://example.com'
        }
    ]);

    const page = await context.newPage();

    // Open dashboard directly
    await page.goto('https://example.com/dashboard');

    console.log('Current URL:', page.url());

    await browser.close();
})();

Expected Output

Current URL: https://example.com/dashboard

Note: This example assumes the application recognizes the supplied test token. Adding a cookie alone does not authenticate a user. The cookie must be valid and accepted by the server.

13. Cookie Properties in Playwright

The following are commonly used cookie properties:

Property Description
name Cookie name.
value Cookie value.
domain Cookie domain.
url URL associated with the cookie.
path Cookie path.
expires Expiration timestamp.
httpOnly Restricts JavaScript access.
secure Restricts transmission to secure connections.
sameSite Controls cross-site cookie behavior.
partitionKey Cookie partition key, when applicable.

14. Best Practices for Cookie Testing

  1. Use context.addCookies() to create cookies before opening the application.
  2. Use context.cookies() to validate cookie values.
  3. Use context.clearCookies() to clean up browser state.
  4. Use storageState() to reuse authenticated sessions.
  5. Test both session cookies and persistent cookies.
  6. Validate HttpOnly, Secure, and SameSite attributes.
  7. Avoid hardcoding production authentication tokens.
  8. Store authentication state files securely and do not commit them to Git.
  9. Create a separate browser context for isolated test execution.
  10. Verify that expired or invalid authentication cookies are handled correctly.

15. Frequently Asked Questions

1. How do I get cookies in Playwright?

const cookies = await context.cookies();
console.log(cookies);

2. How do I add cookies in Playwright?

await context.addCookies([
    {
        name: 'username',
        value: 'sumit',
        url: 'https://example.com'
    }
]);

3. How do I delete all cookies in Playwright?

await context.clearCookies();

4. How do I delete a specific cookie?

await context.clearCookies({
    name: 'username'
});

5. How do I save cookies in Playwright?

await context.storageState({
    path: 'auth.json'
});

6. How do I reuse cookies in another test?

const context = await browser.newContext({
    storageState: 'auth.json'
});

7. Can Playwright access HttpOnly cookies?

Yes. Playwright can access HttpOnly cookies through context.cookies(), but browser-side JavaScript using document.cookie cannot access them.

Conclusion

Playwright provides powerful cookie management functionality through the BrowserContext API. You can add, retrieve, update, delete, and reuse cookies to automate authentication workflows and test browser session management.

No comments:

Post a Comment