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:
| Page | Where the sign-in lives | How the page checks it |
|---|
/dashboard | An HttpOnly cookie named sid, with no Expires or Max-Age | Server reads the cookie; without a valid one it redirects to /login |
/app | A token in localStorage | Page script sends it as a Bearer header to /api/me |
/tab | A token in sessionStorage | Same 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:
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")]);
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:
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:. 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:
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:
| Setup | Page | Result |
|---|
Cookies only (context.addCookies(state.cookies)) | /dashboard | Signed in |
| Cookies only | /app | "You are signed out." |
Full storageState | /app | Signed in with the localStorage token |
Full storageState, opened as 127.0.0.1:4100 | /dashboard | Redirected to /login |
Full storageState | /tab | "You are signed out." |
| Init script restoring sessionStorage | /tab | Signed 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.
const session = await page.evaluate(() => JSON.stringify(sessionStorage));
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.
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();
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:
/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:
| Tool | After the restart | /dashboard | /app |
|---|
Puppeteer, userDataDir | browser.cookies() returned [] | Redirected to /login | Still signed in |
Playwright, launchPersistentContext | context.cookies() returned [] | Redirected to /login | Not 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
- Sign in with a script, on the exact host name you will capture, using credentials from environment variables.
- Save the full state: Playwright's
storageState, or Puppeteer's browser.cookies() plus localStorage. Add sessionStorage by hand if the site uses it.
- Keep the state file out of version control.
- Before every screenshot, check the final URL and wait for an element only signed-in pages have.
- 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.