Shotfly

API reference

Website screenshots with Node.js

Node.js 18 and later have fetch built in, so calling Shotfly needs no SDK: send the page URL and your secret key to GET /v1/screenshot and write the response body to a file. The examples read the key from SHOTFLY_SECRET_KEY. Create a key in the dashboard and keep it on the server.

How do I take a screenshot in Node.js?

screenshot.mjs
import { writeFile } from 'node:fs/promises'

const API = 'https://api.shotfly.dev'
const RETRYABLE = [429, 500, 502, 503] // rate limits and server errors, never charged

/** One screenshot. Waits and retries on RETRYABLE statuses; other errors are final. */
export async function screenshot(params, { retries = 3 } = {}) {
  for (let attempt = 0; ; attempt++) {
    const res = await fetch(`${API}/v1/screenshot?${new URLSearchParams(params)}`, {
      headers: { Authorization: `Bearer ${process.env.SHOTFLY_SECRET_KEY}` },
      signal: AbortSignal.timeout(90_000),
    })
    if (res.ok) {
      return {
        bytes: Buffer.from(await res.arrayBuffer()),
        contentType: res.headers.get('content-type'),
        credits: Number(res.headers.get('x-credits-charged')),
      }
    }
    if (RETRYABLE.includes(res.status) && attempt < retries) {
      await res.body?.cancel()
      const seconds = Number(res.headers.get('retry-after')) || 2 ** attempt
      await new Promise((done) => setTimeout(done, seconds * 1000))
      continue
    }
    // A proxy in front of the API can answer with HTML, so don't assume JSON.
    const body = await res.json().catch(() => null)
    const code = body?.error?.code ?? `http_${res.status}`
    throw Object.assign(new Error(`${code}: ${body?.error?.message ?? res.statusText}`), { code })
  }
}

const shot = await screenshot({ url: 'https://example.com', full_page: 'true', format: 'webp' })
await writeFile('example.webp', shot.bytes)
console.log(`saved example.webp, ${shot.credits} credit`)

Run it with node screenshot.mjs. Rate limits and errors on Shotfly's side are worth retrying, and the helper does that. Other errors are final: a bot challenge (target_blocked), a blank page (blank_page) or a bad parameter (invalid_params) will fail again. Failed requests cost nothing.

How do I get the page title and Open Graph image?

metadata.mjs
const params = new URLSearchParams({ url: 'https://example.com', response_type: 'json' })
const res = await fetch(`https://api.shotfly.dev/v1/screenshot?${params}`, {
  headers: { Authorization: `Bearer ${process.env.SHOTFLY_SECRET_KEY}` },
})
const body = await res.json()
if (!res.ok) throw new Error(`${body.error.code}: ${body.error.message}`)
console.log(body.metadata?.title, body.metadata?.image)
console.log('image, valid until', body.url_expires_at, body.url)

With response_type=json the response is JSON: a link to the image (valid for one hour), its size, what the request cost and the page metadata. See responses.

How do I capture many pages without waiting?

jobs.mjs
const API = 'https://api.shotfly.dev'
const headers = {
  Authorization: `Bearer ${process.env.SHOTFLY_SECRET_KEY}`,
  'content-type': 'application/json',
}

const submitted = await fetch(`${API}/v1/jobs`, {
  method: 'POST',
  headers,
  body: JSON.stringify({ url: 'https://example.com', full_page: true }),
})
if (submitted.status !== 202) throw new Error((await submitted.json()).error.message)
const { job_id } = await submitted.json()

// Poll until it finishes. Or pass webhook_url when submitting and skip this loop.
for (;;) {
  const job = await (await fetch(`${API}/v1/jobs/${job_id}`, { headers })).json()
  if (job.status === 'completed') {
    console.log('image:', job.url)
    break
  }
  if (job.status === 'failed') throw new Error(`${job.error.code}: ${job.error.message}`)
  await new Promise((done) => setTimeout(done, 2000))
}

Results are kept for 24 hours. With webhook_url, Shotfly posts the result to you instead; check the signature as shown in async jobs and webhooks.

How do I embed a screenshot without exposing my key?

signed-url.mjs
import { createHmac } from 'node:crypto'

const rfc3986 = (s) =>
  encodeURIComponent(s).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`)

/** A URL for <img src> or og:image: it carries the public key and a signature, never the secret. */
export function signedScreenshotUrl(params, { publicKey, secret, expiresInSeconds }) {
  const all = { ...params, access_key: publicKey }
  if (expiresInSeconds) all.expires = String(Math.floor(Date.now() / 1000) + expiresInSeconds)
  const canonical = Object.entries(all)
    .map(([k, v]) => [k, String(v)])
    .sort(([ak, av], [bk, bv]) => (ak === bk ? (av < bv ? -1 : av > bv ? 1 : 0) : ak < bk ? -1 : 1))
    .map(([k, v]) => `${rfc3986(k)}=${rfc3986(v)}`)
    .join('&')
  const signature = createHmac('sha256', secret).update(canonical).digest('hex')
  return `https://api.shotfly.dev/v1/screenshot?${new URLSearchParams({ ...all, signature })}`
}

console.log(
  signedScreenshotUrl(
    { url: 'https://example.com', viewport_width: 1200, viewport_height: 630 },
    {
      publicKey: process.env.SHOTFLY_PUBLIC_KEY,
      secret: process.env.SHOTFLY_SECRET_KEY,
      expiresInSeconds: 86_400,
    },
  ),
)

The URL carries your public key (pk_…) and a signature; the secret never leaves your server. Changing any parameter breaks the signature, and expires limits how long the URL works.

Which errors should I handle?

StatusCodesWhat to do
400invalid_params, url_not_allowedFix the request; details lists each problem
401, 403unauthorized, forbidden, signature_invalid, signature_expired, domain_blockedCheck the key, the signature or the target
402quota_exceeded, credits_limitUpgrade, wait for the next period, or raise max_credits
422target_blocked, blank_page, target_http_error, cookie_wallNot charged. Change the parameters (wait_for_selector, escalation=auto) or skip the page
429rate_limited, concurrency_limitedWait (Retry-After when present) and retry
500, 502, 503internal_error, render_failed, service_unavailableRetry with backoff; not charged
504render_timeoutRaise timeout, or queue the capture as an async job

Every error is JSON: { "error": { "code", "message", "request_id", "docs_url" } }. See error codes for the full list.

Last updated 2026-12-01. Markdown version: /docs/guides/nodejs.md