Skip to content

About

Create Screenshot from URL

Resources

Code of conduct

Contributing

Security policy

Stars

8 stars

Watchers

1 watching

Forks

Latest commit

 

History

34 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

SnapFromWeb

A web service that captures screenshots of web pages using Patchright (Playwright with built-in stealth patches).

Screenshot

Features

  • Single and bulk URL capture (POST /api/screenshot), plus a GET form that returns the image bytes directly for <img src>, curl and no-code tools
  • Stealth mode to avoid detection
  • Capture options per request: png/jpeg/webp, quality, viewport, device scale factor, full page, dark mode, wait strategies and request blocking
  • Hourly caching of previously captured screenshots, with refresh to bypass it
  • Concurrent processing with one shared browser and an isolated context per page (MAX_CONCURRENCY)
  • Screenshots organized by domain, with a browsable gallery that loads small WebP thumbnails instead of full-size PNGs
  • Machine-readable error codes (code), so clients never string-match messages
  • SSRF protection: loopback, private, link-local and metadata addresses are rejected
  • Per-client rate limiting, request size and URL-count caps
  • Automatic cleanup of expired screenshots (opt-in via SCREENSHOT_TTL_HOURS), so a deployment can bound disk usage without losing the gallery timeline
  • Prometheus metrics (/api/metrics), liveness/readiness probes and graceful shutdown that lets in-flight captures finish
  • Sitemap and robots.txt generated from SITE_URL

Things to remember

  • data/i/ is where screenshots are written (SCREENSHOTS_DIR, /data/i in Docker) and it is gitignored. It deliberately lives outside public/: files under public/ are copied into the build output and would shadow the route that serves captures and generates thumbnails
  • public/og.png is the preview image that appears when sharing the homepage link

API Endpoints

POST /api/screenshot

Captures screenshots of one or more web pages.

Request Format

For a single URL:

{
  "urls":["http://localhost:4321/"]
}

For multiple URLs:

{
  "urls": [
    "https://example.com",
    "https://example.org"
  ]
}

{ "url": "https://example.com" } is also accepted. Limits: 20 URLs per request (MAX_URLS_PER_REQUEST), 64 KB body (MAX_BODY_BYTES), 30 requests/minute per client (RATE_LIMIT_MAX / RATE_LIMIT_WINDOW_MS). Only http/https on ports 80/443 are accepted, and private/loopback/metadata targets are rejected (set ALLOW_PRIVATE_HOSTS=true to allow them for local development).

Capture options

{
  "urls": ["https://example.com"],
  "refresh": true,
  "options": {
    "format": "webp",
    "quality": 60,
    "fullPage": true,
    "width": 1440,
    "height": 900,
    "deviceScaleFactor": 2,
    "darkMode": false,
    "waitUntil": "networkidle",
    "waitForSelector": "#app",
    "delayMs": 500,
    "timeout": 30000,
    "blockMedia": false,
    "blockAds": false
  }
}
Option Default Notes
format png png, jpeg or webp; the file extension follows
quality – 1-100, only for jpeg/webp
fullPage false Capture the whole scrollable page
width / height 1920 / 1080 Viewport, 320-3840 / 240-4320
deviceScaleFactor 1 1-3
darkMode false Emulates prefers-color-scheme: dark
waitUntil domcontentloaded load, domcontentloaded, networkidle, commit
waitForSelector – Wait for a selector before capturing (SPAs)
delayMs 500 Extra settle time after load, 0-15000
timeout PAGE_LOAD_TIMEOUT Navigation timeout in ms, 1000-120000
blockMedia false Abort images, media and fonts (much faster)
blockAds false Abort known ad/analytics hosts

Any non-default option renders a fresh capture: the hourly cache only serves default png requests. Invalid options are rejected with 400 and the offending fields listed in data.problems.

Response Format

{
    "success": true,
    "data": {
        "urls": [
            {
                "original": "http://localhost:4321/",
                "screenshot": "http://localhost:4321/i/localhost/ee169604f4ce-20260113-12.png",
                "thumb": "http://localhost:4321/i/localhost/ee169604f4ce-20260113-12.png.thumb.webp",
                "format": "png",
                "cached": false
            }
        ]
    }
}

Per-URL failures keep the same shape with an error and a stable code instead of screenshot:

{
    "original": "https://example.org",
    "error": "HTTP 403: Server returned error status",
    "code": "capture_failed"
}

Status codes

Code Meaning
200 Captured; check data.urls[].error for individual failures
400 No usable URLs, invalid JSON or options, too many URLs, all URLs blocked
413 Body larger than MAX_BODY_BYTES
429 Rate limit exceeded (see Retry-After)
500 Unexpected server error
502 GET form only: the page could not be captured
503 Server is shutting down

Every error body is { "success": false, "code": "...", "error": "...", "data": {} }. code is the contract (invalid_request, body_too_large, rate_limited, no_valid_urls, too_many_urls, url_not_allowed, capture_failed, not_found, service_unavailable, internal_error); the message may be reworded. URL-level rejections reuse the guard's reason (private-address, blocked-host, unsupported-protocol, ...). See ADR 0002.

GET /api/screenshot?url=...

Returns the image itself, so it drops straight into HTML, a shell script or an automation tool:

curl -o shot.webp 'http://localhost:4321/api/screenshot/?url=https://example.com&format=webp&fullPage=1'
<img src="http://localhost:4321/api/screenshot/?url=https://example.com&width=800" alt="">

Query params mirror the option names above, plus url (required) and refresh (1/true). Responses carry X-Screenshot-Cached, X-Screenshot-Format and a one-hour Cache-Control; a capture that fails returns 502 with a JSON error.

GET /api/gallery

Lists captured screenshots, newest first. Params: page, pageSize (max 500), domain (matches the domain or its subdomains). Backed by an in-memory index that is invalidated on every new capture.

GET /api/health and /api/ready

/api/health is the liveness probe: cheap, and never touches the browser — { "success": true, "data": { "status": "ok", "uptime": 12 } }. /api/ready is the readiness probe: it checks that the browser is reachable (installed, or the sidecar answering) and that the screenshot directory is writable, and returns 503 until both pass. Use it for Kubernetes readiness probes / load balancer registration.

GET /api/metrics

Prometheus text format: captures by result, capture duration histogram, in-flight captures, rejections by reason, rate-limit hits and HTTP responses by route. Set METRICS_TOKEN to require Authorization: Bearer <token>, or METRICS_ENABLED=false to disable the endpoint.

GET /i/{domain}/{file}.{png,jpg,webp}

Serves a captured screenshot with a one-hour cache header. Append .thumb.webp to get the gallery thumbnail, generated on demand with sharp.

Configuration

Copy .env.example to .env and adjust. Highlights:

Variable Default Purpose
SITE_URL – Public origin for sitemap, robots.txt and image URLs
HEADLESS_BROWSER true Must stay true in containers
BROWSER_WS_ENDPOINT – Connect to a shared browser host (see below)
MAX_CONCURRENCY 10 Pages captured in parallel
PAGE_LOAD_TIMEOUT / RETRY_LIMIT 30000 / 2 Navigation timeout (0 = none) and extra retries
MAX_URLS_PER_REQUEST / MAX_BODY_BYTES 20 / 65536 Request caps
RATE_LIMIT_MAX / RATE_LIMIT_WINDOW_MS 30 / 60000 Per-client fixed window
ALLOW_PRIVATE_HOSTS false Allow localhost/private targets (dev only)
TRUST_PROXY_HEADERS false Trust x-forwarded-for / x-real-ip
SCREENSHOTS_DIR data/i Where captures are stored (outside public/)
SCREENSHOT_TTL_HOURS / CLEANUP_INTERVAL_MS 0 / 1h Retention of expired captures (0 = keep forever)
THUMBNAIL_WIDTH / THUMBNAIL_QUALITY 480 / 70 Gallery WebP previews (0 disables them)
SHUTDOWN_TIMEOUT_MS 10000 How long in-flight captures may finish on SIGTERM
METRICS_ENABLED / METRICS_TOKEN true / – Prometheus endpoint, optionally token-protected
LOG_CONFIG true Log the effective config (redacted) at startup

Development

  1. Install dependencies:
pnpm install
pnpm exec patchright install chromium
  1. Start the development server:
pnpm dev
  1. Type check, test and verify:
pnpm check          # astro check (types + a11y hints)
pnpm test           # vitest
pnpm test:coverage  # with coverage thresholds
pnpm verify         # check + test + build
pnpm format         # prettier (markdown is excluded on purpose)

A dev container is included: it installs dependencies and Chromium on create, so pnpm dev works immediately.

  1. Build for production:
pnpm build
pnpm start

Docker

See docs/docker.md for how the image is kept small, what it contains and further size options.

docker compose up --build

Prebuilt images are published on tags, so you can pull instead of building:

docker pull ghcr.io/amitind/snapfromweb:latest
docker pull ghcr.io/amitind/snapfromweb-browser:latest   # browser host only

SITE_URL is embedded into the sitemap at image build time, so pass it as a build argument for a real deployment:

docker build --build-arg SITE_URL=https://snapfromweb.example.com -t snapfromweb .

Chromium dominates the image size, so it can also run as a separate browser host and be shared by several replicas or projects — the app image drops from 843 MB to 467 MB:

BROWSER_WS_PATH=$(openssl rand -hex 16) docker compose -f docker-compose.split.yml up --build

Set BROWSER_WS_ENDPOINT to ws://<host>:3000/<BROWSER_WS_PATH> to make the app connect to it instead of launching Chromium itself. The port is a no-authentication browser-control endpoint: keep it private.

Measured benchmark: no throughput cost, a faster first capture, and ~190 MB per extra replica instead of ~600-680 MB.

Security

  • The screenshot endpoint is an SSRF-sensitive surface. URLs are restricted to http/https on ports 80/443, and hosts resolving to private/loopback/ link-local/metadata addresses are rejected. The same check runs on every request the page makes (redirects, iframes, subresources, WebSockets), and service workers are blocked. The check resolves DNS before Chromium does, so a DNS-rebinding attacker can still race it; add an egress firewall if you expose this publicly.
  • There is no authentication. Put it behind your own auth/proxy if it is not meant to be public, and set TRUST_PROXY_HEADERS=true only for a proxy you control.
  • With ALLOW_PRIVATE_HOSTS=true, target internal hosts by IP or by a hostname containing a dot: Chromium HTTPS-upgrades single-label names such as http://service/ and the capture fails. See docs/docker.md.
  • Report vulnerabilities according to SECURITY.md.

License

GNU General Public License v3.0. See LICENSE.

About

Create Screenshot from URL

Resources

Code of conduct

Contributing

Security policy

Stars

8 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages