Working with Cookies and Local Storage in Playwright

Working with Cookies and Local Storage in Playwright

Introduction

When automating web applications, dealing with cookies and local storage becomes crucial—especially for tasks like session management, login persistence, and simulating user states. Playwright, a powerful end-to-end testing framework, provides built-in APIs to easily manage browser storage, including cookies, localStorage, and sessionStorage.


This guide will walk you through how to read, set, and clear cookies and local storage using Playwright.


Understanding the Basics

🔹 What are Cookies?

Small pieces of data stored by the browser to remember information (e.g., session ID, authentication).


Can be used to maintain a logged-in state or track user preferences.


🔹 What is Local Storage?

A key-value storage system in the browser.


Data stored persists even after the browser is closed.


Limited to the origin (domain).


1. Handling Cookies in Playwright

✅ Get Cookies

javascript

Copy

Edit

const cookies = await context.cookies();

console.log(cookies);

You can also get cookies for a specific URL:


javascript

Copy

Edit

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

✅ Set Cookies

javascript

Copy

Edit

await context.addCookies([

  {

    name: 'session_id',

    value: 'abc123',

    domain: 'example.com',

    path: '/',

    httpOnly: true,

    secure: true,

    sameSite: 'Lax'

  }

]);

✅ Clear Cookies

javascript

Copy

Edit

await context.clearCookies();

2. Handling Local Storage in Playwright

✅ Read Local Storage

You must evaluate it within the browser context using page.evaluate():


javascript

Copy

Edit

const token = await page.evaluate(() => {

  return localStorage.getItem('auth_token');

});

console.log('Token:', token);

✅ Set Local Storage

You can manually set a value in local storage:


javascript

Copy

Edit

await page.evaluate(() => {

  localStorage.setItem('auth_token', 'abc123');

});

✅ Clear Local Storage

javascript

Copy

Edit

await page.evaluate(() => {

  localStorage.clear();

});

3. Example: Reusing Session with Cookies or Local Storage

Saving Cookies After Login

javascript

Copy

Edit

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

// perform login steps

const cookies = await context.cookies();

fs.writeFileSync('cookies.json', JSON.stringify(cookies));

Loading Cookies Before Test

javascript

Copy

Edit

const cookies = JSON.parse(fs.readFileSync('cookies.json', 'utf8'));

await context.addCookies(cookies);

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

4. Storing Session State with storageState

Playwright provides a handy way to store both cookies and local storage together.


✅ Save Storage State

javascript

Copy

Edit

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

✅ Use Storage State in New Context

javascript

Copy

Edit

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

const page = await context.newPage();

This is useful for skipping repetitive logins in multiple tests.


Best Practices

Use storageState for login persistence across test suites.


Clear cookies and local storage between tests to avoid test pollution.


Use environment-specific data while setting cookies to avoid cross-domain issues.


Always test storage behaviors in both headless and headed modes.


Conclusion

Working with cookies and local storage in Playwright is simple and flexible. Whether you’re testing login flows, session persistence, or local data management, Playwright provides robust APIs to help you control browser storage.

Understanding these tools will help you write faster, more reliable, and maintainable automation scripts.

Learn Playwright Training Course in Hyderabad

Read More

Capturing Screenshots and Videos with Playwright

Working with Alerts and Pop-ups in Playwright

Visit Our IHUB Talent Training Institute in Hyderabad

Get Directions

Comments

Popular posts from this blog

How to Install and Set Up Selenium in Python (Step-by-Step)

Tosca for API Testing: A Step-by-Step Tutorial

Waits in Playwright: Explicit, Implicit, and Auto