How Session Storage Work in Playwright

In Automation Testing logging into an application repeatedly for every test case can be time-consuming and inefficient as well. To rescue with this problem Session Storage state comes to picture with narrative of “Modern Day Problems Require Modern Day Solution

By saving the authenticated state once and reusing it across multiple tests, automation engineer can skip redundant login steps and focus on only business flows.

In this post we will dive deep what is session storage, how it helpful in automation framework, how, where and when you implement session storage, troubleshooting problem and their solution, best practice to secure session storage, pros and cons of it, and real-world test automation code to store session

Below are the points which we are cover in this post

  • What is session storage?
  • Why reuse session in automation framework?
  • How session usability work in Playwright?
  • Internal flow behind the scenes
  • When should you use when not?
  • Troubleshooting common issues
  • Best practices
  • Pros and Cons
  • Setting up global setup for session storage in playwright

What is Session Storage?

  • When you log in to any website, your login details (like token, session IDs and Cookies) are temporarily stored in the browser, which is called session storage.
  • It helps the browser remember that you are already logged in, so you don’t have to re-enter your credentials (username/email and password) again and again while dealing with multiple test case scenario.
  • But here is a catch, once you close the browser this session data is gone

Why Reuse Session in Automation Framework?

  • In Automation testing, every test case starts in incognito mode, which open the fresh browser every time, you’ll end up logging in again and again every single time which is not efficient and profitable too to do the same things again and again
  • To overcome with above issue session re-usability comes into the picture which helps us to login once and test everything

How Session Usability Works in Playwright?

  • Playwright stores all cookies, localStorage, and sessionStorage data from your logged-in browser context into a file (like storageState.json)
  • During test execution, Playwright reads that file and restores the browser state exactly as it was after login.
  • This means the app is recognizes the user as already logged in, no login state and delay user direct navigate to the home/dashboard page bypassing login state
  • Think of it like taking snapshot of your logged-in browser and reusing the snapshot every time your test run
    storageState

    sample session storage state template

     

Internal Flow Behind The Scenes

  • Global Setup Phase (before test run)
    1. Browser launches
    2. Login happens once
    3. Session Saved
    4. Browser Closed
  • Test Execution Phase
    • Each test picks up the saved session file (storageState.json) and starts from logged in state by passing login state
  • Result
    • Test directly land on the protected route (like /dashboard, home/, /profile and etc.) without re-login
  • Flow Diagram
StorageFlow

Sesson Storage Flow

When Should You Use When Not?

  • Do When
    • You have stable login flow that doesn’t change frequently
    • Your webapp uses session or token-based authentication (like JWT)
    • You want to save execution time and skip repetitive login steps
    • You are working with large test suit (8+ spec file)
  • Don’t When
    • You are testing login functionality itself (you need a fresh session)
    • The session expires very quickly (every 2-3 minutes)

Troubleshooting Common Issues

Here are a few things Automation Engineer usually face while implementing session reusability

  1. “Session not valid” or “User not logged in”

    • The store session may have expired
    • Solution: Re-run your global-setup file to generate a fresh storageState.json file
  2. “Cannot read storageState.json”

    • Path mismatch or wrong directory structure.
    • Solution: Use path.resolve(__dirname, ‘storageState.json’) for absolute path handling
  3. “Login Failed in CI/CD pipelines”

    • .env credentials not loaded properly in your pipeline
    • Solution: Make sure to set environment variables in your CI setting (like GitHub, Gitlab, and etc.).

Best Practices

  • Keep login logic separate (as you have done in your Login.ts page object, which keeps your setup maintainable
  • Use .env file for sensitive credentials — never hard code sensitive data
  • Ignore storage files in Git
  • Ignore .env files in Git

Pro And Cons

  • Pro

    • Faster test execution
    • More stable tests
    • Less maintenance
    • Better parallel execution
    • Easier test writing
  • Cons

    • Session expiry
    • Login flow tested only once
    • Extra Setup to manage session file

Setting up Global Setup for Session Storage In Playwright

  • To implement session reusability in Playwright, we first need to create a global-setup file. In this file, we perform the login action once, fetch the authenticated session storage state, and then store it in a file for example sessionStorage.json (you can name it as per your preference)
  • Next, we configure this global setup file inside the Playwright config so that it runs before all tests. This ensures the login session is created only once.
  • Then, under the use block (or within the specific project configuration), we reference the same sessionStorage.json file so that all subsequent tests can reuse the saved session state without logging in again

Code

Global Setup File Structure

import {chromium, FullConfig} from "@playwright/test";
import path from 'path';
import { config as dotenv } from 'dotenv';
import { LOGIN } from './tests/Pages/Login';


dotenv(); // Load environment variables

async function globalSetup(config: FullConfig) {
// Launch browser
const browser = await chromium.launch({ headless: true });
const page = await browser.newPage();
const loginPage = new LOGIN(page);

// Get base URL from playwright config
const baseURL = config.projects[0].use?.baseURL as string;

// Fetch credentials from .env file
const email = process.env.ADMIN_EMAIL;
const password = process.env.ADMIN_PASS;

// Navigate to login page
await page.goto(`${baseURL}/admin/users/login/`);

// Perform login
await loginPage.performLoginWithValidCred(email, password)

// Wait until login completes (adjust URL as needed)
await page.waitForURL(`${baseURL}/admin/dashboard`);

// Save session state in a single file
const storageFile = path.resolve(__dirname, 'sessionStorage.json');
await page.context().storageState({ path: storageFile });
console.log(`Session saved to: ${storageFile}`);
 await browser.close();
}
export default globalSetup;

Config File Structure

import { defineConfig, devices } from '@playwright/test';
import { config as dotenv } from 'dotenv';

dotenv();
export default defineConfig({
    testDir: './tests',
    fullyParallel: false,
    forbidOnly: !!process.env.CI,
    retries: process.env.CI ? 2 : 0,
    workers: process.env.CI ? 1 : undefined,
    reporter: 'html',
    timeout: 90000,

    // Run global setup once before all tests
    globalSetup: './global-setup.ts',
// Global use block with session storage
use: {
   baseURL: 'https://dev.example.com', // your base URL
   storageState: './sessionStorage.json', // single session file
   trace: 'on-first-retry',
   screenshot: 'only-on-failure',
},

 projects: [
{
  name: 'chromium',
  ...devices['Desktop Chrome']
   }],
});

Wrapping It Up

Session reusability in Playwright is a game-changer for modern test automation.
By Saving and reusing the login state we:

  • Cut down repetitive steps
  • Speed up execution
  • Maintain cleaner code

Whether you’re running locally or in CI/CD pipeline, this approach ensures “Login once, test everything”

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *