How to Fix Puppeteer and Pyppeteer Screenshots of SSR Pages
Fix SSR screenshot timing with app-ready signals, network waits, stable layouts, and practical Puppeteer and Pyppeteer examples.

Direct answer: an SSR response can arrive before the browser application has hydrated. Do not take the screenshot just because goto() returned or because the initial HTML exists. Navigate to the real URL, wait for a condition that proves the final content is ready, wait for fonts and layout stability when needed, then capture.
Navigation lifecycle events describe document and resource milestones. They do not know when your application has finished hydration, fetched data, mounted controls, or settled its layout. The Puppeteer Page API and screenshots guide, plus the Pyppeteer page source, document the building blocks used below.
1. Use a page-specific ready signal
The most reliable signal is one owned by the application: a hydration flag, a selector rendered only after data is loaded, or a visible status element that says the target region is complete. A selector that already exists in server-rendered HTML can resolve too early, so choose a condition tied to the completed state.

Puppeteer: complete runnable example
import puppeteer from 'puppeteer';
const url = process.argv[2] ?? 'https://example.com/ssr-page';
const browser = await puppeteer.launch({headless: true});
const page = await browser.newPage();
try {
await page.setViewport({width: 1280, height: 800, deviceScaleFactor: 1});
const response = await page.goto(url, {
waitUntil: 'domcontentloaded',
timeout: 30000
});
if (!response) throw new Error('Navigation returned no response');
if (!response.ok()) throw new Error(`HTTP ${response.status()} at ${page.url()}`);
// The application must set this flag after hydration and data rendering.
await page.waitForFunction(
() => window.__APP_READY__ === true,
{timeout: 30000}
);
// Screenshot() does not automatically wait for fonts.
await page.evaluate(() => document.fonts.ready);
await page.screenshot({
path: 'ssr-page.png',
type: 'png',
fullPage: true,
animations: 'disabled'
});
} finally {
await browser.close();
}
window.__APP_READY__ is illustrative. The target application must set it, for example after its hydration and data promises complete. If you cannot change the application, replace the predicate with a selector or content assertion that proves the exact region is populated.
Use a readiness selector when the app exposes one
await page.goto(url, {waitUntil: 'domcontentloaded'});
await page.waitForSelector('[data-page-ready="true"]', {visible: true, timeout: 30000});
await page.screenshot({path: 'ready.png', fullPage: true});
Prefer a marker such as data-page-ready over a generic heading or container that appears in the server response. A selector should represent completion, not merely existence.
2. Choose the navigation wait deliberately
| waitUntil value | What it means | Use it when | Risk |
|---|---|---|---|
domcontentloaded |
The HTML document has been parsed. | You will wait for an application signal afterward. | Hydration, images, fonts, and data may still be pending. |
load |
The load event has fired. | Traditional page resources are part of your readiness definition. | Client requests and rendering can continue. |
networkidle2 |
At most two active network connections for the idle window. | The site has finite background traffic and this is a useful broad milestone. | Analytics, polling, or streams can make it early or never settle. |
networkidle0 |
No active network connections for the idle window. | A page is known to stop all requests before the desired state. | Long polling, streaming, and telemetry can prevent completion. |
The Puppeteer screenshots guide demonstrates networkidle2. Treat it as a navigation milestone, then wait for the page-specific condition when hydration is asynchronous. Pyppeteer documents equivalent load, domcontentloaded, and networkidle0 choices; its networkidle0 condition means no more than zero connections for at least 500 ms.
Combining a milestone with an app signal
await page.goto(url, {waitUntil: 'networkidle2', timeout: 45000});
await page.waitForSelector('#results[data-state="complete"]', {
visible: true,
timeout: 30000
});
await page.evaluate(() => document.fonts.ready);
await page.screenshot({path: 'final.png', fullPage: true});
Increase the timeout only when the page genuinely needs it. A longer timeout cannot fix a readiness condition that never becomes true.
3. Pyppeteer: wait for hydration before capture
import asyncio
import sys
from pyppeteer import launch
async def main():
url = sys.argv[1] if len(sys.argv) > 1 else 'https://example.com/ssr-page'
browser = await launch(headless=True)
page = await browser.newPage()
try:
await page.setViewport({'width': 1280, 'height': 800, 'deviceScaleFactor': 1})
response = await page.goto(
url,
{'waitUntil': 'domcontentloaded', 'timeout': 30000}
)
if response is None:
raise RuntimeError('Navigation returned no response')
if not response.ok:
raise RuntimeError(f'HTTP {response.status} at {page.url}')
# The target app must set this after hydration and data rendering.
await page.waitForFunction(
'window.__APP_READY__ === true',
{'timeout': 30000}
)
await page.evaluate('document.fonts.ready')
await page.screenshot({
'path': 'ssr-page.png',
'fullPage': True
})
finally:
await browser.close()
asyncio.get_event_loop().run_until_complete(main())
Confirm method signatures against the Pyppeteer version installed in your project. The cited project source is from its development branch, and browser compatibility can depend on your package and Chromium versions.
Pyppeteer with a selector
await page.goto(url, {'waitUntil': 'domcontentloaded'})
await page.waitForSelector(
'[data-page-ready="true"]',
{'visible': True, 'timeout': 30000}
)
await page.screenshot({'path': 'ready.png', 'fullPage': True})
4. Understand setContent
setContent(html) assigns markup to the main frame. It does not prove that scripts loaded by that markup have finished hydration or asynchronous data work. Wait for the same selector, flag, or content assertion you would use after navigation.
await page.setContent(html, {'waitUntil': 'domcontentloaded'})
await page.waitForFunction('window.__APP_READY__ === true')
await page.evaluate('document.fonts.ready')
await page.screenshot({'path': 'rendered.png', 'fullPage': True})
If the HTML references external styles, fonts, or scripts, verify that those requests succeed before diagnosing screenshot timing.
5. Stabilize fonts, images, and moving layout
Hydration can finish while visual rendering is still changing. Missing fonts can alter line breaks; lazy images can change page height; animations can move elements between frames.
- Await
document.fonts.readyin page context when typography matters. Puppeteer’s documentedwaitForFontsoption belongs to PDF generation; do not assumepage.screenshot()uses it automatically. - Scroll through a full page when the application lazy-loads content, or use an application signal that confirms all target images are loaded.
- Disable animations with a test stylesheet or the screenshot option available in your installed Puppeteer version.
- Use a stable element condition when the target is a component that can move during hydration. Puppeteer’s locator API documents stable-bounding-box waiting across animation frames.
await page.addStyleTag({content: `
*, *::before, *::after {
animation: none !important;
transition: none !important;
caret-color: transparent !important;
}
`});
await page.evaluate(() => document.fonts.ready);
await page.screenshot({path: 'stable.png', fullPage: true});
6. Capture only what you need
| Goal | Puppeteer option | Pyppeteer option |
|---|---|---|
| Entire document | fullPage: true |
'fullPage': True |
| One element | Get its bounding box and pass clip |
Get its bounding box and pass 'clip' |
| Transparent output | omitBackground: true |
'omitBackground': True |
| JPEG or WebP | type: 'jpeg' or 'webp' |
'type': 'jpeg' or 'webp' |
| Retina dimensions | Set deviceScaleFactor in the viewport |
Set 'deviceScaleFactor' in the viewport |
const card = await page.$('.product-card');
if (!card) throw new Error('Product card was not found');
const clip = await card.boundingBox();
if (!clip) throw new Error('Product card is not visible');
await page.screenshot({path: 'card.webp', type: 'webp', clip});
Set the viewport before navigation so responsive server rendering and client layout use the intended dimensions. A viewport change after navigation can trigger another responsive render and invalidate an earlier readiness check.
7. Diagnose a blank, partial, or stale screenshot
Capture evidence around the failure instead of adding arbitrary sleeps. Record the final URL, navigation status, console errors, page errors, failed requests, and whether the readiness condition resolved.
page.on('console', message => console.log('[console]', message.type(), message.text()));
page.on('pageerror', error => console.error('[pageerror]', error));
page.on('requestfailed', request => {
console.error('[requestfailed]', request.url(), request.failure()?.errorText);
});
const response = await page.goto(url, {waitUntil: 'domcontentloaded'});
console.log({finalUrl: page.url(), status: response?.status()});
await page.screenshot({path: 'diagnostic-before-ready.png', fullPage: true});
await page.waitForFunction(() => window.__APP_READY__ === true, {timeout: 30000});
await page.screenshot({path: 'diagnostic-after-ready.png', fullPage: true});
| Symptom | Likely cause | Fix |
|---|---|---|
| Server text appears, interactive controls are missing | Capture occurred before hydration. | Wait for an app flag, completed selector, or content assertion. |
networkidle0 times out |
Polling, analytics, streaming, or another persistent request. | Use domcontentloaded or networkidle2, then wait for a specific readiness signal. |
| Screenshot contains a loading skeleton | The selector matched server markup or a generic container. | Target a completed state such as data-state="complete". |
| Text wraps differently between runs | Fonts were not ready or a font request failed. | Inspect failed font requests, await document.fonts.ready, and use a consistent viewport. |
| Images are absent or page height is short | Lazy loading has not been triggered or image requests failed. | Scroll before capture, wait for image completion, and inspect request failures. |
| Final URL is unexpected | Redirect, locale routing, authentication, or bot handling changed the page. | Log page.url(), inspect the response status, and provide required cookies or headers. |
| Pyppeteer API error | Installed package differs from the referenced source or Chromium is incompatible. | Check installed versions and adjust method signatures to that release. |
| Blank page | Navigation failed, a script crashed, or a bot check blocked rendering. | Log page errors and failed requests, save a diagnostic screenshot, and inspect the response. |
8. Performance, reliability, and cost considerations
- Use the smallest viewport and capture region that meets the requirement. Full-page screenshots require more layout and image work than a clipped element.
- Reuse a browser process for multiple pages, but isolate page state and close pages after each job.
- Set explicit navigation and readiness timeouts. Report the failing condition rather than silently falling back to a fixed delay.
- Use caching for deterministic pages when freshness permits. Avoid relying on network idle for pages with continuous background requests.
- For reproducible output, fix viewport, device scale factor, timezone, locale, authentication state, and user agent.
- Do not treat a successful HTTP response as proof that the screenshot is useful. A bot check, blank app shell, or failed client request can still produce a technically successful navigation.
9. Or skip the browser setup
ScreenshotNeo provides a website screenshot API and MCP server. One GET request returns PNG, JPEG, WebP, or PDF, while its capture flow can accept cookie and consent banners and remove more than 60 known consent platforms, newsletter popups, and chat widgets before the shot. Each step can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the page verdict and billing status with X-Page-Verdict and X-Billed headers.

See the ScreenshotNeo API documentation for all options.
cURL
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,
)
r.raise_for_status()
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}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const fs = await import('node:fs/promises');
await fs.writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));
ScreenshotNeo also supports full-page capture with lazy images loaded, CSS element capture, dark mode, device presets and custom viewports, retina scale, PDF settings, custom CSS and JavaScript, clicks, selector waits, delays, network-idle waits, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, caching with a chosen TTL, signed links, async jobs with signed webhooks, bulk capture for up to 100 URLs per call, a usage API, and an OpenAPI specification. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.
The Free plan includes 1,000 shots per month with no card. Paid plans start at $5 for 3,000 shots; yearly billing gives two months free, and every feature is available on every plan. Create a free ScreenshotNeo account and start with 1,000 screenshots a month at no charge.
10. Short FAQ
Is networkidle0 always the best wait?
No. It is useful only when the page genuinely stops all network activity. Polling, streams, and analytics can make it hang, while a page-specific readiness signal maps more directly to the desired state.
Why does waitForSelector return too early?
The selector may be present in SSR HTML before hydration. Wait for a completed-state attribute, a post-fetch element, or an application-owned flag instead.
Does page.screenshot() wait for fonts?
Do not assume it does. Explicitly await document.fonts.ready when font metrics affect the image.
Can a fixed sleep solve SSR screenshot timing?
It can mask a race temporarily, but it cannot observe whether hydration finished. Use a semantic signal and keep a sleep only as a last fallback for a page with no observable condition.
Should I use setContent or goto?
Use goto for the actual SSR URL when possible. Use setContent when you intentionally provide HTML, and still wait for scripts, data, fonts, and layout to finish.


