Preserve Authentication state in Playwright

Pranesh
2 min readSep 15, 2022

--

As playwright opens browser in incognito mode always and you will get new session every time you execute test case, theres a way by which you can reuse the previous authentication state of your application and continue test execution from there. As provided in Playwright documentation storageState() is the method which can provide us the authentication state saved in cookies and local storage context. Let’s see how we can use authentication state and skip login for sub sequent test cases.

I am taking example of OrangeHRM web site for this use case.

Step 1:

I will first write steps to login into application using provided user id and password. (Username : Admin and Password : admin123)

Playwright playwright = Playwright.create();
BrowserType browserType = playwright.chromium();
Browser browser = browserType.launch(new BrowserType.LaunchOptions().setHeadless(false));
BrowserContext browserContext = browser.newContext();
Page page = browserContext.newPage();
page.navigate("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login");

page.locator("[name='username']").fill("Admin");
page.locator("[name='password']").fill("admin123");
page.locator("button[type='submit']").click();

Above code snippet will launch Chromium browser and login to the application. Once logged in i can fetch the authentication state using storageState() method as below:

browserContext.storageState(new BrowserContext.StorageStateOptions().setPath(Paths.get("state.json")));

Step 2:

Once i retrieve the authentication state, i can create new browser context (which will launch new browser) with pre-populated authentication state.

BrowserContext browserContext1 = browser.newContext(new Browser.NewContextOptions().setStorageStatePath(Paths.get("state.json")));
Page page1 = browserContext1.newPage();
page1.navigate("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login");

If i run above code snippet, i will be redirected to home page skipping login page, since we provided the authentication state while creating browser context.

Step 3:

If i create a new browser context without any authentication state, it will navigate you to Login page.

BrowserContext browserContext2 = browser.newContext();
Page page2 = browserContext2.newPage();
page2.navigate("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login");

--

--