How to Capture Screenshots in CI/CD Pipelines
A pipeline guide to screenshot automation: one reusable capture script, GitHub Actions and GitLab CI jobs against preview deployments, secrets handling, rate-limit-aware concurrency and async jobs for larger sets.
Screenshots belong in a pipeline for the same reason tests do: they go stale the moment someone has to remember to update them. A CI job can refresh documentation images, attach screenshots of a preview deployment to a pull request, and produce the "current" images a visual regression check compares against.
This guide wires a screenshot API into GitHub Actions and GitLab CI/CD. It covers one reusable capture script, the workflow patterns built on it, and the operational details that break these jobs in practice: preview URLs, secrets, fork pull requests, rate limits and larger capture sets.
What the pipeline does with the images (commit them, diff them, post them) is your code. Screenshotly loads a public URL in a real browser and returns the image. For the diff step itself, see the visual regression testing guide.
Before you start: three constraints
- The URL must be public. Private and loopback addresses are rejected, so
localhostinside the CI runner won't work. Capture a preview deployment (Vercel, Netlify, Render and similar), a public staging site, or a tunnel. - The API key is a secret. Store it as a repository or project secret and pass it through an environment variable. Never print it or put it in a URL.
- Plan features matter in CI. PNG, JPEG and WebP, full-page captures, fixed viewports and wait options work on every plan. Sending cookies or custom headers (needed for protected previews and logged-in pages) requires Basic. Async jobs require Basic, and batch jobs,
hideSelectorsand AI element removal require Growth. See pricing.
A reusable capture script
Every workflow below calls the same script. It reads a manifest, captures each entry with limited concurrency, honours Retry-After on rate limits, and writes the images plus a results.json summary.
The manifest:
{
"defaults": {
"width": 1280,
"height": 800,
"format": "png",
"timezone": "UTC",
"waitForNetworkIdle": true
},
"captures": [
{ "name": "dashboard", "path": "/dashboard" },
{ "name": "settings", "path": "/settings" },
{ "name": "pricing", "path": "/pricing", "fullPage": true }
]
}
Any field from the screenshot API reference can go in defaults or on a single entry. Use top-level width and height; the API rejects unknown fields.
The script:
// scripts/capture-screenshots.mjs
// Usage: node scripts/capture-screenshots.mjs <manifest.json> <outDir>
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.CAPTURE_BASE_URL;
const CONCURRENCY = Number(process.env.CAPTURE_CONCURRENCY ?? 2);
const [manifestPath, outDir] = process.argv.slice(2);
if (!API_KEY || !BASE_URL || !manifestPath || !outDir) {
console.error('Need SCREENSHOTLY_API_KEY, CAPTURE_BASE_URL, a manifest path and an output dir');
process.exit(1);
}
const manifest = JSON.parse(await readFile(manifestPath, 'utf8'));
const extension = { png: 'png', jpeg: 'jpg', webp: 'webp' };
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// Optional: header that lets the capture browser through a protected preview.
// Sending custom headers requires the Basic plan or higher.
const targetHeaders = process.env.PREVIEW_BYPASS_SECRET
? { 'x-vercel-protection-bypass': process.env.PREVIEW_BYPASS_SECRET }
: undefined;
async function capture(body, attempt = 1) {
const res = await fetch(API_URL, {
method: 'POST',
headers: { 'x-api-key': API_KEY, 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
if (res.ok) return Buffer.from(await res.arrayBuffer()); // binary image body
const error = await res.json().catch(() => ({}));
const message = `${res.status} ${error.error ?? ''}: ${error.message ?? ''}`;
if (res.status === 429 && attempt <= 3) {
const waitSeconds = Number(res.headers.get('retry-after') ?? 60);
if (waitSeconds > 120) throw new Error(`${message} (window too long to wait in CI)`);
await sleep(waitSeconds * 1000);
return capture(body, attempt + 1);
}
if (res.status >= 500 && attempt <= 2) {
await sleep(attempt * 5000);
return capture(body, attempt + 1);
}
throw new Error(message); // 400, 401, 403 and 413 won't succeed on retry
}
await mkdir(outDir, { recursive: true });
const queue = [...manifest.captures];
const results = [];
async function worker() {
while (queue.length > 0) {
const { name, path: pagePath, ...overrides } = queue.shift();
const body = { ...manifest.defaults, ...overrides, url: new URL(pagePath, BASE_URL).toString() };
if (targetHeaders) body.headers = targetHeaders;
const file = `${name}.${extension[body.format ?? 'png']}`;
try {
await writeFile(path.join(outDir, file), await capture(body));
results.push({ name, file, status: 'ok' });
console.log(`ok ${file}`);
} catch (error) {
results.push({ name, file, status: 'failed', error: error.message });
console.error(`failed ${file}: ${error.message}`);
}
}
}
await Promise.all(Array.from({ length: CONCURRENCY }, worker));
await writeFile(path.join(outDir, 'results.json'), JSON.stringify(results, null, 2));
process.exit(results.some((r) => r.status === 'failed') ? 1 : 0);
A few details worth keeping if you adapt it:
- Don't retry 4xx responses other than 429. A 400 means the request body or target URL was rejected, 401 means the key is wrong, and 403 means the requested feature needs a higher plan (the JSON includes
minimumPlan). A 500 can mean the target page failed to load within the 30-second navigation window, so a short retry is reasonable. - Check what you captured.
waitForSelectorwaits up to 10 seconds and then captures anyway, so a successful response does not prove the page reached the state you wanted. Look at the artifacts, or let a diff step catch it. - The bypass header is forwarded to your preview by the capture browser, which means the secret is shared with the capture service. Use a secret scoped to automation that you can rotate. The
x-vercel-protection-bypassheader is Vercel's protection bypass for automation; other hosts use their own header or cookie.
Concurrency and rate limits
Each plan has a per-minute request limit: 5 on Free, 40 on Basic, 80 on Growth and 200 on Scale. Free accounts have 100 captures in total; paid plans have a monthly allowance (2,500, 12,000 and 50,000). Failed captures don't consume quota.
Concurrency is not the same as requests per minute, so start low (CAPTURE_CONCURRENCY=1 on Free, 2–4 on paid plans) and let the 429 handling absorb bursts. If several pipelines share one key, they share the limit too; separate keys per project make usage easier to attribute.
GitHub Actions
Screenshots of a pull request preview
This workflow waits for the PR's preview deployment, captures it, uploads the images as an artifact, and leaves a single comment linking to them:
# .github/workflows/preview-screenshots.yml
name: Preview screenshots
on:
pull_request:
types: [opened, synchronize, reopened]
permissions:
contents: read
pull-requests: write
jobs:
screenshots:
# Secrets are not available to workflows from forked repositories.
if: github.event.pull_request.head.repo.full_name == github.repository
runs-on: ubuntu-latest
env:
CAPTURE_BASE_URL: https://pr-${{ github.event.pull_request.number }}.preview.example.com
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: 22
- name: Wait for the preview to respond
run: |
for i in $(seq 1 30); do
curl -fsS -o /dev/null "$CAPTURE_BASE_URL" && exit 0
sleep 10
done
echo "Preview did not become reachable" && exit 1
- name: Capture
env:
SCREENSHOTLY_API_KEY: ${{ secrets.SCREENSHOTLY_API_KEY }}
run: node scripts/capture-screenshots.mjs screenshots.manifest.json preview-screenshots
- name: Upload screenshots
if: always()
uses: actions/upload-artifact@v7
with:
name: preview-screenshots
path: preview-screenshots/
retention-days: 14
- name: Comment on the pull request
if: always()
uses: actions/github-script@v9
with:
script: |
const fs = require('fs');
const marker = '<!-- preview-screenshots -->';
const results = fs.existsSync('preview-screenshots/results.json')
? JSON.parse(fs.readFileSync('preview-screenshots/results.json', 'utf8'))
: [];
const runUrl = `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`;
const lines = results.map((r) => `- ${r.status === 'ok' ? '✅' : '❌'} ${r.name}${r.error ? `: ${r.error}` : ''}`);
const body = [marker, '### Preview screenshots', ...lines, '', `Images are in the **preview-screenshots** artifact of [this run](${runUrl}).`].join('\n');
const { data: comments } = await github.rest.issues.listComments({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
per_page: 100,
});
const existing = comments.find((c) => c.body?.includes(marker));
if (existing) {
await github.rest.issues.updateComment({ owner: context.repo.owner, repo: context.repo.repo, comment_id: existing.id, body });
} else {
await github.rest.issues.createComment({ owner: context.repo.owner, repo: context.repo.repo, issue_number: context.issue.number, body });
}
Notes:
- The preview URL pattern is a placeholder. Use whatever your host generates. If the preview is protected, the readiness check also needs the bypass header, and the capture needs
PREVIEW_BYPASS_SECRETset from a secret. - The comment links to the artifact instead of embedding images. Artifacts are not served as public image URLs. To show images inline, upload them to storage you control and link those URLs instead.
- One comment, updated in place. The hidden marker stops every push from adding another comment.
If your host reports deployments to GitHub, you can trigger on the deployment instead of polling. The deployment_status event carries the deployed URL:
on:
deployment_status:
jobs:
screenshots:
if: github.event.deployment_status.state == 'success'
runs-on: ubuntu-latest
env:
CAPTURE_BASE_URL: ${{ github.event.deployment_status.environment_url }}
steps:
- uses: actions/checkout@v7
- name: Capture
env:
SCREENSHOTLY_API_KEY: ${{ secrets.SCREENSHOTLY_API_KEY }}
run: node scripts/capture-screenshots.mjs screenshots.manifest.json preview-screenshots
This event is not tied to a pull request, so posting a PR comment from it needs an extra lookup of the PR for the deployed commit.
Refreshing documentation screenshots
For docs images, open a pull request rather than pushing to main. Someone sees the new images before they ship, and branch protection stays intact:
# .github/workflows/refresh-doc-screenshots.yml
name: Refresh documentation screenshots
on:
schedule:
- cron: '0 9 * * 1' # Mondays 09:00 UTC
workflow_dispatch:
permissions:
contents: write
pull-requests: write
jobs:
refresh:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: 22
- name: Capture production pages
env:
SCREENSHOTLY_API_KEY: ${{ secrets.SCREENSHOTLY_API_KEY }}
CAPTURE_BASE_URL: https://app.example.com
run: node scripts/capture-screenshots.mjs docs/screenshots.manifest.json docs/images/screens
- name: Open a pull request with the changes
uses: peter-evans/create-pull-request@v8
with:
branch: automated/doc-screenshots
add-paths: docs/images/screens/*.png
commit-message: 'docs: refresh screenshots'
title: 'docs: refresh screenshots'
body: Automated screenshot refresh. Review the image diffs before merging.
The action only opens a pull request when files changed. Your repository settings must allow GitHub Actions to create pull requests. Byte-level changes in a PNG don't always mean a visible change; if you get noisy PRs, add a pixel-diff step that only keeps images that differ beyond a tolerance. The documentation screenshot automation guide covers the docs side in more depth.
GitLab CI
The same script runs in a merge request pipeline. Add SCREENSHOTLY_API_KEY as a masked CI/CD variable. If you also mark it protected, it is only available to pipelines on protected branches and tags, so merge request pipelines from feature branches won't see it.
# .gitlab-ci.yml
stages:
- deploy
- screenshots
deploy-review:
stage: deploy
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
script:
- echo "Deploy the review app here"
environment:
name: review/$CI_MERGE_REQUEST_IID
url: https://mr-$CI_MERGE_REQUEST_IID.preview.example.com
capture-preview:
stage: screenshots
image: node:22
needs: [deploy-review]
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
variables:
CAPTURE_BASE_URL: https://mr-$CI_MERGE_REQUEST_IID.preview.example.com
CAPTURE_CONCURRENCY: "2"
script:
- node scripts/capture-screenshots.mjs screenshots.manifest.json preview-screenshots
artifacts:
when: always
expire_in: 14 days
paths:
- preview-screenshots/
The script has no npm dependencies, so the job doesn't need npm ci. Artifacts appear on the merge request's pipeline page. Pushing refreshed images back to the repository from GitLab needs a project access token with write access; opening a merge request for review is safer than pushing to the default branch.
Larger capture sets: async jobs and batches
Synchronous captures hold a request open while the browser works. For dozens of pages, queue jobs instead and collect the results:
POST /api/jobs(Basic plan or higher) takes the same body as/api/screenshotand returns202with{ id, status, statusUrl }.GET /api/jobs/{id}returnsstatus(QUEUED,RUNNING,SUCCEEDED,FAILEDorCANCELED) and, once the job succeeds, a signedresultUrlthat expires after 15 minutes, so download it straight away.- An
Idempotency-Keyheader makes a retried submission return the existing job instead of creating a duplicate.
const API = 'https://screenshotly.app/api';
const headers = { 'x-api-key': process.env.SCREENSHOTLY_API_KEY, 'Content-Type': 'application/json' };
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
export async function captureViaJob(body, name) {
// One key per capture per workflow attempt, so a re-run starts fresh jobs.
const key = `${process.env.GITHUB_RUN_ID}-${process.env.GITHUB_RUN_ATTEMPT}-${name}`;
const submit = await fetch(`${API}/jobs`, { method: 'POST', headers: { ...headers, 'Idempotency-Key': key }, body: JSON.stringify(body) });
if (!submit.ok) throw new Error(`${submit.status} ${(await submit.text()).slice(0, 200)}`);
const { id } = await submit.json();
for (let i = 0; i < 60; i++) {
await sleep(5000);
const job = await (await fetch(`${API}/jobs/${id}`, { headers })).json();
if (job.status === 'SUCCEEDED') return Buffer.from(await (await fetch(job.resultUrl)).arrayBuffer());
if (job.status === 'FAILED' || job.status === 'CANCELED') throw new Error(`${id} ${job.status}: ${job.errorMessage ?? ''}`);
}
throw new Error(`${id} still not finished after 5 minutes`);
}
On Growth and Scale, POST /api/jobs/batch accepts { "captures": [ ... ] } with up to 20 capture bodies and returns one job per capture. The whole batch is rejected if it is larger than your remaining allowance. See the async jobs reference for the full contract.
Secrets and key hygiene
- Store
SCREENSHOTLY_API_KEYas a secret and reference it as${{ secrets.SCREENSHOTLY_API_KEY }}(GitHub) or a masked variable (GitLab). Pass it in thex-api-keyheader, never a query string. - Use a separate key per repository or pipeline so you can revoke one without breaking the others.
- To check that a key is still valid without spending a capture, call an authenticated read-only endpoint such as the job list:
status=$(curl -s -o /dev/null -w "%{http_code}" \
-H "x-api-key: $SCREENSHOTLY_API_KEY" \
https://screenshotly.app/api/jobs)
if [ "$status" != "200" ]; then
echo "::error::Screenshotly API key rejected (HTTP $status)"
exit 1
fi
The ::error:: prefix is a GitHub Actions annotation; in GitLab, a plain echo is enough.
Where the images go next
| Goal | Pipeline step after capture |
|---|---|
| Documentation stays current | Open a PR with changed images (above) |
| Reviewers see the UI change | Upload artifact and comment on the PR (above) |
| Catch unintended UI changes | Diff against approved baselines; see the visual regression testing guide |
| Notify another system when a capture is ready | Webhook delivery (webhook.url, Basic+); see the webhooks guide |
For how capture fits alongside browser test runners and diff tools in a test strategy, see the automated testing use case.
Summary
- Capture public preview or staging URLs;
localhostis rejected. - Keep one capture script and one manifest, and call it from every workflow.
- Respect per-minute limits with low concurrency and
Retry-Afterhandling; don't retry 4xx errors. - Upload images as artifacts, comment once per PR, and open PRs instead of pushing image changes to
main. - Use async jobs (Basic+) or batches (Growth+) when the capture set grows.
- Diffing and pass/fail decisions are your step, not the capture API's.
Ready to add screenshots to your pipeline?
Create a free account to get 100 captures for testing the request shape, then check the quickstart and the plans for the features your workflow needs.
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
Can I capture screenshots in GitHub Actions without installing Chrome?
Yes. The capture runs in Screenshotly's browser, so the job only needs to send an HTTP request and save the returned image. Store the API key as a repository secret and upload the images as a workflow artifact. Capture time depends on the target page, so measure it on your own URLs.
Can the pipeline capture localhost or a private staging server?
No. Screenshotly rejects private and loopback addresses, so the URL has to be publicly reachable: a preview deployment, a public staging environment or a tunnel. If the preview is protected, pass the access header or cookie in the request (Basic plan or higher).
How do I fail a pull request on a visual change?
Screenshotly only captures. Compare the new images against approved baselines in your own step, for example with pixelmatch, and exit non-zero when the difference is above the tolerance you set. The visual regression testing guide has a complete compare script.
Why does my workflow fail on pull requests from forks?
GitHub does not pass repository secrets to workflows triggered by pull requests from forks, and the GITHUB_TOKEN is read-only there. Skip the capture job for fork PRs, or run it after a maintainer reviews the change.
Ready to capture your first screenshot?
Get started with 100 free screenshots. No credit card required.