Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

If a Playwright screenshot shows your login page, an empty shell, or a missing private panel, the screenshot code is usually not the root problem. The browser context that captured the page did not have valid authentication at the moment of capture, or the test captured before authenticated data rendered. Save state only after login really completes, load that state into the context that takes the screenshot, restore sessionStorage when your app uses it, and wait for an application signal rather than a timer.

Start with the four checks that fix most cases

  1. Authenticate in the same state you will reuse. A login in one browser context does not log in a different context.
  2. Save state after a real post-login signal. Wait for the final application URL or for a protected element to be visible before calling storageState().
  3. Load the file when the screenshot context is created. Check the path, project dependency and context options.
  4. Wait for the protected content, not merely page load. A page can be loaded while an API request or lazy component is still unauthenticated or incomplete.

Playwright’s state snapshot includes cookies, local storage, IndexedDB and supported virtual WebAuthn credentials. It does not automatically include sessionStorage. That distinction explains many apparently valid but ineffective state files.

Save a known-good authenticated state

Use a setup project so login runs once before dependent browser tests. The following TypeScript pattern waits for both the final URL and an authenticated UI signal. Redirects can set cookies over several hops, so saving earlier can create a file that looks present but cannot authenticate the target page.

// tests/auth.setup.ts
import { test as setup, expect } from '@playwright/test';
import path from 'path';

const authFile = path.join(__dirname, '../playwright/.auth/user.json');

setup('authenticate', async ({ page }) => {
  await page.goto('/login');
  await page.getByLabel('Username').fill(process.env.E2E_USER!);
  await page.getByLabel('Password').fill(process.env.E2E_PASSWORD!);
  await page.getByRole('button', { name: 'Sign in' }).click();

  // Use the application's real completion signals.
  await page.waitForURL('**/dashboard');
  await expect(page.getByTestId('user-menu')).toBeVisible();

  await page.context().storageState({ path: authFile });
});

If your application does not navigate after login, replace waitForURL with a stable authenticated locator, such as a user menu, account heading or private API response. Do not save immediately after clicking the button: the click may only start redirects and token exchange.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
  • WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
  • A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents

Load that state in the project that captures the screenshot

// playwright.config.ts
import { defineConfig } from '@playwright/test';

export default defineConfig({
  projects: [
    { name: 'setup', testMatch: /.*\.setup\.ts/ },
    {
      name: 'chromium',
      use: {
        browserName: 'chromium',
        storageState: 'playwright/.auth/user.json',
      },
      dependencies: ['setup'],
    },
  ],
});

The dependent project runs only after the setup project succeeds. For one test or a temporary diagnosis, apply the state explicitly:

import { test } from '@playwright/test';

test.use({ storageState: 'playwright/.auth/user.json' });

test('captures the private account page', async ({ page }) => {
  await page.goto('/account');
  await page.screenshot({ path: 'account.png', fullPage: true });
});

When you create a context manually, pass storageState while constructing it (or use Playwright’s supported state-setting API). A fresh context otherwise starts unauthenticated even if another test has already logged in.

Verify the state file without leaking credentials

Inspect the JSON structure in a secure local environment, but never print cookie values, authorization headers or tokens. Confirm that expected cookie domains and origin entries exist. A common failure is a cookie scoped to auth.example.com while the screenshot visits app.example.com, or a path/secure setting that excludes the target URL.

  • Check the configured path is relative to the Playwright configuration location you actually run.
  • Check the test is assigned to the project that declares storageState.
  • Check setup is listed as a project dependency.
  • Check the saved domains, paths and origins match the final URL, not an intermediate identity-provider redirect.
  • Regenerate the file when cookies or tokens have expired.

Keep the authentication directory gitignored. A state file can impersonate the test account; use a dedicated account and do not attach the file or its values to logs or bug reports.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
  • SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors

Restore sessionStorage explicitly when the app needs it

Some single-page applications keep a bearer token, tenant selection or login marker in sessionStorage. Playwright’s built-in snapshot does not persist it. Serialize it after login, then install it before the first navigation in the new context.

// After successful login, in a protected artifact location
const session = await page.evaluate(() => JSON.stringify(sessionStorage));
// Save `session` securely alongside your test state.

// Before the first navigation in a new context
await context.addInitScript(storage => {
  if (window.location.hostname === 'app.example.com') {
    for (const [key, value] of Object.entries(storage)) {
      window.sessionStorage.setItem(key, value as string);
    }
  }
}, JSON.parse(session));

The hostname guard is important: sessionStorage is origin-specific. Restore only to the intended origin and treat the serialized values as credentials. If the app changes its storage key or refreshes the token during startup, capture a trace and update the setup flow rather than adding an arbitrary delay.

Use API login when a UI login is slow or fragile

An APIRequestContext can authenticate once, retain the cookies and local storage returned by the server, and export them for a browser context. This avoids repeating a login form while preserving the server-issued state the browser needs.

import { request, chromium, expect } from '@playwright/test';

const api = await request.newContext({ baseURL: 'https://app.example.com' });
await api.post('/api/login', {
  data: { username: process.env.E2E_USER, password: process.env.E2E_PASSWORD },
});
const state = await api.storageState();
await api.dispose();

const browser = await chromium.launch();
const context = await browser.newContext({ storageState: state });
const page = await context.newPage();
await page.goto('https://app.example.com/account');
await expect(page.getByTestId('private-panel')).toBeVisible();
await page.screenshot({ path: 'account.png', fullPage: true });
await browser.close();

The API endpoint must establish the same session mechanism your browser application consumes. If it returns a token that the front end stores only in sessionStorage, add the explicit restore step instead of assuming storageState() captured it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
  • Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
  • Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
  • In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
  • Ultra-thin bezels: Maximize your viewing experience with thin bezels.

Synchronize on authentication and data, not on a fixed sleep

page.waitForTimeout() is useful for interactive debugging but produces flaky production tests: a short delay races the application, while a long delay wastes time. Prefer a URL, locator, response or application-ready marker.

Wait for a protected locator

await page.goto('/account');
await expect(page.getByRole('heading', { name: 'Account' })).toBeVisible();
await expect(page.getByTestId('private-panel')).toContainText('');
await page.screenshot({ path: 'account.png', fullPage: true });

Wait for the response that proves private data arrived

const dataResponse = page.waitForResponse(
  response => response.url().endsWith('/api/me') && response.ok(),
);
await page.goto('/account');
await dataResponse;
await expect(page.getByTestId('private-panel')).toBeVisible();
await page.screenshot({ path: 'account.png' });

Start the response wait before the navigation or action that triggers it. If the panel is lazy-loaded, wait for its own visible or text condition. If the page uses an iframe, select the correct frame before locating the panel.

Separate authentication failures from screenshot-target failures

The page is logged out

Capture the final URL and a redacted list of cookie domains in diagnostics. If the URL is a login route, fix state creation or loading first; changing the locator or screenshot options cannot authenticate a page.

The DOM contains the panel but the image does not

An overlay, cookie banner, modal or fixed header may cover it. Hide or close the overlay in the test, and verify the computed visibility and bounding box. A locator screenshot performs actionability checks and scrolls the target into view, which helps target capture but does not add credentials.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The panel is in a frame

const privateFrame = page.frameLocator('iframe[title="Private data"]');
await expect(privateFrame.getByTestId('private-panel')).toBeVisible();
await privateFrame.getByTestId('private-panel').screenshot({ path: 'panel.png' });

The page is authenticated but visually unstable

Animations, changing timestamps and late fonts can alter pixels after login. Once the protected locator is present, expect(page).toHaveScreenshot() waits for two consecutive stable screenshots before comparing with a baseline. It stabilizes rendering; it cannot repair a missing cookie, token or sessionStorage entry.

Rank #4
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
  • SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
  • MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
  • KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
  • INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient

Choose an authentication lifecycle deliberately

Approach Best use Main risk to control
UI login in a setup project End-to-end coverage of the real sign-in flow Save only after the final URL or protected locator.
API login plus storageState Fast, repeatable tests where an API can create the browser session Ensure the API establishes the same cookies/local storage the app expects.
Pre-generated state file One-off screenshots or isolated environments Expiration, wrong domain and accidental credential exposure.
Per-test or worker fixture Different users, tenants or permissions Regenerate state when the account or token lifecycle changes.

Keep accounts isolated by role and tenant. When a state expires, rerun setup rather than silently falling back to a login page that still produces an image.

Common errors and precise fixes

  • “storageState file not found.” Create the directory before setup, use the path configured in the project, and run the setup project rather than invoking only the dependent test.
  • Setup passes, test is logged out. Confirm the dependent project lists dependencies: ['setup'] and that no fixture creates a new context without the state.
  • State exists but redirects to login. Check expiration, cookie domain/path, secure flag, final host and cross-origin identity-provider behavior.
  • Only a blank shell is captured. Wait for the private API response and panel locator; page load does not guarantee application data.
  • Works in headed mode, fails headless. Compare viewport, user agent, permissions, geolocation and timing-sensitive startup code. Replace sleeps with observable signals and inspect a trace.
  • Panel text is present but covered. Locate the overlay and close it, or capture the panel locator after scrolling it into view.
  • API login does not affect the browser. Export the API context’s storage state and pass it when creating the browser context; do not assume two independently created contexts share cookies.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your goal is a clean image or PDF rather than testing an application’s authentication flow, ScreenshotNeo provides a single HTTP request. It can send custom cookies, headers, user agents and Authorization values, so you can supply the session your application requires without maintaining a Playwright browser harness.

For documentation and all options, see ScreenshotNeo’s API documentation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo removes cookie-consent banners, newsletter popups and chat widgets before capture. Bot checks, blank pages, timeouts, failed loads and cache hits are not billed, and response headers identify the page verdict and billing result. Its MCP server exposes take_screenshot, get_page_info and capture_pdf to Claude, Cursor and other MCP clients. The free plan includes 1,000 screenshots each month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

Security and maintenance checklist

  • Use a dedicated, least-privileged test account.
  • Gitignore playwright/.auth and any sessionStorage artifacts.
  • Never print cookie or token values; redact traces and CI logs.
  • Regenerate state after password, MFA, tenant or session-policy changes.
  • Assert the authenticated URL and a protected locator before every screenshot that matters.
  • Keep setup and capture contexts separate when testing multiple roles.

Frequently Asked Questions

Can Playwright reuse a login across different browser projects?

Yes. Save the authenticated context with storageState and configure each dependent project with the resulting file, provided the domains, origins and account permissions are appropriate.

Best Value
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
  • 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
  • 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.

Does storageState include sessionStorage?

No. Serialize sessionStorage after login and restore it with addInitScript before the first navigation.

Will a locator screenshot log me in automatically?

No. Locator screenshots handle actionability and scrolling only. Authentication must already exist in the context.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When should I regenerate an authentication file?

Regenerate it when cookies or tokens expire, account permissions change, or the application changes its login and storage behavior.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.