How can I share or isolate cookie storage in Playwright?


Sure, you can safely pass the user's session cookie to the context in Playwright. It's a great way to reuse authenticated state, including cookies and local storage based authentication.

Here's a quick example of how you can save and load session storage:

// Save session storage
const sessionStorage = await context.evaluate(() => JSON.stringify(sessionStorage));
// Load session storage
await context.evaluate((value) => sessionStorage = JSON.parse(value), sessionStorage);

Remember, session storage is domain-specific and doesn't persist across page loads. It's handy for storing info related to the signed-in state.

When you pass the user's session cookie to the context, it allows the new context or APIRequestContext to share cookie storage with the browser context.

For instance, you might send an API request that shares cookie storage with the browser context. The response will have a 'Set-Cookie' header with cookies. You can access these cookies and compare them with cookies stored in context.cookies() using context.request.fetch().

// Create a new instance of APIRequestContext with isolated cookie storage
const newContext = await playwright.request.newContext();

This new instance will have its own isolated cookies, separate from those in the browser context.

So, passing the user's session cookie to the context in Playwright is safe and allows for sharing or isolating cookie storage, depending on your needs.

Remember, this is based on the given context. If you have specific use cases or additional considerations, you might need to do a bit more research.


Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

Related Discord Threads

Related Questions

AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.