Tutorial

How to Capture Screenshots with Authentication and Cookies

Pass a session cookie or header with the capture request and Screenshotly renders the page as that user. How each method works, which one leaks least, and how to make the request fail instead of returning a login screen.

Asad AliDecember 28, 202510 min read

Dashboards, admin panels, account pages, and gated documentation all sit behind a login. To capture them, the headless browser that renders the page needs the same credentials a signed-in user's browser would send. With the Screenshotly API you provide those credentials in the capture request, as cookies or as HTTP headers, and the page renders as that user.

This guide covers how that works in Screenshotly, which method to choose, complete examples, and the security trade-offs of each approach.

What you need

  • A Basic plan or higher. The cookies and headers fields are gated; on Free they return 403 with "minimumPlan": "basic". See pricing.
  • A target reachable from the public internet. Screenshotly resolves the hostname and refuses localhost, private network ranges (10.x, 172.16–31.x, 192.168.x and others), link-local addresses, and names ending in .local, .internal, or .home.arpa. The same check runs on every request the page makes while it renders, so scripts or images served from an internal host will be blocked too. A staging site behind a VPN will not work; a public staging URL protected by a login will.
  • Credentials for a dedicated capture account in the target app, as explained in the security section below.

How Screenshotly renders an authenticated page

For each capture, Screenshotly:

  1. Launches a new headless Chromium instance. Nothing from earlier captures, including other customers' cookies, is present.
  2. Sets the cookies you sent, after checking that each cookie's domain matches the target hostname or one of its parent domains.
  3. Applies any custom headers you sent to every request the page makes.
  4. Navigates to the URL and waits for DOM content, or for network idle if waitForNetworkIdle is true.
  5. Applies waitForSelector, delay, and any other options, captures the result, and closes the browser.

Because cookies and headers are set before navigation, the very first request to your app is already authenticated.

Choosing a method

Method Use it when Reaches third parties? Notes
Session cookie The app uses cookie sessions (most server-rendered apps and many SPAs) No; the browser only sends a cookie to its own domain The default choice
Custom header An internal render route checks an Authorization or custom header Yes; the header goes with every request the page makes, including CDNs and analytics Use only for pages that load nothing from other origins
HTTP Basic (header) A staging site sits behind Basic auth Yes, for the same reason Credentials in the URL (https://user:pass@…) are rejected
Token in localStorage An SPA reads a JWT from localStorage n/a No direct support; see the SPA section

Session cookies

Each entry in cookies accepts these fields, up to 50 cookies per request:

Field Required Behavior
name Yes 1–256 characters
value Yes Up to 4,096 characters
domain No Defaults to the target URL's hostname. A different value must be the target hostname or a parent domain, otherwise the request fails with 400
path No Defaults to /
httpOnly No Defaults to false
secure No Defaults to true for HTTPS targets

Other cookie attributes such as sameSite or expires are not supported and are dropped, so do not rely on them. (Unknown fields at the top level of the request are rejected with 400.)

Get a session for the capture account

If your app has a JSON login endpoint, your server can sign in as the capture account and keep the session cookie. Replace the URL, field names, and cookie name with your app's:

// Node.js 20+. Signs in as the capture account and returns the session cookie value.
async function getCaptureSession() {
  const response = await fetch('https://app.example.com/api/login', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      email: process.env.CAPTURE_ACCOUNT_EMAIL,
      password: process.env.CAPTURE_ACCOUNT_PASSWORD,
    }),
    redirect: 'manual',
  });

  const pair = response.headers
    .getSetCookie()
    .map((header) => header.split(';')[0])
    .find((cookie) => cookie.startsWith('session='));

  if (!pair) throw new Error(`Login failed with status ${response.status}`);
  return pair.slice('session='.length);
}

A cleaner option, if you control the app, is to have its backend issue a short-lived session for the capture user directly. That avoids storing a password and sidesteps MFA and SSO prompts.

Send it with the capture request

async function captureLoggedInPage(url, sessionValue) {
  const response = await fetch('https://screenshotly.app/api/screenshot', {
    method: 'POST',
    headers: {
      'x-api-key': process.env.SCREENSHOTLY_API_KEY,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      url,
      format: 'png',
      fullPage: true,
      waitForSelector: '[data-testid="dashboard"]',
      cookies: [
        { name: 'session', value: sessionValue, httpOnly: true, secure: true },
      ],
    }),
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(`${response.status} ${error.error}: ${error.message ?? ''}`);
  }

  return Buffer.from(await response.arrayBuffer());
}

const session = await getCaptureSession();
const png = await captureLoggedInPage('https://app.example.com/dashboard', session);

domain is omitted, so the cookie is set for app.example.com. If your app shares a session across subdomains, set domain to the parent, for example example.com.

Apps that need several cookies

Some apps split the session across cookies, for example a session ID plus a separate tenant or CSRF cookie. Send them all:

{
  "url": "https://app.example.com/admin/reports",
  "format": "png",
  "cookies": [
    { "name": "session_id", "value": "SESSION_VALUE" },
    { "name": "tenant", "value": "acme" },
    { "name": "csrf_token", "value": "CSRF_VALUE" }
  ]
}

Copy the cookie names from your browser's developer tools (Application → Cookies) while signed in as the capture account.

Custom headers

Some apps expose a render route that authenticates with a header rather than a cookie:

{
  "url": "https://app.example.com/render/weekly-report",
  "format": "pdf",
  "headers": {
    "Authorization": "Bearer SHORT_LIVED_RENDER_TOKEN"
  }
}

(PDF output also needs Basic or higher.)

Keep in mind that custom headers are attached to every request the page makes, not only the first one. If the page loads fonts from a CDN, an analytics script, or an embedded video, those third parties receive the header too. Use headers only for routes that load assets from your own origin, and make the token short-lived and limited to rendering.

A few header names cannot be set: Host, Connection, Content-Length, Forwarded, Proxy-Authorization, TE, Transfer-Encoding, Upgrade, and the X-Forwarded-* family. You can send at most 50 headers, each value up to 4,096 characters.

HTTP Basic authentication

URLs that embed credentials, such as https://user:pass@staging.example.com, are rejected with 400 ("URLs containing credentials are not allowed"). Send an Authorization header instead:

const basic = Buffer.from(
  `${process.env.STAGING_USER}:${process.env.STAGING_PASSWORD}`,
).toString('base64');

const body = {
  url: 'https://staging.example.com/pricing',
  format: 'png',
  headers: { Authorization: `Basic ${basic}` },
};

The third-party warning above applies here as well: every origin the staging page loads will see those credentials. Use a throwaway staging password, not one shared with anything else.

Single-page apps that keep tokens in localStorage

Screenshotly sets cookies and headers before the page loads, but it has no way to write localStorage before your app's JavaScript runs. The javascript option (Growth and higher) runs only after the page has loaded, which is too late for apps that read their token on startup, and reloading the page from that script is not a reliable way to recover.

Better options, in order of preference:

  1. Let the app accept a cookie. Many SPA auth libraries can read the session from an HttpOnly cookie as well as storage. This also protects the token from cross-site scripting.
  2. Add a one-time render link. Your backend issues a single-use URL such as https://app.example.com/render?ticket=… that exchanges the ticket for a session cookie and redirects to the page. Make the ticket expire within a minute or two. The full URL will appear in your own logs and in the url field of Screenshotly webhook payloads, which is why it must be single-use.
  3. Render a server-side version of the view specifically for capture, authenticated with a cookie.

Make the request fail instead of capturing a login page

Screenshotly cannot tell your dashboard from your login screen; both are a successful render. An expired session therefore produces a 200 with a picture of the login form.

waitForSelector helps timing but does not fail the request: if the element never appears, the capture continues after 10 seconds. To get a hard failure, use selector with an element that only exists for signed-in users. If it is missing, the API returns 400 with "Element with selector … was not found", and failed requests use no quota.

{
  "url": "https://app.example.com/dashboard",
  "format": "png",
  "selector": "[data-testid='dashboard']",
  "cookies": [{ "name": "session", "value": "SESSION_VALUE" }]
}

This captures only that element. If you need the full page, run the element check as a cheap first request or validate the result in your own pipeline before publishing it.

Security practices that matter

Use a dedicated, read-only capture account. Give it access to exactly the pages you capture, ideally in a demo tenant with sample data. Never reuse a real person's session.

Keep sessions short and mint them per run. Create a session at the start of a batch and revoke it at the end. If the session leaks from a log, it is already useless.

Keep credentials on the server. The capture request contains your Screenshotly key and the target app's session, so it must be sent from your backend, never from browser code. Do not log request bodies.

Prefer cookies to headers. Cookies stay on your domain; headers travel to every origin the page loads.

Be careful with caching and retention. With cache: true (Basic and higher), the cache key includes your cookies and headers, so two different sessions never share a cached image. But a cached image stays valid for the whole cacheTtl even if you revoke the session, and cached responses are sent with Cache-Control: public. Do not enable caching for private pages that pass through a shared CDN or proxy. Similarly, storage delivery returns a signed link that anyone holding it can open for 24 hours, and the file is kept for the workspace owner's retention period (7 days by default, 1–30 configurable in dashboard settings). Choose the shortest retention that works.

Do not plan on IP allowlisting. There is no published list of capture IP addresses to allowlist, so authenticate with credentials instead.

Know what Screenshotly keeps. Synchronous captures are not stored unless you ask for caching or storage. Async job requests, including their cookies and headers, and queued webhook deliveries are encrypted with AES-256-GCM before they reach the database. The full picture is on the security page, and integration-side practices such as key storage and proxying are in the screenshot API security guide.

Long batches and expiring sessions

When you capture many pages in one run, refresh the session before it expires rather than after a failure:

class CaptureSession {
  constructor(ttlMs) {
    this.ttlMs = ttlMs;
    this.value = null;
    this.expiresAt = 0;
  }

  async get() {
    // Refresh one minute early so no capture starts with a nearly expired session.
    if (!this.value || Date.now() > this.expiresAt - 60_000) {
      this.value = await getCaptureSession();
      this.expiresAt = Date.now() + this.ttlMs;
    }
    return this.value;
  }
}

const session = new CaptureSession(10 * 60_000);
for (const path of ['/dashboard', '/reports', '/settings']) {
  const png = await captureLoggedInPage(`https://app.example.com${path}`, await session.get());
  // store png ...
}

Keep the loop within your plan's per-minute limit (5 on Free, 40 on Basic, 80 on Growth, 200 on Scale). For large runs, async jobs avoid holding HTTP connections open, and batch jobs (Growth and higher) accept up to 20 captures per call.

Troubleshooting

Symptom Likely cause Fix
403 "authenticated page cookies requires the basic plan or higher" Free plan Upgrade, or test unauthenticated pages first
400 "Cookie domain … does not match the target URL" domain is not the target hostname or a parent of it Omit domain, or set it to the hostname or its parent
400 "Header … is not allowed" A forbidden header name such as Host or X-Forwarded-For Remove it
400 "URLs containing credentials are not allowed" user:pass@ in the URL Send an Authorization: Basic header
400 "Unsafe URL" The host resolves to a private or internal address Use a publicly reachable URL
200, but the image shows the login page Session expired, wrong cookie name, or a missing companion cookie Refresh the session, compare cookie names with devtools, and use the selector check
Page renders but images or styles are missing Assets served from an internal host are blocked, or the page needs more time Serve assets publicly; add waitForNetworkIdle or waitForSelector
SPA shows an empty shell The app reads its token from localStorage Switch to cookie auth or a one-time render link

Summary

  1. Authenticated captures need Basic or higher and a publicly reachable target.
  2. Send a session cookie for a dedicated, read-only capture account; it is the method that leaks least.
  3. Treat custom headers and Basic auth as visible to every origin the page loads.
  4. Use selector on a signed-in-only element when a login screen must count as a failure.
  5. Keep sessions short, keep requests server-side, and be deliberate about caching and retention.

Ready to capture logged-in pages? Create a free account to test the request shape, then move to Basic when you add cookies. New to the API? Start with your first request.

See also: Documentation screenshot automation

authentication
cookies
protected pages
api
security

About the Author

Asad Ali

Asad Ali

CTO at ZTABS and the developer behind Screenshotly. Writes about screenshot automation, API design, and building reliable SaaS backends with Next.js, Node.js, and TypeScript.

Credentials: CTO at ZTABS, full-stack developer, builder and maintainer of Screenshotly and its official JavaScript and Python clients

Frequently Asked Questions

Which Screenshotly plan supports authenticated captures?

Basic and higher. Requests that include cookies or headers on the Free plan return 403 with minimumPlan set to basic. The optional javascript field, sometimes used for token-based apps, needs Growth or higher.

Is it safe to pass my own session cookie to the capture API?

Use a dedicated capture account instead. A personal session carries all of your permissions, and signing out or changing your password breaks the pipeline. A read-only capture account limits what a leaked session can do and can be revoked without affecting anyone.

How do I capture pages behind SSO or MFA?

Avoid automating the interactive login. The most reliable pattern is for your own backend to issue a short-lived session for a read-only capture user and pass that cookie to Screenshotly. If that is not possible, sign in once in a browser you control and reuse the resulting session cookie until it expires.

Can Screenshotly capture an intranet or a staging site behind a VPN?

No. Target URLs must resolve to public IP addresses. Localhost, private network ranges, and internal hostnames such as .local or .internal are rejected, and the same check applies to every resource the page loads. Expose a publicly reachable, authenticated staging URL instead.

Why did I get a screenshot of the login page instead of the dashboard?

The target app did not accept the session, usually because it expired, the cookie name or domain is wrong, or another required cookie is missing. Screenshotly cannot tell a login page from a dashboard, so it returns 200. Capture an element that only exists for signed-in users with selector; if it is missing, the request fails with 400.

Ready to capture your first screenshot?

Get started with 100 free screenshots. No credit card required.

Related Articles