Use the standard Playwright context.addCookies() method to add one or more cookies:
// Add cookies to the context
await context.addCookies([
  {
    name: 'sessionId',
    value: 'abc123',
    domain: 'example.com',
    path: '/'
  },
  {
    name: 'theme',
    value: 'dark',
    domain: 'example.com',
    path: '/',
    expires: Math.floor(Date.now() / 1000) + 86400 // expires in 1 day
  }
]);
When adding cookies, you can specify the following properties:
PropertyTypeRequiredDescription
namestringThe name of the cookie
valuestringThe value of the cookie
domainstringThe domain for which the cookie is valid
pathstringThe path for which the cookie is valid (defaults to ’/‘)
expiresnumberExpiration time as Unix timestamp in seconds
httpOnlybooleanWhether the cookie is HTTP-only
securebooleanWhether the cookie requires HTTPS
sameSitestringSameSite attribute (‘Strict’, ‘Lax’, or ‘None’)

Best Practices

  • Add cookies before navigation: Set cookies before navigating to pages that depend on them
  • Match the domain: Ensure the cookie domain matches the domain you’re testing
  • Use console.log(): Debug cookie issues using console logging and the VM’s browser console
  • Set appropriate expiration: Use reasonable expiration times for test cookies