Screenshot API for Documentation: The Complete Implementation Guide
Treat docs screenshots as build output. A manifest-driven capture script, a viewport and theme matrix, hash checks to avoid churn, and a reviewable pull request on every refresh.
Documentation screenshots go stale quietly. A button gets renamed, a settings panel moves, the sidebar picks up a new section, and the screenshot in step 3 of your setup guide no longer matches what readers see. Nobody files a bug; readers just lose confidence in the docs.
The fix is to treat documentation screenshots as build output rather than hand-made assets: a list of what to capture, a script that captures it the same way every time, and a pull request that shows exactly which images changed.
This guide walks through that setup with the Screenshotly API. It covers the decisions that make captures repeatable (environment, demo data, viewport and theme), a complete capture script, and a GitHub Actions workflow that opens a reviewable PR. For other CI systems and for pipeline patterns beyond docs, see the CI/CD screenshot automation guide.
What the API does, and what stays in your pipeline
Screenshotly renders a public URL in a headless Chromium browser and returns the image. For documentation work, the parts that matter are:
- Viewport control: top-level
widthandheight, or adevicepreset (desktop,laptop,tablet,mobile). With neither, the viewport is 1920×1080. - Readiness controls:
waitForNetworkIdle,waitForSelectoranddelay. - Framing:
fullPagefor the whole scrollable page,selectorto capture a single element, orclipfor a fixed rectangle. - Appearance:
darkMode(setsprefers-color-scheme: dark),deviceScaleFactorfor 2× images,timezonefor date-dependent UIs. - Clean-up (Growth plan and above):
hideSelectorsto hide known elements, andaiRemovalto detect cookie banners, chat widgets and similar overlays. - Logged-in pages (Basic and above):
cookiesandheaders.
What the API does not do: click, type, or walk through a multi-step flow. The closest thing is the javascript option (Growth and above), which runs a script in the page before capture. If a screenshot depends on an open dropdown or a half-completed wizard, either expose that state through a URL (a query parameter or a dedicated docs route) or capture that one image with a local Playwright script.
Two more constraints shape the setup:
- The target must be publicly reachable. Requests to
localhost, private IP ranges and other internal addresses are rejected. Point the pipeline at a preview deployment or a staging environment, not at a dev server inside the CI runner. - Each image is one API call. A 40-page manifest with three variants is 120 captures per refresh. Check that against your plan's quota and per-minute rate limit on the pricing page.
Step 1: Make the pages deterministic
Most "flaky" documentation screenshots are flaky because the page is. Fix that before writing any capture code:
- Seed a demo workspace. Fixed names, fixed numbers, no real customer data. Screenshots of a live production account leak data and change every time someone uses it.
- Freeze time-dependent text. "Updated 3 minutes ago" changes on every capture. Render absolute dates in the demo account, and pass
timezone(for example"UTC") so dates render the same way regardless of where the browser runs. - Add a readiness marker. Have the app set an attribute such as
data-docs-readyon the main container once data has loaded. ThenwaitForSelector: "[data-docs-ready]"waits for that point rather than guessing with delays. - Remove third-party widgets at the source if you can. A docs-capture flag that disables the chat widget and consent banner on staging is cheaper and more reliable than hiding them after the fact.
Step 2: Write a manifest
Keep the list of captures in a file that writers can edit without touching code. Save it as docs/screenshots/manifest.json:
{
"outputDir": "docs/images/screens",
"sessionCookie": "demo_session",
"hideSelectors": ["#chat-widget", ".consent-banner"],
"variants": [
{ "name": "desktop", "width": 1440, "height": 900, "theme": "light" },
{ "name": "desktop-dark", "width": 1440, "height": 900, "theme": "dark" },
{ "name": "mobile", "width": 390, "height": 844, "theme": "light" }
],
"pages": [
{ "path": "/dashboard", "file": "dashboard", "auth": true, "waitForSelector": "[data-docs-ready]" },
{ "path": "/settings/billing", "file": "billing-panel", "auth": true, "selector": "#billing-panel" },
{ "path": "/pricing", "file": "pricing", "fullPage": true }
]
}
A few notes on the choices:
- Variants define the viewport and theme matrix. Each page is captured once per variant. Drop the dark variant if your docs don't show both themes, since every variant multiplies capture volume.
darkModeonly sets theprefers-color-schememedia feature. If your app stores the theme in a user setting orlocalStorageinstead of following the system preference, set the theme on the demo account instead.selectorcaptures one element. It's the cleanest way to document a single panel. If the element isn't on the page, the API returns a 400 error rather than a wrong image, which is the behavior you want in CI.hideSelectorsrequires the Growth plan. On Free or Basic, leave it out of the manifest and remove widgets at the source (step 1).
Step 3: The capture script
This script has no dependencies beyond Node.js 18 or later (it uses the built-in fetch). It reads the manifest, captures every page in every variant, and only writes a file when the image bytes changed.
// scripts/capture-docs-screenshots.mjs
import { createHash } from 'node:crypto';
import { mkdir, readFile, writeFile } from 'node:fs/promises';
import path from 'node:path';
const API_URL = 'https://screenshotly.app/api/screenshot';
const API_KEY = process.env.SCREENSHOTLY_API_KEY;
const BASE_URL = process.env.DOCS_CAPTURE_BASE_URL; // public preview or staging URL
const SESSION = process.env.DOCS_DEMO_SESSION; // optional; cookies need Basic+
if (!API_KEY || !BASE_URL) {
console.error('Set SCREENSHOTLY_API_KEY and DOCS_CAPTURE_BASE_URL');
process.exit(1);
}
const manifest = JSON.parse(await readFile('docs/screenshots/manifest.json', 'utf8'));
const sha256 = (buffer) => createHash('sha256').update(buffer).digest('hex');
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
function buildRequest(page, variant) {
const body = {
url: new URL(page.path, BASE_URL).toString(),
width: variant.width,
height: variant.height,
format: 'png',
timezone: 'UTC',
waitForNetworkIdle: true,
darkMode: variant.theme === 'dark',
};
if (page.waitForSelector) body.waitForSelector = page.waitForSelector;
if (page.selector) body.selector = page.selector;
if (page.fullPage) body.fullPage = true;
if (manifest.hideSelectors?.length) body.hideSelectors = manifest.hideSelectors; // Growth+
if (page.auth) {
if (!SESSION) throw new Error(`${page.path} needs DOCS_DEMO_SESSION`);
body.cookies = [{
name: manifest.sessionCookie,
value: SESSION,
domain: new URL(BASE_URL).hostname,
secure: true,
httpOnly: true,
}];
}
return body;
}
async function capture(body, attempt = 1) {
const response = await fetch(API_URL, {
method: 'POST',
headers: { 'x-api-key': API_KEY, 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
if (response.status === 429 && attempt < 4) {
const retryAfter = Number(response.headers.get('retry-after')) || 60;
await sleep(retryAfter * 1000);
return capture(body, attempt + 1);
}
if (!response.ok) {
throw new Error(`${response.status} ${await response.text()}`);
}
return Buffer.from(await response.arrayBuffer());
}
async function readExisting(file) {
try {
return await readFile(file);
} catch {
return null;
}
}
await mkdir(manifest.outputDir, { recursive: true });
const report = { changed: [], unchanged: [], failed: [] };
for (const page of manifest.pages) {
for (const variant of manifest.variants) {
const file = path.join(manifest.outputDir, `${page.file}-${variant.name}.png`);
try {
const image = await capture(buildRequest(page, variant));
const existing = await readExisting(file);
if (existing && sha256(existing) === sha256(image)) {
report.unchanged.push(file);
continue;
}
await writeFile(file, image);
report.changed.push(file);
} catch (error) {
report.failed.push({ file, error: error.message });
}
}
}
console.log(JSON.stringify(report, null, 2));
if (report.failed.length > 0) process.exit(1);
Design decisions worth keeping if you adapt it:
- Sequential requests. The loop captures one image at a time, which keeps a small manifest well inside the per-minute limit on every plan. If you add concurrency, cap it below your plan's rate limit and keep the
Retry-Afterhandling. - Failures fail the job, but don't block other pages. Each failure is recorded and the script exits non-zero at the end, so the pipeline shows red while the rest of the images still refresh.
- The API key goes in the
x-api-keyheader.Authorization: Bearer <key>also works. Never put the key in a URL or commit it to the manifest.
Why the hash check matters, and where it stops helping
Writing only changed files keeps refresh PRs small: if nothing in the UI moved, the PR is empty and the workflow below doesn't open one. The check compares raw bytes, though, so it only helps when the page renders identically. Animations caught mid-frame, rotating content, or anything time-based will produce a "changed" image every run. Fix those at the source (step 1) rather than loosening the check.
If you need to tell a meaningful change from a few anti-aliased pixels, you need a pixel-diff step with a threshold. That's the job of visual regression testing, covered in the visual regression testing guide and the automated testing use case.
Step 4: Open a pull request with the new images
Pushing regenerated images straight to main skips the one check that matters: does the new screenshot still match the text around it? A pull request puts each changed image in front of a writer.
This workflow runs on demand and every Monday, then uses peter-evans/create-pull-request to open or update a single refresh PR:
# .github/workflows/docs-screenshots.yml
name: Refresh docs screenshots
on:
workflow_dispatch:
schedule:
- cron: '0 6 * * 1'
permissions:
contents: write
pull-requests: write
jobs:
capture:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: 24
- name: Capture screenshots
env:
SCREENSHOTLY_API_KEY: ${{ secrets.SCREENSHOTLY_API_KEY }}
DOCS_CAPTURE_BASE_URL: ${{ vars.DOCS_CAPTURE_BASE_URL }}
DOCS_DEMO_SESSION: ${{ secrets.DOCS_DEMO_SESSION }}
run: node scripts/capture-docs-screenshots.mjs
- name: Open refresh pull request
uses: peter-evans/create-pull-request@v8
with:
branch: docs/screenshot-refresh
add-paths: docs/images/screens
commit-message: 'docs: refresh product screenshots'
title: 'docs: refresh product screenshots'
body: Automated capture from the docs staging environment. Check each image against the surrounding text before merging.
Setup notes:
- Store
SCREENSHOTLY_API_KEYandDOCS_DEMO_SESSIONas repository secrets, andDOCS_CAPTURE_BASE_URLas a repository variable. - For the action to open PRs with the default
GITHUB_TOKEN, the repository (or organization) setting "Allow GitHub Actions to create and approve pull requests" must be enabled. - If no image changed, the action has nothing to commit and doesn't open a PR.
To refresh screenshots after each staging or preview deploy instead of on a schedule, trigger the same job from your deploy pipeline. The CI/CD guide covers deploy-triggered workflows and GitLab CI.
Step 5: Reference the images from your docs
Docs-as-code frameworks (Docusaurus, MkDocs, Mintlify, Nextra and others) all serve images from the repository, so the generated files can be referenced like any other asset:

The exact path depends on where your framework serves static files, so adjust outputDir in the manifest to match. Stable file names (<page>-<variant>.png) are what make this work: the Markdown never changes, only the image does. Write alt text that describes what the reader should notice, not just the page name.
For theme-aware docs, many frameworks can swap images by color scheme (for example Docusaurus's ThemedImage component). Point the light and dark variants at *-desktop.png and *-desktop-dark.png.
Plan requirements at a glance
| What you need | Request fields | Minimum plan |
|---|---|---|
| Public pages, viewport and theme matrix | width, height, darkMode, timezone, fullPage, selector |
Free |
| Wait for data before capture | waitForNetworkIdle, waitForSelector, delay |
Free |
| Logged-in pages with a demo session | cookies or headers |
Basic |
| Hide known widgets by selector | hideSelectors |
Growth |
| Detect banners and chat widgets automatically | aiRemoval |
Growth |
| Run a script before capture (open a panel, set state) | javascript |
Growth |
Free accounts get 100 captures in total, which is enough to prove the manifest and script. A recurring refresh across several variants needs a paid monthly quota.
Fidelity checks before you roll out
Run the script once and review the output by eye before wiring it into CI:
- Fonts. In the current implementation, web-font requests are skipped for viewport captures (
fullPage: false) to speed up loading, so text may render in a fallback font. Full-page captures load fonts. If brand typography matters in your docs, compare a sample of both and usefullPage: truewhere the difference shows. - Video and live connections. Media and WebSocket requests are not loaded during capture. Pages that show data from a live socket connection need a docs mode that renders seeded data over plain HTTP.
- Overlays. If
aiRemovalis enabled, check that it hid only what you expected. Prefer explicithideSelectorsfor elements you know about. - Readiness. If an image shows a loading skeleton,
waitForSelectorprobably timed out (it captures anyway after 10 seconds). Fix the readiness marker rather than adding longer delays.
When this isn't the right approach
- The UI only exists on a developer machine or behind a VPN with no public preview URL. Run Playwright or Puppeteer locally instead.
- The screenshot depends on a multi-step interaction (drag a card, complete three wizard steps). The API can't click or type; script those few images locally.
- You document a native desktop or mobile app. A web-screenshot API captures web pages only.
For everything else, a manifest, a script, and a weekly PR replace most of the manual work and make every screenshot change reviewable.
Ready to automate your documentation screenshots?
Create a free account → to get 100 free captures for testing the manifest and script. The API reference lists every request field.
See also: Documentation screenshots use case →
About the Author

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
Should I commit generated screenshots to the docs repo?
Usually, yes. Committed images keep the docs build self-contained and make every change visible in a pull request, where a writer can check that the new image still matches the surrounding text. Open a PR rather than pushing straight to main, and only write files whose bytes actually changed so unchanged pages don't create noise. If the images make the repository too large, Git LFS is the usual answer.
How do I capture logged-in pages in CI?
Use a dedicated demo account with seeded, non-sensitive data, and pass its session cookie (or an auth header) in the capture request. Cookies and custom headers require the Basic plan or higher. Keep the session value in a CI secret, scope the account to read-only access where your app allows it, and never use a real customer's or employee's credentials.
What do I do when the screenshot doesn't match the rendered page?
It is usually timing. Set waitForNetworkIdle: true so the capture waits for network activity to settle, and add waitForSelector on an element that only appears once data has loaded. Note that waitForSelector gives up after 10 seconds and captures anyway, so check the image rather than treating a 200 response as proof the page was ready. A short delay (in milliseconds, up to 10,000) is the last resort.
Ready to capture your first screenshot?
Get started with 100 free screenshots. No credit card required.