ScreenshotNeo

BlogHow-to

How to Add Authentication Cookies to a Website Screenshot API Request

Pass the target site’s valid session cookie using the screenshot provider’s documented format. Keep it separate from the API key that authenticates your request.

By the ScreenshotNeo team4 October 202610 min read

A screenshot API needs two different credentials for a protected page: the screenshot service’s API key authenticates your request to that service; a valid session cookie lets the browser that renders the target URL access the logged-in page. Put each credential where that provider expects it. Cookie support and request syntax vary by provider, so check the endpoint documentation before sending a request.

The examples below use Cloudflare Browser Run and screenshot-api.net as labeled examples. Their formats are not interchangeable. Use only a session cookie you are authorized to use, and do not place live credentials in public code or logs.

First identify how the target site authenticates you and whether the screenshot endpoint supports that mechanism. A session cookie is one option; HTTP Basic authentication and custom target-site headers are different mechanisms. Cloudflare Browser Run documents cookies, HTTP Basic authentication, and custom headers for authenticated captures. Screenshot-api.net documents a semicolon-separated cookie parameter, repeated target-host headers, and a separate basic_auth option. ScreenshotEngine says its documented endpoint does not expose custom cookies, target-site Authorization headers, or login scripts. See the provider documentation for Cloudflare authenticated screenshots, screenshot-api.net, and ScreenshotEngine authentication.

If the endpoint does not support the target site’s authentication mechanism, its API key will not sign in to that site. Choose a browser-rendering workflow or screenshot service that explicitly supports the required mechanism.

  1. Sign in to the target website through its authorized login flow.
  2. Use the site’s developer tools or an approved session-creation flow to obtain the cookie name and value actually issued by the site. Do not guess cookie names or values.
  3. Check the cookie’s domain and path scope against the URL you will capture. A cookie for one host or path may not be sent to another.
  4. Check its expiration and any site-specific requirements. A copied cookie can expire, be revoked, or depend on other cookies.

In browser developer tools, cookies are commonly listed under the site’s storage or application panel. Follow your browser’s and organization’s policies for handling session credentials.

Cloudflare’s REST example uses a JSON array of cookie objects in the request body. The screenshot service’s bearer token goes in the HTTP Authorization header; the target site’s session cookie goes in the JSON body. Replace the placeholders with your account ID, API token, and authorized session cookie.

curl -X POST 'https://api.cloudflare.com/client/v4/accounts/<accountId>/browser-rendering/screenshot' \
  -H 'Authorization: Bearer <apiToken>' \
  -H 'Content-Type: application/json' \
  -d '{
    "url": "https://example.com/protected-page",
    "cookies": [
      {
        "name": "session_id",
        "value": "<session-cookie-value>",
        "domain": "example.com",
        "path": "/"
      }
    ]
  }' \
  --output screenshot.png

This schema is specific to Cloudflare Browser Run. Its authenticated-page documentation also describes authenticate for HTTP Basic authentication and setExtraHTTPHeaders for custom headers; use those only when they match how the target site authenticates you. See Cloudflare’s examples and Quick Actions documentation.

This provider documents cookies as a string such as name=value; name2=value2. Its POST endpoint accepts the cookie in JSON. Use POST when sending credentials so they are not exposed in a URL query string.

curl -X POST 'https://screenshot-api.net/v1/capture' \
  -H 'Authorization: Bearer YOUR_SCREENSHOT_API_KEY' \
  -H 'Content-Type: application/json' \
  -d '{
    "url": "https://example.com/protected-page",
    "cookies": "session_id=YOUR_SESSION_COOKIE"
  }' \
  --output screenshot.png

For multiple cookies, use the provider’s documented semicolon-separated format, for example session_id=VALUE; preference=VALUE. Do not copy this syntax to another provider unless its documentation specifies it. The provider says cookies are set on the target host before page load and scoped by domain. Its response includes the final document status in X-Page-Status; a 401 or 403 can indicate that the capture shows a login or error page. See the screenshot-api.net documentation.

Python example for screenshot-api.net

This complete example keeps the screenshot API key and target session cookie in environment variables, sends the cookie in a POST body, checks the HTTP response, and writes the returned image.

import os
import requests

api_key = os.environ["SCREENSHOT_API_KEY"]
session_cookie = os.environ["TARGET_SESSION_COOKIE"]

response = requests.post(
    "https://screenshot-api.net/v1/capture",
    headers={
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
    },
    json={
        "url": "https://example.com/protected-page",
        "cookies": f"session_id={session_cookie}",
    },
    timeout=90,
)
response.raise_for_status()

with open("screenshot.png", "wb") as screenshot:
    screenshot.write(response.content)

print("Final page status:", response.headers.get("X-Page-Status", "not provided"))

Install the dependency with python -m pip install requests. Set SCREENSHOT_API_KEY and TARGET_SESSION_COOKIE in your server or shell environment before running the script. The cookie name shown is an example: replace it with the actual name issued by your target site.

Node.js example for screenshot-api.net

This example uses Node.js with built-in fetch. It reads credentials from environment variables, sends JSON in a POST request, checks for an HTTP error, and saves the image bytes.

const apiKey = process.env.SCREENSHOT_API_KEY;
const sessionCookie = process.env.TARGET_SESSION_COOKIE;

if (!apiKey || !sessionCookie) {
  throw new Error('Set SCREENSHOT_API_KEY and TARGET_SESSION_COOKIE first');
}

const response = await fetch('https://screenshot-api.net/v1/capture', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${apiKey}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    url: 'https://example.com/protected-page',
    cookies: `session_id=${sessionCookie}`,
  }),
});

if (!response.ok) {
  throw new Error(`Screenshot request failed: HTTP ${response.status}`);
}

const image = Buffer.from(await response.arrayBuffer());
await (await import('node:fs/promises')).writeFile('screenshot.png', image);
console.log('Final page status:', response.headers.get('x-page-status') ?? 'not provided');

Run it with the two environment variables set. As in the Python example, replace session_id with the target site’s real cookie name. These Python and Node.js examples use screenshot-api.net’s documented endpoint and request shape, not a universal screenshot API schema.

4. Check that the capture reached the authenticated page

A screenshot can be a perfectly valid image of the wrong page. The browser may have rendered a login form, access-denied page, or redirect destination. Inspect the provider’s response status or final-page metadata where available, then inspect the image itself. For screenshot-api.net, the documented X-Page-Status header reflects the final document’s HTTP status after redirects; 401 or 403 is a signal to investigate, not proof of a particular cookie problem.

  • Confirm that the requested URL uses the cookie’s domain and path.
  • Confirm that the cookie has not expired or been revoked and that the site did not require an additional session cookie.
  • Check redirects: the final page may be on a different host where the original cookie does not apply.
  • Make sure the page has finished loading before capture if the site renders its authenticated content asynchronously. Use the provider’s documented wait or load options if available.

5. Keep credentials out of URLs, source control, and logs

Session cookies and API keys are credentials. Anyone who obtains a valid session cookie may be able to use that session, subject to the site’s controls. Keep both values on a trusted server, use a secret store or protected runtime configuration, and avoid committing them to source control or printing request headers and bodies in logs. Prefer a POST body for cookie-bearing requests when the provider supports it; URLs are more likely to appear in access logs, browser history, monitoring, and error reports. The screenshot-api.net docs specifically recommend its POST form for credentials because query strings can be written to access logs.

Limit the session’s permissions and lifetime where the target site allows it. Rotate or revoke a credential if it has been exposed. Do not put an authenticated screenshot request or its secret-bearing URL in public client-side code.

Options and edge cases

Situation What to do
Site uses a session cookie Pass the valid cookie using the screenshot provider’s documented cookie schema.
Site uses HTTP Basic authentication Use the provider’s documented Basic Auth option, if supported. Do not encode those credentials as a session cookie.
Site expects a custom authorization or bypass header Use a supported target-site header option and verify its host and redirect behavior.
Several cookies are required Pass all required cookies in the provider’s expected structure or delimiter format. Do not assume one cookie is sufficient.
Cookie has a narrow path or host scope Capture the matching host and path, or obtain an authorized cookie with suitable scope.
Page redirects to another host Check the final URL and whether the destination requires its own authentication. Cookie scope does not automatically extend to unrelated hosts.
Provider does not support custom cookies Use a service or browser-rendering workflow that documents the needed mechanism. A service API key does not log in to the target site.

Cookie domain and path fields are explicit in Cloudflare Browser Run’s structured cookie example. Screenshot-api.net documents a cookie string set on the target host. Follow the chosen provider’s own scope and schema rules; do not mix formats.

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server for developers. Its API accepts custom cookies, but use the ScreenshotNeo docs for the exact cookie parameter syntax. This one-call example shows the API key and target URL; it is a basic capture request, not a cookie-injection example:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Python:

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)

Node.js:

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, popups, and chat widgets before the shot; bot checks, blank pages, and failed loads are never billed. Its MCP server lets AI agents take screenshots. The free plan includes 1,000 screenshots a month with no card, and paid plans start at $5 for 3,000. Create a free ScreenshotNeo account.

Performance, reliability, and cost

  • Performance: Each request requires the provider to render the page in a browser. Large pages, slow third-party resources, redirects, and delayed client-side rendering can increase capture time. Use documented wait or timeout controls and request only the capture dimensions or page extent you need.
  • Reliability: Treat a successful image response as distinct from a successful authenticated page. Where available, check final-page status and validate that the expected content is present. Retry transient provider or network failures with bounded backoff; do not blindly retry a persistent 401 or 403 with the same expired credential.
  • Cost: Provider pricing and billing rules differ; consult that provider’s current plan and usage documentation. Avoid unnecessary repeated captures and use caching only when the authenticated content and cache semantics are appropriate. ScreenshotNeo states that only clean shots are billed; bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and responses identify the page verdict and billing status in headers.

Troubleshooting

Symptom Likely cause Fix
Screenshot shows a login page Cookie is missing, expired, invalid, incorrectly formatted, or scoped to a different host/path. Obtain a fresh authorized cookie, verify its actual name and value, check scope, and confirm the provider’s required schema.
Final status is 401 or 403 The target site returned an authentication or access-denied response, or a redirect led to a protected destination. Inspect the final URL and response metadata; verify cookie validity and any required headers or additional cookies.
Provider returns 400 or validation error Request body does not match that provider’s schema, fields are misspelled, or JSON is malformed. Compare the request to the provider’s endpoint docs. Cloudflare expects a structured cookie array in its example; screenshot-api.net documents a cookie string.
Provider returns 401 The screenshot service rejected its own API credentials. Check the service API key, authorization header or query parameter, account permissions, and endpoint. This is separate from the target site’s session cookie.
Image is blank or missing expected content Page scripts have not rendered, the capture happened too early, or resources failed. Use documented wait controls, check provider errors and final-page status, and try a smaller or simpler target page to isolate the issue.
Cookie works in a browser but not in capture The browser session may use additional cookies, a different host, or a token bound to browser/device state. Check the site’s authorized session requirements and supply only supported credentials. If authentication is bound to a local browser session, use an appropriate browser workflow.
Cookie appears in logs or a URL Credential was sent in a query string or request logging recorded the body. Use POST where available, redact secret-bearing fields, restrict log access, and rotate an exposed session.
Redirected capture loses authentication Redirect target uses another host or cookie scope. Check the redirect destination and acquire authorization scoped for the destination as permitted by the site.

FAQ

No. The API key authenticates you to the screenshot provider. The target site’s session cookie authenticates the rendering browser to the website.

Do not assume a provider accepts or needs a full cookie jar. Use the minimum authorized cookies required by the target page and the provider’s documented format.

Can I use these examples with any screenshot API?

No. They illustrate provider-specific request formats. Check the exact endpoint documentation for cookie support, encoding, scope, and response metadata.

What if the page is protected by my local browser session?

A hosted API cannot automatically access cookies stored in your local browser. Use an authorized mechanism supported by the site and provider, or a browser workflow that can operate within that session.