Monday, May 19, 2025

How to Get and Use Cookies in Playwright: A Step-by-Step Guide for Beginners

In this example we will explore how to work with cookies in playwright with simple examples. Cookies are essential for maintaining state and storing small amounts of data on the client-side.


What Are Cookies?

Cookies are small text files stored on the client's browser by a website. They are used to remember information between HTTP requests (because HTTP is stateless).


Basic Cookie Lifecycle

  1. Server sets a cookie via HTTP response headers.
  2. Browser stores the cookie and sends it back with subsequent requests to the same server.
  3. Server reads the cookie and uses the data (like session info).
  4. Cookies can also be set/modified using JavaScript.

How to Get and Use Cookies in Playwright: A Step-by-Step Guide for Beginners

In this example we will explore how to work with cookies in Playwright using JavaScript, with a detailed explanation and code examples. Playwright is a powerful end-to-end testing framework, and managing cookies is essential when you're simulating login states, persisting sessions, or testing user flows.


What Are Cookies in Playwright Context?

In Playwright, cookies help you:

  1. Simulate authenticated sessions (e.g., avoid logging in every test).
  2. Test user-specific features.
  3. Persist state between tests or pages.
  4. Playwright allows you to read, add, delete, and manage cookies programmatically through its API.


✅ Reading cookies from a page

This example helps to read cookies from web page.
const cookies = await context.cookies();
console.log(cookies); // Array of cookie objects

✅ Setting Cookies in a page

You can set cookies before navigating to a page.

await context.addCookies([{
  name: 'sessionId',
  value: 'abc123',
  domain: 'example.com',
  path: '/',
  httpOnly: true,
  secure: true,
  sameSite: 'Lax'
}]);


✅  Deleting Cookies from a page

Clear all cookies.

await context.clearCookies();

✅  Saving and Restoring Cookies (Session Persistence)

This is useful for avoiding repeated login in multiple tests.

Saving cookies to a file:

const fs = require('fs');

const cookies = await context.cookies();
fs.writeFileSync('cookies.json', JSON.stringify(cookies));

Loading cookies from a file:

const cookies = JSON.parse(fs.readFileSync('cookies.json'));
await context.addCookies(cookies);

Simulate example to get all cookies.

In this example we will get all cookies from a web page and print in console.

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

(async () => {
  const browser = await chromium.launch();
  const context = await browser.newContext();
  const page = await context.newPage();
  await page.goto('https://example.com/dashboard');

  // get all cookies
  const cookies = await context.cookies();
  console.log(cookies); // Array of cookie objects

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


Simulate Login by Setting Cookie

In this example we are setting up cookies before launching web page, so that use can login to page directly with help of cookies.

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

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

  await context.addCookies([{
    name: 'auth_token',
    value: 'securetoken123',
    domain: 'example.com',
    path: '/',
    httpOnly: true,
    secure: true
  }]);

  const page = await context.newPage();
  await page.goto('https://example.com/dashboard');

  // The user should now be "logged in" based on the auth_token cookie

  await page.screenshot({ path: 'dashboard.png' });

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

This is all about handling cookies in playwright with simple example.


No comments:

Post a Comment