Fixing Playwright 401 Errors on Protected Routes with storageState

A developer found that Playwright E2E tests accessing protected pages returned 401 Unauthorized errors even though the same flow worked in a regular browser. The cause is that Playwright runs each test in a fresh browser context, so cookies, localStorage, and tokens from a login test are not carried over to later tests. The suggested fix is to save the authenticated session after login using page.context().storageState({ path: 'auth.json' }), which writes cookies and localStorage to a file. This saved state can then be reused so that tests on protected routes start already signed in. The article illustrates the approach with a sign-in test and an example of the resulting auth.json contents.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.


Discussion (0)
Log in to join the discussion and vote.
Log in