Declarative Screenshots
On this page
Declarative screenshots for Astro documentation sites. You define which pages to capture
and which elements to highlight directly in your MDX. A separate CLI generates the PNG files
using Playwright and Docker. Your docs build just renders the committed PNGs as <img> tags.
Two packages
astro-better-declarative-screenshots — Astro components for your docs site.
Reads committed PNGs at build time and renders them as <img> tags. No Playwright, no Docker,
no heavy dependencies.
astro-better-generate-screenshots — CLI that generates the PNGs. Starts Docker,
captures pages with Playwright WebKit, injects highlights, and writes PNGs to your output
directory.
The split keeps Playwright’s ~250 MB browser binaries out of your docs build. Regular builds stay fast; generation runs on a schedule, on demand, or only when content changes.
Installation
Install the Astro components
In your Astro project:
$ npm install astro-better-declarative-screenshots
Install the screenshot generator
The generator requires Node.js 20.9 or later. Install the generator in a screenshots/ subdirectory, which keeps Playwright out of your main node_modules:
$ mkdir screenshots && cd screenshots
$ npm init -y
$ npm install astro-better-generate-screenshots
If you set browserContainer, the browser runs in Docker and you can skip this. Otherwise, install WebKit locally:
$ npx playwright install --with-deps webkit
Add a convenience script
In your root package.json:
{
"scripts": {
"screenshots": "screenshots/node_modules/.bin/take-screenshots",
"check-screenshots": "screenshots/node_modules/.bin/check-screenshots"
}
}
Docker setup
The generator starts a Docker container of your site before capturing pages.
For bss-docs — a static Astro site — the simplest approach is to build first,
then serve the dist/ directory with a lightweight static file server.
services:
bss-docs:
image: node:20-alpine
working_dir: /app
volumes:
- ../dist:/app/dist:ro
command: npx --yes serve dist -l 4000 --no-clipboard
ports:
- "4000:4000"
healthcheck:
test: ["CMD", "wget", "-qO-", "http://localhost:4000/docs"]
interval: 3s
timeout: 5s
retries: 30
Add the build step to the screenshots script so one command does everything:
{
"scripts": {
"screenshots": "npm run build && screenshots/node_modules/.bin/take-screenshots"
}
}
Then just:
$ npm run screenshots
Configuration
Create screenshot.config.mjs at the project root:
export default {
baseUrl: 'http://localhost:4000',
outputDir: 'public/img/screenshots',
// render in a pinned Linux container so every OS produces identical images
browserContainer: true,
window: { width: 1200, height: 800 },
// capture light and dark images; the site sets html.dark whenever it shows dark
colorScheme: 'both',
darkMode: 'class',
chrome: {
style: 'macos',
renderIn: 'css',
showUrl: true,
theme: 'light',
// replace localhost:4000 with the real domain in the URL bar
baseUrl: 'https://better-static-sites.github.io',
},
docker: {
compose: 'screenshots/docker-compose.yml',
service: 'bss-docs',
healthcheck: {
url: 'http://localhost:4000/docs',
timeout: 60000,
interval: 3000,
},
},
};
The chrome.baseUrl substitution makes the URL bar show better-static-sites.github.io/docs/...
instead of localhost:4000/docs/... in the rendered screenshot. To show the same text for
every screenshot, such as a host name, set chrome.url instead.
Address bar text
By default, the address bar shows the screenshot’s url as written, after the chrome.baseUrl substitution. Four chrome settings trim the text:
| Setting | Default | Effect |
|---|---|---|
showHost | true | false shows only the path. The host leaves full URLs, and chrome.baseUrl no longer applies to the address bar. |
showQuery | true | false drops the query string. |
showHash | true | false drops the hash. |
shortenIds | false | true shortens each UUID to the first 8 characters, followed by .... |
With showHost, showQuery, and shortenIds set, http://localhost:9011/admin/tenant/edit/30663132-6464-6665-3032-326466613934?tenantId=1#email shows as /admin/tenant/edit/30663132...#email. Set showHash: false as well to show /admin/tenant/edit/30663132.... Text longer than 72 characters ends in .... chrome.url replaces the text on every screenshot, so these settings don’t apply when chrome.url is set.
A screenshot can override each of the four settings with a prop of the same name, for example in a tutorial where the reader needs the full query string:
<Screenshot url="/oauth2/authorize?client_id=abc&response_type=code" showQuery />
Consistent rendering across operating systems
Browsers draw text with the host OS’s font engine and installed fonts, so the same page captured on macOS and on a Linux CI runner differs by a few percent of pixels. That’s enough for drift checks to flag every screenshot as changed.
Set browserContainer: true to capture in a pinned Linux container instead of a local browser:
- The generator builds a small image from
mcr.microsoft.com/playwrightat the exact version of your installedplaywrightpackage, then caches it. It rebuilds only when that version or the bundled image files change. - It starts the container on a random local port, connects with Playwright’s
exposeNetwork, and removes the container when the run ends. Pages atlocalhostURLs, like your Docker services, load through the host, so no extra networking is needed. - The image installs Inter for system UI fonts (
-apple-system,system-ui, Helvetica, Segoe UI) and DejaVu Sans Mono for Menlo and other monospace fonts, with grayscale antialiasing. The result looks close to macOS rendering. - macOS, Linux, Windows, arm64, and x86-64 hosts all produce the same pixels. Docker is the only requirement, and no local browser install is needed.
To use your own image, pass it instead. It must be based on mcr.microsoft.com/playwright at the same version as your playwright package:
export default {
browserContainer: { image: 'my-org/screenshot-browser:1.63.0' },
};
Turning this on changes how text renders, so regenerate and commit all screenshots once afterward to set a new baseline.
Declaring screenshots in MDX
Import the components at the top of any .mdx file:
import Screenshot from 'astro-better-declarative-screenshots/Screenshot.astro';
import Highlight from 'astro-better-declarative-screenshots/Highlight.astro';
Basic screenshot
Place the Screenshot component where the image should appear:
<Screenshot
url="/content/details"
alt="The Details component documentation page."
/>


Full-page capture
Capture the full height of a page with fullPage:
<Screenshot
url="/build-tools/code-blocks"
alt="The code blocks documentation page showing all meta string features."
fullPage={true}
/>


A full-page capture grows the window until nothing on the page is scrolled out of view, including scrolling elements such as a sidebar. Growing the window keeps sticky headers and sidebars in place. The capture stops at maxFullPage.height, which is 8000 px by default. To stop a long page sooner, add maxHeight={1400} or another height to the screenshot. When the first highlight falls below maxHeight, the capture scrolls to the highlight.
To make every screenshot full-page, set fullPage: true in screenshot.config.mjs. A screenshot that sets height or fullPage={false} then keeps a fixed window height.
Light and dark screenshots
Set colorScheme: 'both' in screenshot.config.mjs to capture every screenshot in light and dark, or set colorScheme="both" on one screenshot. The generator writes name.png and name.dark.png, and the Screenshot component renders both. CSS shows the image that matches the site’s theme, and the hidden image doesn’t download. Every screenshot on this page switches when you change the theme.
Set darkMode so the component reads your site’s theme the same way the site does:
'media'(default) followsprefers-color-scheme, unless<html>hasdata-theme="light"orclass="light".'class'reads only<html>: the page is dark when<html>hasclass="dark"ordata-theme="dark". Use'class'when your theme script adds.darkfor the system setting too, as Tailwind’s class strategy does. This site uses'class'.
The generator switches the scheme with Playwright’s color scheme emulation, so the page sees prefers-color-scheme: dark. If your app stores the theme somewhere else, such as a cookie, set it in beforeScreenshot, which receives colorScheme. Until a dark image exists, the light image shows in both themes.
Highlight an element
Nest a Highlight component inside Screenshot to call out a specific element.
The highlight is injected onto the live page before the screenshot is taken.
<Screenshot
url="/content/tables"
alt="The tables page with the TableGrid live example highlighted."
>
<Highlight
selector=".abt-grid-table"
label="TableGrid"
color="#6366f1"
/>
</Screenshot>


Arrow style
Use style="arrow" to point at an element instead of boxing it:
<Screenshot
url="/build-tools/code-blocks"
alt="The code blocks page with the diff example called out."
>
<Highlight
selector=".code-figure"
style="arrow"
label="title tab"
color="#e74c3c"
/>
</Screenshot>


Multiple highlights
Chain multiple <Highlight> children to annotate several elements at once:
<Screenshot
url="/content/tables"
alt="The tables page with both complex TableGrid examples annotated."
fullPage={true}
>
<Highlight selector=".abt-grid-table:first-of-type" label="basic" />
<Highlight selector=".abt-grid-table:last-of-type" label="rowspan" color="#059669" />
</Screenshot>


Generating screenshots
From the project root:
$ npm run screenshots
The script builds the site first, then starts Docker, waits for the health check to pass,
captures every <Screenshot> found in your source, and writes PNGs to outputDir.
To regenerate only screenshots whose name or URL contains a given string:
$ npm run screenshots -- --filter tables
Commit the generated PNGs alongside your source. Subsequent docs builds read them from disk — no Playwright or Docker involved.
Run Shards in Parallel
A run captures one screenshot at a time. To use more of your machine, split the run into shards that run in parallel:
$ npm run screenshots -- --shards 4
The CLI starts one copy of itself for each shard. Each shard takes whole source files, so the screenshots on one page run in one shard, in the same order as a run without shards. The CLI gives the largest files out first, each to the shard with the fewest captures so far.
Each shard starts its own browser container and its own Docker Compose project. The project name is the compose file’s folder plus -shard-1, -shard-2, and so on. Every output line starts with the shard, such as [shard 2/4]. The command exits with code 1 when any shard fails.
Two shards can’t publish the same host port. Before the config loads, the CLI sets SCREENSHOT_SHARD_INDEX to the shard’s zero-based index and SCREENSHOT_SHARD_COUNT to the number of shards. Use the index to give each shard its own port:
const port = 9011 + 10 * Number(process.env.SCREENSHOT_SHARD_INDEX ?? 0);
export default {
baseUrl: `http://localhost:${port}`,
docker: {
compose: 'screenshots/docker-compose.yml',
healthcheck: { url: `http://localhost:${port}/api/status` },
env: { APP_PORT: String(port) },
},
};
Then read the port in the compose file:
services:
app:
ports:
- "${APP_PORT:-9011}:9011"
When a Screenshot url includes a host and port, such as http://localhost:9012/setup, every shard opens that port. Use a path such as /setup instead, so the URL resolves against the shard’s baseUrl.
To run one shard on its own, such as one CI job for each shard, pass --shard <index>/<count>. The index starts at 1:
$ npm run screenshots -- --shard 2/4
Four shards start four copies of every service in your compose file. Check that Docker has enough memory for every shard before you raise the count.
CI: checking for drift
check-screenshots recaptures all screenshots and diffs them against the committed
references. Use it in a scheduled CI job to catch visual regressions.
$ npm run check-screenshots -- --threshold 0.002 --diff-dir .screenshot-diffs
--threshold— fraction of pixels that may differ before failure (default0.001)--diff-dir— where to write diff images (default.screenshot-diffs)--fail-on-missing— exit non-zero if any reference PNG is missing--filter— check only screenshots whose name or URL matches this string
Automated weekly refresh
The recommended pattern: a scheduled GitHub Action builds the site, runs the generator, and opens a PR if any PNGs changed. This separates “something drifted” from “the drift was intentional.”
name: Update screenshots
on:
schedule:
- cron: '0 8 * * 1' # every Monday
workflow_dispatch:
permissions:
contents: write
pull-requests: write
jobs:
update:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: .nvmrc
cache: npm
cache-dependency-path: |
package-lock.json
screenshots/package-lock.json
- name: Install site modules
run: npm ci
- name: Build site
run: npm run build
- name: Install screenshots CLI
run: npm ci
working-directory: ./screenshots
# no Playwright browser install step: browserContainer renders in Docker
- name: Delete cached screenshots
run: rm -f public/img/screenshots/*.png
- name: Generate screenshots
run: npm run screenshots
- name: Check for changes and open PR
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
git add public/img/screenshots/
if git diff --cached --quiet; then
echo "All screenshots match -- no PR needed."
else
BRANCH="screenshots/auto-update-$(date +%Y-%m-%d)"
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git checkout -b "$BRANCH"
git commit -m "chore: update screenshots $(date +%Y-%m-%d)"
git push origin "$BRANCH"
gh pr create --title "chore: update screenshots $(date +%Y-%m-%d)" \
--body "Weekly automated screenshot refresh. Review the diff before merging." \
--label "screenshots" --base main
fi
Screenshot props
| Prop | Type | Default | Description |
|---|---|---|---|
url | string | required | URL path to capture (relative to baseUrl, or a full URL) |
alt | string | derived from filename | Alt text for the <img> |
id | string | auto-derived | Override the output filename (without .png) |
width | number | window.width from config | Viewport width for this screenshot |
height | number | window.height from config | Viewport height for this screenshot. Turns off a config-wide fullPage default |
fullPage | boolean | fullPage from config | Grow the capture to the full page height, up to maxHeight |
maxHeight | number | maxFullPage.height from config | Tallest a full-page capture grows |
colorScheme | 'light' | 'dark' | 'both' | colorScheme from config | Color scheme to capture; both adds a dark image |
crop | string | — | CSS selector for the part of the page to crop the image to; covers every matching element and overrides fullPage |
cropPadding | number | 16 | Pixels of space kept around the cropped area |
chrome | boolean | true, false when cropped | Draw the window chrome around the image |
showHost | boolean | chrome.showHost from config | Show the host in the address bar |
showQuery | boolean | chrome.showQuery from config | Show the query string in the address bar |
showHash | boolean | chrome.showHash from config | Show the hash in the address bar |
shortenIds | boolean | chrome.shortenIds from config | Shorten UUIDs in the address bar |
Filenames are derived from the URL path and highlight selectors. /docs/ui/tables with a
.abt-grid-table highlight becomes docs-ui-tables-abt-grid-table.png. Pass an explicit
id when the same URL appears more than once on a page.
Highlight props
| Prop | Type | Default | Description |
|---|---|---|---|
selector | string | required | CSS selector for the element to highlight |
style | 'border' | 'arrow' | 'both' | 'border' | Visual treatment |
color | string | '#f60' | Highlight color (any CSS color) |
label | string | '' | Short text badge drawn above the element |
borderWidth | number | 3 | Border thickness in pixels (border style only) |
Elements with zero dimensions (hidden inputs, display:none elements) are skipped automatically.
Window chrome styles
The chrome.style option in screenshot.config.mjs controls the window frame rendered around each screenshot. All styles support theme: 'light' and theme: 'dark'.
| Style | Description |
|---|---|
macos | macOS Safari toolbar with traffic lights. The default |
linux | GNOME-style titlebar |
windows | Windows 11 flat titlebar with rectangular controls |
none | No chrome; image rendered directly |
On screens 640 px wide or narrower, every style shows a compact address bar in place of the full window frame, which leaves more room for the image. The compact bar drops the window controls, and drops the whole bar when showUrl is false. Only renderIn: 'css' adapts this way, because renderIn: 'png' draws the frame into the image.
renderIn: 'css' renders the window chrome as HTML/CSS in the Screenshot component — no
image processing needed and the chrome adapts to dark mode automatically. With colorScheme: 'both',
renderIn: 'png' draws each image’s frame in that image’s scheme. renderIn: 'png'
composites the chrome into the PNG at capture time (legacy). Use css for new projects.
Strict mode
By default, <Screenshot> renders a placeholder when the PNG is missing.
Set strict: true in screenshot.config.mjs or SCREENSHOTS_STRICT=true in your
environment to throw at build time instead. This is useful in CI to catch references
to PNGs that were never generated.