logo of Screenshot for Web
Free toolsPlaygroundDocsBlogPricing
LoginDashboard

Company

HomeFeaturesPricingBlogFacts

Screenshot Tools

Website ScreenshotsFull Page ScreenshotsScrolling ScreenshotsWebsite HistoryPDF Generation APIScreenshot API

Legal

Terms of UsePrivacy PolicyCookie PolicyCopyrightSecurity

Support

FAQSupportContact UsAPI Status
screen shot for web logo

No clutter. No distractions. Just clean, full-page screenshots with smart customization.

© 2026 HYDRANODE LTD. All rights reserved.

Screenshot for Web is operated by HYDRANODE LTD, a company registered in England and Wales, company number 15672526. Registered office: 124 City Road, London, London, England, EC1V 2NX.

FacebookInstagramLinkedInYouTube
  1. Home
  2. Blog
  3. Guides

Screenshots of pages behind a login in Playwright and Puppeteer: what to save, tested

Sign in once, save the session and capture signed-in pages. We tested cookies, localStorage, sessionStorage, profile folders and expired sessions against a test app.

Screenshot for Web·October 29, 2026·6 min read

Sources

  1. Playwright docs: Authentication (storage state and session storage)
  2. Playwright API: BrowserContext.storageState() and addCookies()
  3. Puppeteer guide: Cookies (browser.cookies, setCookie, deleteCookie)
  4. Puppeteer API: Page.cookies() deprecation notice
  5. Puppeteer API: LaunchOptions (userDataDir)
  6. MDN: Set-Cookie header (host-only, HttpOnly, session cookies)

How this article was made

Researched and drafted with AI assistance from the sources listed. We wrote the test app, ran every script and made every screenshot on 29 October 2026 on a Mac, with Playwright 1.64.1 (Chromium 156.0.8078.4) and Puppeteer 25.16.0 (Chrome for Testing 156.0.8078.47), against the local test server.

Capture any page without ads, banners or chat widgets, free and without an account.

Try the free tools

More articles

  • News

    Puppeteer 25.19 stops print and dark mode emulation from cancelling each other

    Before Puppeteer 25.19.0, emulateMediaType and emulateMediaFeatures reset each other, losing print or dark mode. Our tests, the fix and a workaround.

    November 26, 2026
  • News

    Chrome 158 drops XSLT: what it does to screenshots of sitemaps and feeds

    We captured eight live sitemaps in Chrome 156 and Chromium 158. Styled pages turn into raw XML, a red warning bar is already in captures, and two fixes work.

    November 9, 2026
  • Research

    Chrome DevTools' full-size screenshot: where it fails on long and lazy pages

    We ran DevTools' full-size screenshot on six long pages: it stops at 16,384 pixels and misses content that appears on scroll. Here's why, and the fixes that worked.

    November 8, 2026

To screenshot a page behind a login, sign in once in a script, save the browser's state to a file, and start every later capture from that file. In Playwright that is context.storageState({ path }) and browser.newContext({ storageState }). In Puppeteer it is browser.cookies() and browser.setCookie(), plus a few lines for localStorage. We built a small test app that keeps people signed in three different ways and ran each method against it. The full saved state worked every time. Cookies alone missed the token-based part of the app, sessionStorage was never saved, a Chrome profile folder lost the session cookie on restart, and an expired session produced a screenshot of the sign-in form with HTTP 200 and no error.

The test app

Sites keep a signed-in state in one of a few places, and a screenshot script has to carry over whichever one the site uses. Our test app, a 75-line Node server on localhost:4100, has one page for each:

PageWhere the sign-in livesHow the page checks it
/dashboardAn HttpOnly cookie named sid, with no Expires or Max-AgeServer reads the cookie; without a valid one it redirects to /login
/appA token in localStoragePage script sends it as a Bearer header to /api/me
/tabA token in sessionStorageSame as /app

An HttpOnly cookie can't be read by the page's JavaScript through document.cookie, and a cookie without Expires or Max-Age is a session cookie, which the browser removes when it shuts down (MDN's Set-Cookie reference covers both). Our app's sign-in accepts any password, because it is a test app; the scripts still read one from an environment variable, the way you would against a real site.

Sign in once and save the state with Playwright

This script fills the sign-in form, waits for the dashboard, collects a token for the localStorage part of the app, and writes everything to .auth/state.json:

// Step 1: sign in once and save the browser's state.
const { chromium } = require("playwright");

(async () => {
  const browser = await chromium.launch();
  const context = await browser.newContext();
  const page = await context.newPage();

  await page.goto("http://localhost:4100/login");
  await page.fill('input[name="email"]', "demo@example.test");
  await page.fill('input[name="password"]', process.env.DEMO_PASSWORD);
  await Promise.all([page.waitForURL("**/dashboard"), page.click("button")]);

  // Token-based parts of the app keep their token in localStorage.
  await page.goto("http://localhost:4100/app");
  await page.evaluate(async () => {
    const { token } = await (await fetch("/api/token", { method: "POST" })).json();
    localStorage.setItem("token", token);
  });

  await context.storageState({ path: ".auth/state.json" });
  await browser.close();
})();

The saved file, with the secret values cut short by us:

{
  "cookies": [
    { "name": "sid", "value": "ad5baa…", "domain": "localhost", "path": "/",
      "expires": -1, "httpOnly": true, "secure": false, "sameSite": "Lax" }
  ],
  "origins": [
    { "origin": "http://localhost:4100",
      "localStorage": [ { "name": "token", "value": "d9be9a…" } ] }
  ]
}

Two details matter. The HttpOnly cookie is in the file even though the page itself could never read it, because Playwright reads cookies from the browser, not from the page. And the session cookie is saved with expires: -1, so it survives in the file after the browser closes. The file is a working sign-in: Playwright's authentication guide warns that it can be used to impersonate the account and strongly discourages committing it to a repository. Keep it in a folder listed in .gitignore.

Capture from the saved state, and refuse the sign-in page

The second script opens a new context from the file and captures two pages. It also checks where each page ended up before it takes the screenshot:

// Step 2: capture signed-in pages from the saved state, and refuse login-page screenshots.
const { chromium } = require("playwright");

async function captureSignedIn(context, url, path, signedInSelector) {
  const page = await context.newPage();
  const response = await page.goto(url);
  const landed = new URL(page.url()).pathname;
  if (landed.startsWith("/login")) {
    throw new Error(`${url} redirected to ${page.url()} (HTTP ${response.status()}): the saved session has expired`);
  }
  await page.waitForSelector(signedInSelector, { timeout: 5000 });
  await page.screenshot({ path });
  await page.close();
}

(async () => {
  const browser = await chromium.launch();
  const context = await browser.newContext({ storageState: ".auth/state.json" });
  await captureSignedIn(context, "http://localhost:4100/dashboard", "out/dashboard.png", ".kpi");
  await captureSignedIn(context, "http://localhost:4100/app", "out/app.png", ".kpi");
  console.log("captured both pages");
  await browser.close();
})().catch((err) => {
  console.error(err.message);
  process.exit(1);
});

With a fresh state file it printed captured both pages, and both screenshots show the signed-in dashboard.

The check is there because of what happened next. We restarted the server with sessions that expire after 5 seconds, signed in, waited 6 seconds, and ran a plain script that only calls goto and screenshot. It printed status 200 url http://localhost:4100/login?next=/dashboard -> screenshot saved. The server's redirect was followed, the sign-in page arrived with status 200, and the script saved a picture of the sign-in form without any error. A scheduled job would keep doing that every day. The guarded script stopped instead, with exit code 1 and this message:

http://localhost:4100/dashboard redirected to http://localhost:4100/login?next=/dashboard (HTTP 200): the saved session has expired

Checking the final URL catches redirects. Waiting for an element that only signed-in pages have, like .kpi here, catches apps that show a "signed out" message at the same address. Use both.

What the saved state does and doesn't carry

We then started fresh contexts in four ways and read the first line of each page. The results, from experiments.js:

SetupPageResult
Cookies only (context.addCookies(state.cookies))/dashboardSigned in
Cookies only/app"You are signed out."
Full storageState/appSigned in with the localStorage token
Full storageState, opened as 127.0.0.1:4100/dashboardRedirected to /login
Full storageState/tab"You are signed out."
Init script restoring sessionStorage/tabSigned in with the sessionStorage token

Copying only the cookies, which many scripts do, is enough for sites that keep the whole sign-in in a cookie and not for apps that keep a token in localStorage.

The host name has to match. Our cookie was set without a Domain attribute, which makes it a host-only cookie, sent only to the host that set it. localhost and 127.0.0.1 reach the same server but are different hosts to the browser, so the dashboard redirected to the sign-in page. Sign in on the exact host you will capture.

sessionStorage isn't in the file at all: after saving a sessionStorage token, storageState() returned "origins": []. Playwright's authentication guide says it has no API for session storage and shows a workaround, which we ran: read sessionStorage with page.evaluate, then write it back from an init script in the new context, only on the right host.

// Save, in the signed-in page:
const session = await page.evaluate(() => JSON.stringify(sessionStorage));

// Restore, in a new context, before any page script runs:
await context.addInitScript(([data, host]) => {
  if (location.host === host) {
    for (const [key, value] of Object.entries(JSON.parse(data))) sessionStorage.setItem(key, value);
  }
}, [session, "localhost:4100"]);

Playwright's API reference also lists an indexedDB: true option for storageState(), added in version 1.51, for apps that keep their sign-in in IndexedDB. Our test app doesn't use IndexedDB, so we didn't test it.

The same thing in Puppeteer

Puppeteer has no single storage-state file, so you save cookies and localStorage separately. Puppeteer's cookie guide uses browser.cookies() and browser.setCookie(); the page-level page.cookies() is marked deprecated in its API reference in favour of those. localStorage belongs to the page's origin, so it has to be written from inside a page of that origin, before the app's own script reads it. page.evaluateOnNewDocument does that.

// Puppeteer: save cookies and localStorage after signing in, restore them in a fresh browser.
const puppeteer = require("puppeteer");
const fs = require("node:fs");

const ORIGIN = "http://localhost:4100";

async function signInAndSave() {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto(`${ORIGIN}/login`);
  await page.type('input[name="password"]', process.env.DEMO_PASSWORD);
  await Promise.all([page.waitForNavigation(), page.click("button")]);
  await page.goto(`${ORIGIN}/app`);
  const localStorageData = await page.evaluate(async () => {
    const { token } = await (await fetch("/api/token", { method: "POST" })).json();
    localStorage.setItem("token", token);
    return JSON.stringify(localStorage);
  });
  const cookies = await browser.cookies();
  console.log("document.cookie:", JSON.stringify(await page.evaluate(() => document.cookie)));
  console.log("browser.cookies():", cookies.map((c) => `${c.name} httpOnly=${c.httpOnly} session=${c.session}`).join(", "));
  fs.writeFileSync(".auth/pptr.json", JSON.stringify({ cookies, localStorage: localStorageData }));
  await browser.close();
}

async function captureFromSaved() {
  const saved = JSON.parse(fs.readFileSync(".auth/pptr.json", "utf8"));
  const browser = await puppeteer.launch();
  await browser.setCookie(...saved.cookies);
  const page = await browser.newPage();
  // localStorage has to be written by the page's own origin, before the app's script runs.
  await page.evaluateOnNewDocument((origin, data) => {
    if (location.origin === origin) {
      for (const [key, value] of Object.entries(JSON.parse(data))) localStorage.setItem(key, value);
    }
  }, ORIGIN, saved.localStorage);
  for (const path of ["/dashboard", "/app"]) {
    await page.goto(`${ORIGIN}${path}`);
    await page.waitForSelector(".kpi", { timeout: 5000 });
    console.log(path, "->", page.url(), "|", (await page.$eval("main", (m) => m.innerText)).split("\n")[0]);
  }
  await page.screenshot({ path: "out/pptr-app.png" });
  await browser.close();
}

signInAndSave().then(captureFromSaved);

Its output:

document.cookie: ""
browser.cookies(): sid httpOnly=true session=true
/dashboard -> http://localhost:4100/dashboard | Visitors
/app -> http://localhost:4100/app | Signed in with a localStorage token as demo@example.test

The page saw an empty document.cookie, while browser.cookies() returned the HttpOnly session cookie. That is why reading cookies with page.evaluate(() => document.cookie) doesn't work for most sign-ins.

Why a profile folder isn't enough

The other common approach is to give the browser a persistent profile folder, userDataDir in Puppeteer or launchPersistentContext in Playwright, sign in once, and reuse the folder. We signed in with each, closed the browser, and launched it again on the same folder:

ToolAfter the restart/dashboard/app
Puppeteer, userDataDirbrowser.cookies() returned []Redirected to /loginStill signed in
Playwright, launchPersistentContextcontext.cookies() returned []Redirected to /loginNot tested

The localStorage token survived the restart, but the session cookie did not, which matches MDN's description of session cookies being removed when the client shuts down. Many sites set a sign-in cookie with an expiry date, which a profile folder would keep, but you can't tell which kind a site uses until it fails. The storage-state file had no such problem: Playwright saved the session cookie with expires: -1 and restored it into the new context.

A checklist for signed-in captures

  1. Sign in with a script, on the exact host name you will capture, using credentials from environment variables.
  2. Save the full state: Playwright's storageState, or Puppeteer's browser.cookies() plus localStorage. Add sessionStorage by hand if the site uses it.
  3. Keep the state file out of version control.
  4. Before every screenshot, check the final URL and wait for an element only signed-in pages have.
  5. When the check fails, sign in again and retry once, then stop and report.

Our free screenshot tools capture public pages only; for pages behind a login, run the capture in your own browser as above.