How to take a website screenshot in Node.js
By URLBooth · Published · Last updated
To take a website screenshot in Node.js, call the URLBooth endpoint POST /v1/screenshots with the built-in fetch, a JSON body such as { url: "https://example.com" } and an Authorization: Bearer key. The response body is the image, so you read it as bytes and write it with fs/promises. No packages are needed on Node 18 or later.
What is the minimal Node.js example with fetch?
Node 18 and later ship fetch and AbortSignal.timeout, so a capture needs no dependencies. Save this as screenshot.mjs (top-level await needs ES modules), set URLBOOTH_API_KEY and run it with node screenshot.mjs. The API requires the Pro plan, and you create keys in the dashboard under API keys.
import { writeFile } from "node:fs/promises";const response = await fetch("https://urlbooth.com/v1/screenshots", {method: "POST",headers: {Authorization: `Bearer ${process.env.URLBOOTH_API_KEY}`,"Content-Type": "application/json",},body: JSON.stringify({ url: "https://example.com" }),signal: AbortSignal.timeout(60_000),});if (!response.ok) {const { error } = await response.json();throw new Error(`${error.code}: ${error.message} (${error.requestId})`);}await writeFile("screenshot.png", Buffer.from(await response.arrayBuffer()));console.log("saved", response.headers.get("X-Screenshot-Id"));
Unlike some HTTP clients, fetch does not throw on a 4xx or 5xx response. It resolves normally, so you must check response.ok yourself, which is why the error branch is not optional. It also has no timeout by default; the signal: AbortSignal.timeout(60_000) line aborts the request after 60 seconds. The server gives up after about 45, so this is a backstop, not the normal path.
Should you use a Buffer or a stream for the image?
response.arrayBuffer() returns an ArrayBuffer, and fs.writeFile wants a Buffer or typed array, so wrap it with Buffer.from. That is the right default: the whole image is in memory for a moment, and you can hand the same Buffer to a database, S3 or an image library. Use a stream when you only want the bytes on disk and do not need them in memory, for example a worker handling many large full-page captures. Readable.fromWeb converts the web stream from fetch into a Node stream, and pipeline from node:stream/promises handles errors and cleanup.
import { createWriteStream } from "node:fs";import { Readable } from "node:stream";import { pipeline } from "node:stream/promises";const response = await fetch("https://urlbooth.com/v1/screenshots", {method: "POST",headers: {Authorization: `Bearer ${process.env.URLBOOTH_API_KEY}`,"Content-Type": "application/json",},body: JSON.stringify({ url: "https://example.com", fullPage: true }),signal: AbortSignal.timeout(60_000),});if (!response.ok) throw new Error((await response.json()).error.message);await pipeline(Readable.fromWeb(response.body),createWriteStream("full-page.png"),);
One trap: call only one of arrayBuffer(), json() or body per response. The body can be consumed once, so check response.ok first and decide whether you are reading an image or a JSON error.
How do you set the device, format, full page, cleanup and frame?
Put them in the object you pass to JSON.stringify: device (for example iphone-17-pro, macbook-pro-14 or desktop), format (png, jpeg or webp), fullPage, cleanup and frame. Anything else is rejected with a 400. The full device list is in the API docs. Frames are disabled for full-page captures, so do not combine frame with fullPage.
import { writeFile } from "node:fs/promises";const response = await fetch("https://urlbooth.com/v1/screenshots", {method: "POST",headers: {Authorization: `Bearer ${process.env.URLBOOTH_API_KEY}`,"Content-Type": "application/json",},body: JSON.stringify({url: "https://example.com",device: "iphone-17-pro",format: "webp",fullPage: true,cleanup: true,}),signal: AbortSignal.timeout(60_000),});if (!response.ok) throw new Error((await response.json()).error.message);await writeFile("pricing.webp", Buffer.from(await response.arrayBuffer()));
Can you call the API from browser code?
No. Anything in client-side JavaScript, including a bundled React app, can be read by every visitor, and the API key bills your account. Keep the call in Node and expose only your own route. The example below lets the browser request a preview from your server, which forwards it with the key from the environment. If the URL comes from user input, validate it and rate limit your route; the API rejects private and local addresses, but your route still spends your daily quota.
// Express-style route: the browser asks your server, your server asks URLBooth.import express from "express";const app = express();app.get("/preview", async (req, res) => {const upstream = await fetch("https://urlbooth.com/v1/screenshots", {method: "POST",headers: {Authorization: `Bearer ${process.env.URLBOOTH_API_KEY}`,"Content-Type": "application/json",},body: JSON.stringify({ url: String(req.query.url), format: "jpeg" }),signal: AbortSignal.timeout(60_000),});if (!upstream.ok) {const { error } = await upstream.json();return res.status(upstream.status).json({ error: error.code });}res.type(upstream.headers.get("Content-Type") ?? "image/jpeg");res.send(Buffer.from(await upstream.arrayBuffer()));});app.listen(3000);
How do you get a saved screenshot later?
The X-Screenshot-Id response header identifies the stored copy, and X-Expires-At says when it goes away: captures are kept for two days. Fetch it again with a GET to /v1/screenshots/{id}/image using the same key.
import { writeFile } from "node:fs/promises";const id = process.argv[2]; // the X-Screenshot-Id value from an earlier captureconst response = await fetch(`https://urlbooth.com/v1/screenshots/${id}/image`, {headers: { Authorization: `Bearer ${process.env.URLBOOTH_API_KEY}` },signal: AbortSignal.timeout(60_000),});if (!response.ok) throw new Error(`HTTP ${response.status}`);await writeFile("again.png", Buffer.from(await response.arrayBuffer()));
How do you handle errors and rate limits in Node.js?
On failure the body is JSON with error.code, error.message and error.requestId. Pro allows 60 requests per minute, 10 concurrent captures and 10,000 per day. A 429 rate_limited includes Retry-After in seconds; daily_limit_reached is also a 429 but only clears at 00:00 UTC. Retry 503 capture_unavailable and 504 capture_timeout with backoff, and do not retry 400, 401 or 402. A 502 capture_failed usually means the target site blocked the browser.
const RETRYABLE = new Set([429, 503, 504]);const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));export async function capture(body, attempts = 3) {for (let attempt = 1; ; attempt++) {const response = await fetch("https://urlbooth.com/v1/screenshots", {method: "POST",headers: {Authorization: `Bearer ${process.env.URLBOOTH_API_KEY}`,"Content-Type": "application/json",},body: JSON.stringify(body),signal: AbortSignal.timeout(60_000),});if (response.ok) return Buffer.from(await response.arrayBuffer());const { error } = await response.json();if (!RETRYABLE.has(response.status) || attempt === attempts) {throw new Error(`${error.code} (request ${error.requestId})`);}const seconds = Number(response.headers.get("Retry-After")) || 2 ** attempt;await sleep(seconds * 1000);}}
For batches, do not fire all requests with a bare Promise.all: a few hundred at once would hit the concurrency limit immediately. A small worker pool keeps ten in flight. Save the retry helper above as capture.js next to this file.
import { capture } from "./capture.js";const urls = ["https://example.com", "https://example.org", "https://example.net"];const results = new Array(urls.length);let next = 0;async function worker() {while (next < urls.length) {const index = next++;results[index] = await capture({ url: urls[index] });}}// 10 workers matches the 10 concurrent captures the Pro plan allows.await Promise.all(Array.from({ length: 10 }, worker));
When should you run a headless browser yourself instead?
Run Puppeteer or Playwright yourself if you need to sign in, click through a flow or capture pages that are not on the public internet. If you only need an image of a public URL, the API avoids shipping Chromium, fonts and memory headroom with your Node service. See screenshot API vs running Puppeteer yourself for the comparison.
Where to go next
- API reference for every option, device and error code.
- Pricing: Pro is $20 per month.
- How to take a website screenshot with an API.
- For other languages, see the Python screenshot guide, PHP screenshot guide and Go screenshot guide.