Playwright + Java · Lesson 30 of 38

0/38 done

Module 30: Authentication & Sessions

30. Global Authentication & Session Reuse with StorageState

18 minlesson

Your task

Implement createAuthenticatedContext:

  1. Accept Browser browser and String statePath.
  2. Return browser.newContext(new Browser.NewContextOptions().setStorageStatePath(Paths.get(statePath))).

Write it in the editor, then press Check answer (Ctrl + Enter).

Global Authentication Pattern

java
import java.nio.file.Paths;

// Step 1: Perform login once and save session state
Page loginPage = browser.newPage();
loginPage.navigate("https://targetqa.com/login");
loginPage.getByLabel("Email").fill("admin@targetqa.com");
loginPage.getByLabel("Password").fill("Secret123!");
loginPage.getByRole(AriaRole.BUTTON).click();

// Save cookies and localStorage to auth.json:
loginPage.context().storageState(new BrowserContext.StorageStateOptions()
    .setPath(Paths.get("state/adminAuth.json")));

// Step 2: Instantly spawn pre-authenticated contexts:
BrowserContext authenticatedContext = browser.newContext(
    new Browser.NewContextOptions().setStorageStatePath(Paths.get("state/adminAuth.json"))
);
Page authPage = authenticatedContext.newPage();
authPage.navigate("https://targetqa.com/dashboard"); // Already logged in!

Key Takeaways & Walkthrough Summary

Logging in via the UI before every single test wastes tremendous amounts of time. In Playwright, you log in once, save the browser's storage state to a JSON file, and reload it directly in new contexts. Let's master session reuse with storageState!

Part of the Playwright + Java course (Playwright with Java). Practice this concept live in the Playwright Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

What is stored in storageState JSON?

Playwright captures all cookies, JWT tokens, and localStorage items associated with the session, allowing instant authentication bypass.

Ready? Solve the task in the editor

Use Check answer to mark it complete. Hints are there if you need them.

Java
Skip