Tutorial

Node.js Screenshot API: Server-Side Integration Guide

A server-side Node.js guide to the Screenshotly API: a small fetch client with sane retries, a safe Express proxy for browser apps, durable async jobs, and webhook verification.

Asad AliJanuary 25, 202613 min read

Node.js is a natural home for screenshot work: the API call usually lives next to the queue worker, the Express route or the cron script that needs the image. This guide is server-side only. It builds a small client around native fetch, then uses it for a browser-safe proxy route, batch captures, durable async jobs and signed webhooks.

If you are building a React, Vue or plain browser app, read Calling from a browser app safely. The browser talks to your server, and only your server talks to Screenshotly.

Reference docs for the Node.js APIs used here: the built-in Fetch API (based on undici), AbortSignal.timeout(), stream.pipeline, p-limit, BullMQ, and Express. For the full parameter list, see the screenshot API reference.

The API contract in one table

Item Value
Endpoint POST https://screenshotly.app/api/screenshot
Auth x-api-key: YOUR_KEY header (Authorization: Bearer YOUR_KEY also works)
Body JSON, max 64 KB. Unknown fields are rejected with 400.
Success 200 with the image/PDF bytes and a matching Content-Type
Errors JSON { "error": "...", "message": "..." }
Duration Captures can take tens of seconds (page navigation alone may take up to 30 s, plus any delay or wait). Set a client timeout of about 60 s, and use async jobs for slow pages, PDFs and batches.

Plans differ by quota and features. Free includes 100 captures in total, then Basic ($14/month, 2,500 captures), Growth ($59/month, 12,000) and Scale ($199/month, 50,000). Failed captures don't count against quota. See pricing for details.

Setup

You need Node.js 18 or later (the examples use ES modules and top-level await). Express is only needed for the server sections:

mkdir screenshot-app && cd screenshot-app
npm init -y
npm pkg set type=module
npm install express

Put the key in an environment file that is not committed:

# .env
SCREENSHOTLY_API_KEY=your_api_key_here

On Node 20.6+ you can load it with node --env-file=.env app.mjs. On older versions, use dotenv.

A minimal client with sane retries

This module is the only place that knows the key. It retries timeouts, 5xx responses and short 429 waits. It fails fast on everything else.

// screenshotly.mjs
const API_URL = 'https://screenshotly.app/api/screenshot';
const MAX_RETRY_WAIT_SECONDS = 60;

export class ScreenshotlyError extends Error {
  constructor(status, body, retryAfter) {
    super(`Screenshotly ${status}: ${body.message || body.error || 'request failed'}`);
    this.name = 'ScreenshotlyError';
    this.status = status;
    this.body = body;
    this.retryAfter = retryAfter;
  }
}

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function readErrorBody(response) {
  const text = await response.text();
  try {
    return JSON.parse(text);
  } catch {
    return { error: text };
  }
}

export async function capture(options, { retries = 3, timeoutMs = 60_000 } = {}) {
  const apiKey = process.env.SCREENSHOTLY_API_KEY;
  if (!apiKey) throw new Error('SCREENSHOTLY_API_KEY is not set');

  for (let attempt = 0; ; attempt++) {
    let response;
    try {
      response = await fetch(API_URL, {
        method: 'POST',
        headers: { 'x-api-key': apiKey, 'Content-Type': 'application/json' },
        body: JSON.stringify(options),
        signal: AbortSignal.timeout(timeoutMs),
      });
    } catch (error) {
      // Network error or client-side timeout
      if (attempt >= retries) throw error;
      await sleep(2 ** attempt * 1000);
      continue;
    }

    if (response.ok) {
      return {
        buffer: Buffer.from(await response.arrayBuffer()),
        contentType: response.headers.get('content-type'),
      };
    }

    const body = await readErrorBody(response);
    const retryAfter = Number(response.headers.get('retry-after')) || 0;
    // A short Retry-After is a per-minute throughput limit. A long one means
    // the monthly quota is used up, so waiting inside this process is pointless.
    const retryable = response.status === 429
      ? retryAfter <= MAX_RETRY_WAIT_SECONDS
      : response.status >= 500;

    if (!retryable || attempt >= retries) {
      throw new ScreenshotlyError(response.status, body, retryAfter);
    }
    await sleep(response.status === 429 ? retryAfter * 1000 : 2 ** attempt * 1000);
  }
}

Use it from any script:

// capture-example.mjs
import { writeFile } from 'node:fs/promises';
import { capture } from './screenshotly.mjs';

const { buffer, contentType } = await capture({
  url: 'https://example.com',
  device: 'desktop',
  format: 'png',
});

await writeFile('example.png', buffer);
console.log(`Saved ${buffer.length} bytes (${contentType})`);

Why these retry rules:

  • 400, 401, 403 and 413 are never retried. The same request will fail the same way. 403 with "error": "Plan upgrade required" includes a minimumPlan field that names the plan the feature needs.
  • 5xx and network errors are retried with exponential backoff. Failed captures don't consume quota, so a retry after a 500 costs nothing extra.
  • 429 is retried only when Retry-After is short. Throughput limits are per minute: Free 5, Basic 40, Growth 80 and Scale 200 requests. When the monthly quota runs out, Retry-After is the number of seconds until the reset, which can be days.
  • A client-side timeout is not proof of failure. The capture may still finish on the server. If duplicate work matters, use async jobs with an Idempotency-Key.

Streaming large captures to disk

Full-page PNGs and PDFs can be several megabytes. To avoid holding the whole body in memory, stream it:

// stream-to-disk.mjs
import { createWriteStream } from 'node:fs';
import { Readable } from 'node:stream';
import { pipeline } from 'node:stream/promises';

const response = await fetch('https://screenshotly.app/api/screenshot', {
  method: 'POST',
  headers: {
    'x-api-key': process.env.SCREENSHOTLY_API_KEY,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ url: 'https://example.com', fullPage: true, format: 'png' }),
  signal: AbortSignal.timeout(60_000),
});

if (!response.ok) {
  throw new Error(`Capture failed: ${response.status} ${await response.text()}`);
}

await pipeline(Readable.fromWeb(response.body), createWriteStream('full-page.png'));

The same Readable.fromWeb(response.body) stream can be passed as the Body of an S3 upload through @aws-sdk/lib-storage's Upload helper.

Capture options

All options are top-level JSON fields. There is no nested viewport object, and the schema rejects unknown fields. The API reference has the full list. The most useful ones:

Field What it does Plan
device desktop (1920×1080), laptop (1366×768), tablet (768×1024), mobile (375×812) All
width, height Custom viewport, 320–3840 × 240–3840 px All
fullPage Capture the whole scrollable page All
format png, jpeg, webp All
format: "pdf" / "html" PDF document or rendered HTML Basic+
quality 0–100 for JPEG/WebP All
delay, waitForSelector, waitForNetworkIdle Wait before capturing All
selector, clip Capture one element or a region All
darkMode, deviceScaleFactor (1–3), timezone, userAgent Rendering context All
blockAds Block ads All
headers, cookies, stealth, cache, storage, webhook Authenticated pages, caching, delivery Basic+
aiRemoval, mockup, hideSelectors, javascript, scroll, geolocation Cleanup, frames, scripting Growth+
proxyRegion, format: "webm" Regional proxy, short video Scale

Responsive and high-DPI captures

import { capture } from './screenshotly.mjs';

// Preset device viewport
const mobile = await capture({ url: 'https://example.com', device: 'mobile' });

// Exact viewport at 2x pixel density
const retina = await capture({
  url: 'https://example.com',
  width: 1440,
  height: 900,
  deviceScaleFactor: 2,
});

Full page, waiting for content

const page = await capture({
  url: 'https://example.com/pricing',
  fullPage: true,
  waitForSelector: 'main',
  waitForNetworkIdle: true,
  format: 'webp',
  quality: 80,
});

PDF output (Basic plan and above)

const pdf = await capture({ url: 'https://example.com/invoice/123', format: 'pdf' });

PDF output is fixed at A4 with 1 cm margins and prints backgrounds. Page size, orientation, margins, and headers/footers are not configurable, so there is no pdfOptions field. If you need Letter or landscape output, render the PDF yourself.

Cleaner captures and device frames (Growth plan and above)

// Remove cookie banners, chat widgets and newsletter popups, and hide your own promo bar
const clean = await capture({
  url: 'https://example.com',
  aiRemoval: { enabled: true, types: ['cookie-banner', 'chat-widget', 'newsletter'] },
  hideSelectors: ['#promo-bar'],
});

// Wrap the capture in a device frame
const framed = await capture({ url: 'https://example.com', mockup: 'macbook-pro' });

aiRemoval.types accepts cookie-banner, newsletter, chat-widget, social-overlay and ad. mockup is a template ID string: browser-light, browser-dark, browser-minimal, iphone-14, ipad-pro or macbook-pro. On a lower plan, these requests return 403 with "minimumPlan": "growth".

Calling from a browser app safely

The capture endpoint is meant to be called from servers:

  • Your key would be public. Anything in a browser bundle, localStorage or a request header can be read in DevTools.
  • CORS isn't enabled for captures. The endpoint does not send Access-Control-Allow-Origin on POST responses, so a cross-origin fetch() from a web page is blocked by the browser.

Instead, add a narrow route to your own backend. It validates the input, applies your own per-user limit and adds the key server-side. This route accepts only a URL, a device and an image format:

// server.mjs
import express from 'express';
import { rateLimit } from 'express-rate-limit';
import { capture, ScreenshotlyError } from './screenshotly.mjs';

const app = express();
app.use(express.json({ limit: '10kb' }));

const FORMATS = new Set(['png', 'jpeg', 'webp']);
const DEVICES = new Set(['desktop', 'laptop', 'tablet', 'mobile']);

function parseTarget(value) {
  if (typeof value !== 'string' || value.length > 2048) return null;
  try {
    const url = new URL(value);
    return url.protocol === 'https:' || url.protocol === 'http:' ? url.toString() : null;
  } catch {
    return null;
  }
}

// Protect your quota: 10 previews per minute per client.
// Key this by user ID instead of IP if the route sits behind your auth.
const previewLimiter = rateLimit({ windowMs: 60_000, limit: 10 });

app.post('/api/preview', previewLimiter, async (req, res) => {
  const url = parseTarget(req.body?.url);
  const format = req.body?.format ?? 'png';
  const device = req.body?.device ?? 'desktop';
  if (!url || !FORMATS.has(format) || !DEVICES.has(device)) {
    return res.status(400).json({ error: 'Invalid url, format or device' });
  }

  try {
    const { buffer, contentType } = await capture({ url, format, device }, { retries: 1 });
    res.type(contentType).set('Cache-Control', 'private, max-age=300').send(buffer);
  } catch (error) {
    // Don't leak upstream details (or anything key-related) to the browser
    const status = error instanceof ScreenshotlyError && error.status === 400 ? 400 : 502;
    res.status(status).json({ error: 'Capture failed' });
  }
});

app.listen(process.env.PORT || 3000);

Install the limiter with npm install express-rate-limit. Screenshotly also refuses private and internal addresses with 400 Unsafe URL, so the route can't be used to probe your network. Still, put it behind your normal session auth if only signed-in users should create captures.

The browser then calls your route. No key is involved:

// In the browser (React, Vue or plain JS)
let controller;

export async function loadPreview(url, img) {
  controller?.abort(); // cancel a stale capture when the user asks for a new one
  controller = new AbortController();

  const response = await fetch('/api/preview', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ url, device: 'desktop' }),
    signal: controller.signal,
  });
  if (!response.ok) throw new Error(`Preview failed (${response.status})`);

  const objectUrl = URL.createObjectURL(await response.blob());
  img.onload = () => URL.revokeObjectURL(objectUrl);
  img.src = objectUrl;
}

On Vercel, Netlify or Cloudflare, the same logic fits in a serverless function. What matters is that the key is only in the function's environment.

Batch captures with bounded concurrency

Promise.all() over a long list fires every request at once. Use p-limit (npm install p-limit) to cap in-flight captures, and let the client's 429 handling absorb the per-minute limit:

// batch.mjs
import pLimit from 'p-limit';
import { writeFile } from 'node:fs/promises';
import { capture } from './screenshotly.mjs';

const urls = [
  'https://example.com/',
  'https://example.com/pricing',
  'https://example.com/docs',
];

const limit = pLimit(4);

const results = await Promise.allSettled(
  urls.map((url, index) =>
    limit(async () => {
      const { buffer } = await capture({ url, format: 'webp', quality: 80 });
      await writeFile(`capture-${index}.webp`, buffer);
      return url;
    }),
  ),
);

for (const [index, result] of results.entries()) {
  console.log(urls[index], result.status === 'fulfilled' ? 'ok' : result.reason.message);
}

Size the concurrency to your plan. Per-minute throughput is 5 on Free, 40 on Basic, 80 on Growth and 200 on Scale. For more than a few dozen URLs, move to async jobs.

Async jobs for long or durable captures

The synchronous endpoint holds the HTTP connection open while the browser renders. For slow pages, large PDFs or work that must survive a restart, use the jobs API (Basic plan and above). See the async jobs reference.

  • POST /api/jobs takes the same body as /api/screenshot and returns 202 with { id, status, replayed, statusUrl }.
  • Send an Idempotency-Key header. If you retry the submit, you get the original job back (replayed: true) instead of a duplicate.
  • GET /api/jobs/{id} returns QUEUED, RUNNING, SUCCEEDED, FAILED or CANCELED. A succeeded job includes a short-lived resultUrl.
  • Failed jobs are retried by Screenshotly up to three times with exponential backoff.
// jobs.mjs
const BASE_URL = 'https://screenshotly.app';
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

function apiHeaders(extra = {}) {
  return { 'x-api-key': process.env.SCREENSHOTLY_API_KEY, ...extra };
}

export async function submitJob(body, idempotencyKey) {
  const response = await fetch(`${BASE_URL}/api/jobs`, {
    method: 'POST',
    headers: apiHeaders({ 'Content-Type': 'application/json', 'Idempotency-Key': idempotencyKey }),
    body: JSON.stringify(body),
  });
  if (!response.ok) throw new Error(`Submit failed: ${response.status} ${await response.text()}`);
  return response.json(); // { id, status, replayed, statusUrl }
}

export async function waitForJob(id, { intervalMs = 2000, timeoutMs = 300_000 } = {}) {
  const deadline = Date.now() + timeoutMs;
  while (Date.now() < deadline) {
    const response = await fetch(`${BASE_URL}/api/jobs/${id}`, { headers: apiHeaders() });
    if (!response.ok) throw new Error(`Status check failed: ${response.status}`);
    const job = await response.json();
    if (job.status === 'SUCCEEDED') return job;
    if (job.status === 'FAILED' || job.status === 'CANCELED') {
      throw new Error(`Job ${id} ended as ${job.status}: ${job.errorMessage ?? 'no details'}`);
    }
    await sleep(intervalMs);
  }
  throw new Error(`Job ${id} did not finish within ${timeoutMs} ms`);
}

// Usage
const job = await submitJob({ url: 'https://example.com/report', format: 'pdf' }, 'report-2026-11');
const done = await waitForJob(job.id);

// resultUrl is a pre-signed link. Don't send your API key to it.
const file = await fetch(done.resultUrl);
if (!file.ok) throw new Error(`Download failed: ${file.status}`);

If the resultUrl has expired by the time you download, read the job again to get a fresh one. Growth and Scale accounts can also queue up to 20 captures in one call with POST /api/jobs/batch and a body of { "captures": [ ... ] }.

Receiving signed webhooks

Instead of polling, you can add a webhook object to a capture or job request (Basic plan and above):

const job = await submitJob(
  {
    url: 'https://example.com',
    format: 'png',
    webhook: {
      url: 'https://your-app.example.com/webhooks/screenshotly',
      secret: process.env.SCREENSHOTLY_WEBHOOK_SECRET,
    },
  },
  'homepage-capture-2026-11-13',
);

Screenshotly POSTs JSON such as:

{
  "event": "screenshot.completed",
  "timestamp": "2026-11-13T10:15:00.000Z",
  "data": {
    "url": "https://example.com",
    "format": "png",
    "size": 284133,
    "storageUrl": "https://screenshotly.app/api/assets/…",
    "duration": 4210
  }
}

For async jobs, storageUrl is a signed download link to the stored result. A job that fails for good sends screenshot.failed with data.error. When you set secret, every delivery carries X-Screenshotly-Signature: sha256=<hex>: an HMAC-SHA256 of the raw request body keyed with your secret. Deliveries are attempted up to five times, so handle repeats idempotently.

Verify the signature against the raw bytes before parsing:

// webhook.mjs
import crypto from 'node:crypto';
import express from 'express';

const app = express();

// Register this route before any global express.json(), so the body stays raw.
app.post('/webhooks/screenshotly', express.raw({ type: 'application/json' }), (req, res) => {
  const expected =
    'sha256=' +
    crypto.createHmac('sha256', process.env.SCREENSHOTLY_WEBHOOK_SECRET).update(req.body).digest('hex');
  const received = req.get('x-screenshotly-signature') ?? '';

  const valid =
    received.length === expected.length &&
    crypto.timingSafeEqual(Buffer.from(received), Buffer.from(expected));
  if (!valid) return res.status(401).end();

  const event = JSON.parse(req.body.toString('utf8'));
  if (event.event === 'screenshot.completed') {
    // Download event.data.storageUrl promptly; it expires
  } else if (event.event === 'screenshot.failed') {
    console.warn('Capture failed', event.data.url, event.data.error);
  }
  res.sendStatus(204);
});

app.listen(process.env.PORT || 3000);

Running captures from a BullMQ worker

If your app already uses Redis queues, a BullMQ worker is a good fit for captures that are part of your own pipeline. Examples are generating a preview after a post is published, or a nightly archive run. Let BullMQ own the retries and turn off the client's internal ones:

npm install bullmq ioredis
// capture-worker.mjs
import { Queue, Worker } from 'bullmq';
import IORedis from 'ioredis';
import { writeFile } from 'node:fs/promises';
import { capture } from './screenshotly.mjs';

// BullMQ workers need maxRetriesPerRequest: null on their Redis connection
const connection = new IORedis(process.env.REDIS_URL ?? 'redis://127.0.0.1:6379', {
  maxRetriesPerRequest: null,
});

export const captureQueue = new Queue('captures', { connection });

// Producer
await captureQueue.add(
  'capture',
  { url: 'https://example.com', postId: 42 },
  { attempts: 3, backoff: { type: 'exponential', delay: 5000 } },
);

// Consumer: at most 4 in flight and 40 jobs per minute (the Basic plan's limit)
const worker = new Worker(
  'captures',
  async (job) => {
    const { buffer } = await capture({ url: job.data.url, format: 'png' }, { retries: 0 });
    await writeFile(`post-${job.data.postId}.png`, buffer); // or upload to S3
  },
  { connection, concurrency: 4, limiter: { max: 40, duration: 60_000 } },
);

process.on('SIGTERM', async () => {
  await worker.close(); // waits for active jobs to finish
  process.exit(0);
});

If you don't run Redis, Screenshotly's async jobs give you durable retries and idempotency without it.

Caching

You have two layers:

  • Screenshotly cache (Basic plan and above). Send cache: true with cacheTtl (60–86,400 seconds, default 3,600) to return a cached capture for repeated identical requests. This makes repeat responses faster, but each successful response still counts as a capture.
  • Your own storage. For images you'll serve for weeks (link previews, thumbnails), save the bytes to S3/R2 or disk, keyed by a hash of the URL and options, and serve from there. Re-capture on a schedule rather than on every page view.

Error reference

Status Meaning What to do
400 Invalid JSON, unknown or out-of-range field, unsafe target URL Fix the request; don't retry
401 Missing or invalid API key Check the env var; don't retry
403 Feature needs a higher plan (minimumPlan in body), or the account isn't allowed Upgrade or drop the option
413 Request body over 64 KB Trim the javascript, headers or cookies you send
429 Per-minute limit or monthly quota reached Honor a short Retry-After; fail if it's long
500 Capture failed Retry with backoff (failed captures are free)
503 Regional capture proxy unavailable Retry later or drop proxyRegion

Responses also include X-Screenshot-Duration (ms) and X-Screenshot-Size (bytes). When present, X-RateLimit-Limit and X-RateLimit-Remaining on a successful response describe your capture quota. Log them to spot slow pages and see how fast you're using quota.

Deployment checklist

  • SCREENSHOTLY_API_KEY (and SCREENSHOTLY_WEBHOOK_SECRET if you use webhooks) come from your platform's secret store, never the repo or the client bundle.
  • Every fetch has an AbortSignal.timeout().
  • Concurrency is bounded (p-limit, BullMQ concurrency/limiter) to your plan's per-minute limit.
  • Large responses are streamed, not buffered, when you run many captures per process.
  • Slow pages, PDFs, batches and anything that must not be lost use /api/jobs with an Idempotency-Key.
  • Webhook routes verify X-Screenshotly-Signature against the raw body.

A minimal container:

FROM node:22-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
EXPOSE 3000
CMD ["node", "server.mjs"]

Conclusion

A production Node.js integration comes down to five pieces:

  1. One client module that owns the key, the timeout and the retry rules.
  2. A narrow proxy route for browser apps, so the key never leaves the server.
  3. Bounded concurrency sized to your plan.
  4. Async jobs and signed webhooks for slow, large or must-not-lose captures.
  5. Correct options: top-level width/height, string mockup IDs, and A4 PDFs.

Ready to add screenshots to your Node.js app?

Create a free account →. The Free plan includes 100 captures to test the request and response shape.

See the Node.js integration page → for a shorter quick start, or the API reference → for every parameter.

nodejs
tutorial
api
express
automation

About the Author

Asad Ali

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

Should I use node-fetch or native fetch?

On Node 18 and later, use the built-in fetch. It is based on undici and needs no extra dependency. Everything in this guide uses native fetch, AbortSignal.timeout() and Node's own stream utilities.

Can I call the Screenshotly API directly from browser JavaScript?

No. The capture endpoint does not return CORS headers on POST responses, and any key shipped to the browser can be copied from DevTools. Call your own server route instead and keep the API key in a server-side environment variable. This guide includes an Express proxy route for that.

How should I retry a 429 response?

Read the Retry-After header. A per-minute throughput limit returns a short wait you can sleep through. An exhausted monthly quota returns a Retry-After that can be days long, so cap the wait (60 seconds in this guide) and fail the job instead of sleeping.

What should graceful shutdown look like for a capture worker?

On SIGTERM, stop taking new jobs, let in-flight captures finish, then exit. With BullMQ, await worker.close(), which waits for active jobs before resolving.

Ready to capture your first screenshot?

Get started with 100 free screenshots. No credit card required.

Related Articles