# Website screenshots with Node.js

> Take website screenshots from Node.js with the built-in fetch: save images, read page metadata, queue jobs and sign embeddable URLs, with code that runs.

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?

```js
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?

```js
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](https://shotfly.dev/docs/responses).

## How do I capture many pages without waiting?

```js
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](https://shotfly.dev/docs/async-jobs).

## How do I embed a screenshot without exposing my key?

```js
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?

| Status | Codes | What to do |
| --- | --- | --- |
| 400 | `invalid_params`, `url_not_allowed` | Fix the request; `details` lists each problem |
| 401, 403 | `unauthorized`, `forbidden`, `signature_invalid`, `signature_expired`, `domain_blocked` | Check the key, the signature or the target |
| 402 | `quota_exceeded`, `credits_limit` | Upgrade, wait for the next period, or raise `max_credits` |
| 422 | `target_blocked`, `blank_page`, `target_http_error`, `cookie_wall` | Not charged. Change the parameters (`wait_for_selector`, `escalation=auto`) or skip the page |
| 429 | `rate_limited`, `concurrency_limited` | Wait (`Retry-After` when present) and retry |
| 500, 502, 503 | `internal_error`, `render_failed`, `service_unavailable` | Retry with backoff; not charged |
| 504 | `render_timeout` | Raise `timeout`, or queue the capture as an async job |

Every error is JSON: `{ "error": { "code", "message", "request_id", "docs_url" } }`. See [error codes](https://shotfly.dev/docs/errors) for the full list.

---

Source: https://shotfly.dev/docs/guides/nodejs · Last updated 2026-12-01
