How to Fix Playwright Screenshots Missing an Authenticated View
Fix Playwright screenshots that show logged-out pages by saving the right auth state, restoring sessionStorage, and waiting for protected content.

If a Playwright screenshot shows a logged-out page, the screenshot code is usually working correctly: the browser context has no valid authentication at capture time. Fix the context first, then capture the page after an explicit authenticated signal.
The reliable sequence is:
- Log in in the same browser context that will take the screenshot, or create that context with a saved
storageState. - Save state only after the final redirect or a protected UI element proves login succeeded.
- Restore sessionStorage separately if the application uses it.
- Navigate to the protected URL and wait for the protected panel or API response.
- Capture the page or locator after the content is visible.
Playwright’s authentication guidance recommends saving authenticated state after a real post-login signal. A screenshot cannot recover a cookie, token or storage entry that is missing from its context.
1. A complete working setup
This setup project logs in once, verifies the final URL and user menu, and saves the browser state. The Chromium project depends on that setup and loads the saved file for every test.
Authenticate once
// 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();
// Login cookies may be set during redirects.
await page.waitForURL('**/dashboard');
await expect(page.getByTestId('user-menu')).toBeVisible();
await page.context().storageState({ path: authFile });
});
Load the state in the test project
// 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'],
},
],
});
Capture the authenticated page
// tests/account.spec.ts
import { test, expect } from '@playwright/test';
test('captures the private account view', async ({ page }) => {
await page.goto('/account');
await expect(page.getByRole('heading', { name: 'Account' })).toBeVisible();
await expect(page.getByTestId('private-panel')).toBeVisible();
await page.screenshot({ path: 'artifacts/account.png', fullPage: true });
});
Keep playwright/.auth in .gitignore. Authentication files can contain cookies and tokens that impersonate the test account. Use a dedicated test account and never print cookie values in diagnostics.
2. Why the screenshot is logged out
The login happened in another context
Each Playwright browser context has isolated cookies, local storage and other state. Logging in with one page does not authenticate a page created in a different context unless you pass the saved state when creating that context.

const browser = await chromium.launch();
const loginContext = await browser.newContext();
const loginPage = await loginContext.newPage();
// ...perform login...
const state = await loginContext.storageState();
const screenshotContext = await browser.newContext({ storageState: state });
const screenshotPage = await screenshotContext.newPage();
await screenshotPage.goto('https://app.example.com/account');
If you create a fresh context manually, provide storageState at construction time. For a one-off test, use test.use({ storageState: 'playwright/.auth/user.json' }).
The state was saved too early
A click completing does not prove that authentication is complete. Cookies may arrive during redirects, and the application may render the private panel only after an API call. Save state after waitForURL, a protected locator assertion or a response that proves the user session exists.
The test loaded the wrong file
Check the path relative to the Playwright configuration, confirm that the test belongs to the project declaring storageState, and verify that the setup project is listed as a dependency. A typo can silently produce a fresh unauthenticated context.
3. What storageState saves, and what it does not
Playwright’s state snapshot preserves cookies, local storage, IndexedDB and supported virtual WebAuthn credentials. It does not automatically persist sessionStorage. Applications that put access tokens or tenant data in sessionStorage need an explicit export and restore step.
Serialize sessionStorage after login
const sessionStorageJson = await page.evaluate(() =>
JSON.stringify(sessionStorage)
);
await fs.promises.writeFile(
'playwright/.auth/session.json',
sessionStorageJson,
'utf8'
);
Restore it before the first navigation
import fs from 'node:fs';
const session = JSON.parse(
fs.readFileSync('playwright/.auth/session.json', 'utf8')
);
const context = await browser.newContext({
storageState: 'playwright/.auth/user.json',
});
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);
}
}
}, session);
const page = await context.newPage();
await page.goto('https://app.example.com/account');
The hostname guard prevents private session data from being copied into another origin. Session storage is origin-specific, so confirm the scheme, host and port match the page being captured.
4. API login without clicking through the UI
If your application exposes a test login endpoint, authenticate with APIRequestContext, save its state, and create a browser context from that state. This keeps the browser test focused on the protected page.
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('/account');
await expect(page.getByTestId('private-panel')).toBeVisible();
await page.screenshot({ path: 'account.png', fullPage: true });
The API endpoint must set the same cookies or storage values that the browser application expects. If it returns only a bearer token that the frontend stores in sessionStorage, restore that value explicitly.
5. Synchronize on authenticated content
Do not use a fixed delay as proof that login or data loading finished. Playwright documents page.waitForTimeout() as flaky for production tests. Use a URL, locator, response or application-ready marker instead.
Wait for the protected locator
await page.goto('/account');
await expect(page.getByTestId('private-panel')).toBeVisible();
await page.screenshot({ path: 'account.png', fullPage: true });
Wait for the data response
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' });
Wait for the final URL
await page.getByRole('button', { name: 'Sign in' }).click();
await page.waitForURL('**/dashboard');
await expect(page.getByTestId('user-menu')).toBeVisible();
Waiting for load alone is insufficient when the private panel is rendered by JavaScript after an API request. Wait for the panel’s own visibility or text condition.
6. Locator screenshots, frames and overlays
A locator screenshot waits for actionability and scrolls the target into view. It helps capture one authenticated component, but it cannot create authentication.

const panel = page.getByTestId('private-panel');
await expect(panel).toBeVisible();
await panel.screenshot({ path: 'private-panel.png' });
If the panel is inside an iframe, select the correct frame first:
const frame = page.frameLocator('iframe[name="billing"]');
await expect(frame.getByTestId('invoice-list')).toBeVisible();
await frame.getByTestId('invoice-list').screenshot({ path: 'invoices.png' });
An overlay can cover a panel even when the panel exists in the DOM. Check cookie dialogs, loading masks, modals and chat widgets. Dismiss them using stable locators before capture, or wait for their hidden state.
7. Visual assertions after authentication
toHaveScreenshot waits for two consecutive stable screenshots before comparing pixels. This is useful after authentication when animations or late layout changes make the image unstable. It does not repair missing cookies, expired tokens or absent sessionStorage.
await page.goto('/account');
await expect(page.getByTestId('private-panel')).toBeVisible();
await expect(page).toHaveScreenshot('account.png', {
fullPage: true,
});
Put the authenticated-content assertion before the visual assertion. Otherwise a stable logged-out page can become the accidental baseline.
8. A diagnostic decision tree
- Did setup reach its completion signal? If not, inspect the login form, credentials, redirects and final URL.
- Was the state file written? Confirm the file exists and contains expected cookie domains and origin entries without exposing values.
- Did the test load that file? Check project selection, dependency order and the path in configuration.
- Is the state expired or scoped incorrectly? Re-run setup and inspect cookie domain, path, secure flag and expiration.
- Does the app use sessionStorage? Export it after login and restore it with
addInitScript. - Is the protected panel lazy-loaded? Wait for its locator or the response that supplies its data.
- Is it in an iframe? Use
frameLocatorand assert the target inside that frame. - Is an overlay hiding it? Wait for the overlay to disappear or close it through the application’s UI.
- Does a service worker or identity provider redirect? Capture a trace and inspect the final request, origin and response chain.
9. Common errors and fixes
| Error or symptom | Likely cause | Fix |
|---|---|---|
| Screenshot shows the login form | No state was loaded, or cookies expired | Verify storageState, rerun setup and wait for the final URL. |
| State file exists but dashboard is empty | Session token is in sessionStorage | Serialize and restore sessionStorage before navigation. |
| Panel exists in DOM but is absent in image | Overlay, iframe or viewport issue | Check overlay visibility, select the correct frame and capture after scrolling or use a locator screenshot. |
| Intermittent logged-out failures | State expires or setup races a redirect | Save after an authenticated assertion and regenerate expired state. |
| API login does not authenticate UI | API sets a different token mechanism | Compare cookies, local storage and sessionStorage expected by the frontend. |
| Visual baseline is the login page | Assertion ran before authentication | Assert a protected locator before toHaveScreenshot. |
10. Reliability, performance and cost considerations
A setup-project state file reduces repeated UI logins and makes tests faster. Regenerate it when credentials, permissions or token lifetimes change. Worker-scoped fixtures can isolate accounts when tests mutate server-side data; a shared account is simpler but can create test interference.
Use explicit response and locator waits instead of long sleeps. They finish as soon as the application is ready and avoid adding a fixed delay to every test. Keep screenshots and traces as artifacts only when a failure needs investigation.
For parallel runs, use separate test accounts when the application changes account data. A single state file can be safely read by many workers, but concurrent mutations may still affect the rendered view.
11. Or skip the browser setup
If your goal is a clean screenshot of a URL rather than a full end-to-end browser test, ScreenshotNeo provides a single screenshot API request. Its options include custom cookies, headers and Authorization, so you can supply the access data your page requires without maintaining a Playwright browser in your capture service. See the ScreenshotNeo API documentation for all parameters.
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 banners, newsletter popups and chat widgets before the shot. Bot checks, blank pages and failed loads are never billed, and response headers identify the page verdict and whether the shot was billed. Its MCP server lets Claude, Cursor and other MCP clients call take_screenshot, get_page_info and capture_pdf. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Create a free ScreenshotNeo account.
12. Security checklist
- Store auth files in a gitignored directory.
- Use dedicated accounts with minimum permissions.
- Mask tokens and cookie values in logs.
- Regenerate state after expiry or permission changes.
- Keep sessionStorage exports protected like passwords.
- Delete artifacts containing private data after debugging.
FAQ
Does storageState include sessionStorage?
No. It includes cookies, local storage, IndexedDB and supported virtual WebAuthn credentials. Export and restore sessionStorage separately.
Can a locator screenshot log me in?
No. It waits for the locator to be actionable and scrolls it into view, but authentication must already exist in the browser context.
Should I wait for network idle?
Use an application signal such as a protected locator, final URL or specific response. Network activity can remain open because of analytics, sockets or polling.
Why does the screenshot work locally but fail in CI?
Check environment credentials, state-file paths, cookie domains, token expiration, timezone and identity-provider redirects. Regenerate state inside the CI job when appropriate.
Can visual comparisons fix an unauthenticated baseline?
No. Visual assertions stabilize pixels and compare them with a baseline; they do not add missing credentials.


