Build a Website Screenshot API with Node.js and Playwright

Build a Website Screenshot API with Node.js and Playwright

Link previews, thumbnails in a dashboard and visual records of web pages start the same way. A real browser opens the page and captures a website screenshot at a known size. Here you build a website screenshot API in Node.js that does this work. GET /screenshot takes a URL and returns a PNG, JPEG or WebP image. Playwright controls the Chromium browser that makes it. Each request gets its own browser context, the service checks an API key, and it can save the image in Amazon S3 or Cloudflare R2. When the target page answers with an error, the service says so and does not return an image of the error page.

Call the finished screenshot API

Start the service in one terminal:

API_KEY=change-me npm start

Start the local test page from the repository in a second terminal:

npm run test-page

Then request a 1200 x 630 WebP image, the usual size of an Open Graph link preview:

curl -H "Authorization: Bearer change-me" -o preview.webp "http://localhost:3000/screenshot?url=http://127.0.0.1:8080/&width=1200&height=630&format=webp"

The response has status 200, the header Content-Type: image/webp and a body of 23,030 bytes. On the test Mac, the request took about 0.1 seconds with the browser already open. This is the image:

WebP screenshot of the test page at 1200 x 630: a heading, a line that reads viewport 1200 x 630 and device pixel ratio 1, and three cards for PNG, JPEG and WebP

The test page prints the viewport and the device pixel ratio that Chromium gave it, so each image shows the parameters that made it.

Tested with Version
Node.js 22.22.3 on the Mac, 22.23.4 in GitHub Actions for the Docker run, 26.13.0 in the Docker image
Playwright 1.65.0, with Chrome Headless Shell 158.0.8127.18
Express 5.3.0
AWS SDK for JavaScript (@aws-sdk/client-s3) 3.1164.0
image-size (tests only) 2.1.0
Operating systems macOS 26.7.1 on Apple Silicon (M5) for the tests, Ubuntu 24.04 in GitHub Actions for the Docker image
Docker base image mcr.microsoft.com/playwright:v1.65.0-noble
Test date 9 November 2026 for the Docker image, 10 November 2026 for the tests

The complete code, with the tests and the test script, is in the nodejs-playwright folder of the website-screenshot repository on GitHub.

How the screenshot API is built

The service has the same layout as the HTML to PDF API with Node.js. It has one browser for the whole process, a validator, a render module and a small HTTP layer. That tutorial explains the shared parts. This one covers what differs for screenshots: browser contexts, viewport and scale, image formats, the API key and storage.

One screenshot request from the client to Chromium and back:

Sequence diagram: the client calls app.js, render.js opens a new context in Chromium, gets the image bytes, closes the context, and app.js returns the image or the storage key

File Job
src/validate.js Turns the query string into screenshot options
src/render.js Owns Chromium, takes one screenshot in a new browser context and checks that the page loaded
src/app.js Routes, the API key check and the error responses
src/storage.js Optional upload to S3 or R2
src/server.js Starts Chromium, then the HTTP server
test/ The tests, a local test page and its server

Set up the project

Create a folder and add package.json:

{
  "name": "screenshot-api-nodejs",
  "version": "1.0.0",
  "description": "Website screenshot API with Node.js, Express and Playwright",
  "private": true,
  "type": "module",
  "scripts": {
    "start": "node src/server.js",
    "test": "node --test test/*.test.js",
    "test-page": "node test/test-page-server.js"
  },
  "engines": {
    "node": ">=22"
  },
  "dependencies": {
    "@aws-sdk/client-s3": "3.1164.0",
    "express": "5.3.0",
    "playwright": "1.65.0"
  },
  "devDependencies": {
    "image-size": "2.1.0"
  }
}

Install the packages:

npm install

Download the browser:

npx playwright install --only-shell chromium

Notes on the setup:

  • The playwright package has no install script, so npm install does not download a browser. The second command does.
  • --only-shell downloads only Chrome Headless Shell, a smaller Chromium build for headless use. Playwright uses it for headless launches by default.
  • On Linux, add --with-deps. It installs the system libraries for Chromium with apt-get.
  • Each Playwright version expects one browser build. Playwright 1.65.0 expects build 1254, which is Chromium 158. Exact versions keep the screenshots the same from one install to the next.
  • image-size reads the width and height of images in the tests.

Validate the screenshot parameters

GET /screenshot reads all its input from the query string. Create src/validate.js:

// Turns the query string of GET /screenshot into screenshot options.

const FORMATS = ['png', 'jpeg', 'webp'];

// An error that the API returns to the client with status 400.
export function badRequest(message) {
  return Object.assign(new Error(message), { status: 400, expose: true });
}

export function parseScreenshotRequest(query) {
  const format = query.format ?? 'png';
  if (!FORMATS.includes(format)) {
    throw badRequest('"format" must be png, jpeg or webp.');
  }
  if (format === 'png' && query.quality !== undefined) {
    throw badRequest('"quality" works only with jpeg and webp.');
  }

  return {
    url: parseUrl(query.url),
    width: parseNumber(query.width, 'width', { min: 320, max: 1920, fallback: 1280, integer: true }),
    height: parseNumber(query.height, 'height', { min: 240, max: 1920, fallback: 800, integer: true }),
    scale: parseNumber(query.scale, 'scale', { min: 0.25, max: 3, fallback: 1 }),
    format,
    quality: format === 'png'
      ? undefined
      : parseNumber(query.quality, 'quality', { min: 1, max: 100, fallback: 80, integer: true }),
    fullPage: parseBoolean(query.fullPage, 'fullPage'),
    store: parseBoolean(query.store, 'store'),
  };
}

function parseUrl(value) {
  if (typeof value !== 'string' || value === '') {
    throw badRequest('"url" is required.');
  }
  if (value.length > 2048) {
    throw badRequest('"url" is longer than 2048 characters.');
  }
  let url;
  try {
    url = new URL(value);
  } catch {
    throw badRequest('"url" must be an absolute URL.');
  }
  // This blocks file:, data:, javascript: and chrome: URLs. It is NOT protection against SSRF.
  if (url.protocol !== 'http:' && url.protocol !== 'https:') {
    throw badRequest('"url" must start with http:// or https://.');
  }
  return url.href;
}

function parseNumber(value, name, { min, max, fallback, integer = false }) {
  if (value === undefined) return fallback;
  const number = Number(value);
  // A repeated parameter (?width=1&width=2) arrives as an array: reject it too.
  const valid = typeof value === 'string' && value.trim() !== '' && Number.isFinite(number)
    && (!integer || Number.isInteger(number)) && number >= min && number <= max;
  if (!valid) {
    throw badRequest(`"${name}" must be ${integer ? 'an integer' : 'a number'} from ${min} to ${max}.`);
  }
  return number;
}

function parseBoolean(value, name) {
  if (value === undefined || value === 'false') return false;
  if (value === 'true') return true;
  throw badRequest(`"${name}" must be true or false.`);
}

Why the validator works this way:

  • Every number has a range. The number of image pixels is width x height x scale x scale. The largest request (1920 x 1920 at scale 3) gives about 33 million pixels. Without limits, one request can use gigabytes of memory.
  • Express 5 turns a repeated parameter such as ?width=800&width=900 into an array. The typeof check rejects it with status 400.
  • PNG has no quality setting. Playwright throws options.quality is unsupported for the png screenshots, so the validator rejects this case first, with a clearer message.
  • Only http: and https: URLs pass. This blocks file:///etc/passwd, but it does not stop server-side request forgery (SSRF): a request that makes your server call internal addresses. The HTML to PDF tutorial shows the risk with the cloud metadata address. Do not open this service to the internet without SSRF protection.

Capture the website screenshot with Playwright

Create src/render.js. It owns Chromium and takes one Playwright screenshot for each call:

import { chromium } from 'playwright';

// Limits for one screenshot. Change them with environment variables.
const RENDER_TIMEOUT_MS = Number(process.env.RENDER_TIMEOUT_MS ?? 15_000);
// After the HTML loads, wait at most this long for the network to go idle.
const NETWORK_IDLE_TIMEOUT_MS = Number(process.env.NETWORK_IDLE_TIMEOUT_MS ?? 5_000);
const MAX_OPEN_CONTEXTS = Number(process.env.MAX_OPEN_CONTEXTS ?? 4);
// Full-page screenshots stop at this height (in CSS pixels) to limit memory use.
const MAX_FULL_PAGE_HEIGHT = 10_000;

let browserPromise;
let openContexts = 0;

// One Chromium process for the whole service. Requests share it.
export function getBrowser() {
  browserPromise ??= launchBrowser();
  return browserPromise;
}

async function launchBrowser() {
  try {
    const browser = await chromium.launch({
      // Playwright starts Chromium without its sandbox by default. This service
      // opens pages that it does not control, so it turns the sandbox on.
      chromiumSandbox: process.env.CHROMIUM_SANDBOX !== 'false',
    });
    // If Chromium crashes, the next request starts a new one.
    browser.on('disconnected', () => {
      browserPromise = undefined;
    });
    return browser;
  } catch (error) {
    browserPromise = undefined;
    throw error;
  }
}

export async function closeBrowser() {
  const browser = await browserPromise;
  await browser?.close();
}

// Takes one screenshot and returns the image as a Buffer.
export async function takeScreenshot(options) {
  if (openContexts >= MAX_OPEN_CONTEXTS) {
    throw Object.assign(new Error('Too many screenshots in progress. Try again later.'), {
      status: 503,
      expose: true,
    });
  }
  openContexts++;
  let context;
  try {
    const browser = await getBrowser();
    // A new context for each request: no cookies, storage or cache from other requests.
    context = await browser.newContext({
      viewport: { width: options.width, height: options.height },
      deviceScaleFactor: options.scale,
    });
    // Applies to page.goto() and page.screenshot().
    context.setDefaultTimeout(RENDER_TIMEOUT_MS);

    const page = await context.newPage();
    // 'domcontentloaded' waits for the HTML only. 'load' also waits for every
    // image, frame and ad, and on some pages it does not come at all.
    const response = await page.goto(options.url, { waitUntil: 'domcontentloaded' });
    // A 403 block page or a 404 page is an answer, but it is not the page.
    const status = response?.status() ?? 200;
    if (status >= 400) {
      throw targetFailed(`The page answered with status ${status}.`, status);
    }

    // Give scripts, images and fonts a short time to finish, then continue.
    await page.waitForLoadState('networkidle', { timeout: NETWORK_IDLE_TIMEOUT_MS }).catch((error) => {
      if (error.name !== 'TimeoutError') throw error;
    });
    // A redirect from a script can end on Chrome's error page after goto().
    if (page.url().startsWith('chrome-error://')) {
      throw targetFailed('The page could not be loaded.');
    }

    return await page.screenshot({
      type: options.format,
      quality: options.quality,
      fullPage: options.fullPage,
      // With fullPage, Playwright cuts this clip to the height of the page.
      clip: options.fullPage
        ? { x: 0, y: 0, width: options.width, height: MAX_FULL_PAGE_HEIGHT }
        : undefined,
    });
  } finally {
    openContexts--;
    // Closes the page too. close() fails when Chromium crashed: keep the first error.
    await context?.close().catch(() => {});
  }
}

// The target page failed. The API answers 502 and names the status of the page.
function targetFailed(message, targetStatus) {
  return Object.assign(new Error(message), { status: 502, expose: true, targetStatus });
}

A browser context is an isolated browser session, with its own cookies, local storage, cache and permissions (Playwright: isolation). One caller’s page cannot read the cookies that another caller’s page set. A context is cheap. On the test Mac, a new context with its page took a median of 40 ms. A Chromium launch took 140 to 470 ms. So the service keeps one browser and opens a context for each request.

The other decisions in this file:

  • The viewport and deviceScaleFactor belong to the context, so each request gets its own size. The next section explains both.
  • Playwright starts Chromium without its sandbox, because chromiumSandbox is false by default (launch options). Puppeteer keeps the sandbox on by default. This service opens pages that other people choose, so it turns the sandbox on. CHROMIUM_SANDBOX=false turns it off; use that only for pages that you trust.
  • waitUntil: 'domcontentloaded' returns when the HTML is parsed. The default, load, also waits for every image, frame and script, and on pages with many ads it often does not come in time. A request to an ad server that never answers keeps load open until the timeout, and the caller gets status 504 and no image. The networkidle option of page.goto() has the same problem, and the page.goto() reference marks it as discouraged.
  • After domcontentloaded, page.waitForLoadState('networkidle') waits until the page makes no request for 500 ms. The code limits it to NETWORK_IDLE_TIMEOUT_MS (5 seconds by default) and ignores its TimeoutError: the screenshot goes on with what the page has. A busy page costs you at most 5 seconds. A quiet page costs a few hundred milliseconds. A page that loads data after that needs a wait for an element, which a later tutorial covers.
  • page.goto() does not throw for HTTP error codes. The code reads response.status() and fails for 400 and higher, so a 403 bot-block page or a 404 page does not become a screenshot. The error has targetStatus, and the API returns it to the caller.
  • A script on the page can send the browser to an address that does not load. Chromium then shows its own error page, and the URL of the page starts with chrome-error://. The code checks the URL after the wait and fails, so the error page of Chrome is not returned as a result.
  • fullPage: true captures the whole scrollable page. A long article or an endless feed can give an image tens of thousands of pixels high. The clip stops the image at 10,000 CSS pixels. With fullPage, Playwright cuts the clip to the page height, so a 3,000 px page still gives a 3,000 px image. The tests check both cases.
  • The finally block closes the context and its page in all cases, and the counter returns status 503 when MAX_OPEN_CONTEXTS screenshots run. The HTML to PDF tutorial explains why both matter.

Set the viewport and the scale

The viewport is the window size in CSS pixels. The page sees it in innerWidth, innerHeight and its CSS media queries. The scale is the device scale factor: the number of image pixels for each CSS pixel. A phone screen has a factor of 2 or 3. The image size is the viewport multiplied by the scale:

Query parameters What the page sees Image size
width=1200&height=630 1200 x 630, ratio 1 1200 x 630
width=390&height=700&scale=2 390 x 700, ratio 2 780 x 1400
width=1200&height=630&scale=0.25 1200 x 630, ratio 0.25 300 x 158

How viewport and scale set the result:

Diagram: the viewport size sets the page layout, and the viewport times the scale sets the image size

This is the second request from the table, with format=webp: a phone layout at scale 2. The cards change from three columns to one, because the page sees a 390 px viewport:

Screenshot of the test page with a 390 x 700 viewport at scale 2: the three cards are in one column, and the page reports a device pixel ratio of 2

A scale less than 1 makes a thumbnail without an image library. Chromium lays out the page for 1200 px and draws it at a quarter of the size. The 300 x 158 WebP thumbnail of the test page has 3,074 bytes. At this size, the 1 px lines of the test page disappear.

Choose PNG, JPEG or WebP for the screenshot

Since version 1.62, a Playwright screenshot can be PNG, JPEG or WebP. Before that version, a WebP image needed a converter such as sharp. Now type: 'webp' in page.screenshot() is enough. For WebP, quality: 100 gives a lossless image, and lower values give lossy compression.

File sizes of the 1200 x 630 test page, measured on the test Mac:

Format Quality Bytes
PNG lossless 38,535
JPEG 80 48,545
JPEG 50 34,655
WebP 80 23,030
WebP 50 17,514
WebP 100 (lossless) 16,328

The test page has flat colors and text. For it, lossless WebP is the smallest file, and JPEG at quality 80 is larger than PNG. A page with photos gives other results, so measure your own pages. The service uses quality 80 for JPEG and WebP when the request has no quality. Playwright’s own default for WebP is 100.

Pick a format for each use:

Decision diagram: pages with photos use lossy WebP or JPEG; other pages use lossless WebP, or PNG when the client cannot read WebP

Add the HTTP routes and the API key check

Create src/app.js:

import { createHash, timingSafeEqual } from 'node:crypto';
import express from 'express';
import { takeScreenshot } from './render.js';
import { createStorage } from './storage.js';
import { badRequest, parseScreenshotRequest } from './validate.js';

const CONTENT_TYPES = { png: 'image/png', jpeg: 'image/jpeg', webp: 'image/webp' };

export function createApp({ apiKey = process.env.API_KEY, storage = createStorage() } = {}) {
  const app = express();
  app.disable('x-powered-by');

  app.get('/health', (req, res) => {
    res.json({ status: 'ok' });
  });

  app.get('/screenshot', requireApiKey(apiKey), async (req, res) => {
    const options = parseScreenshotRequest(req.query);
    if (options.store && !storage) {
      throw badRequest('"store" needs S3_BUCKET on the server.');
    }

    const image = await takeScreenshot(options);
    const contentType = CONTENT_TYPES[options.format];

    if (options.store) {
      const saved = await storage.save(image, contentType, options.format);
      return res.status(201).json(saved);
    }
    res.type(contentType).send(image);
  });

  // Express 5 sends errors from async handlers here.
  app.use((error, req, res, next) => {
    if (error.name === 'TimeoutError') {
      return res.status(504).json({ error: 'The page did not load in time.' });
    }
    // Playwright reports network errors as "net::ERR_NAME_NOT_RESOLVED" and similar.
    if (error.message?.includes('net::ERR_')) {
      return res.status(502).json({ error: 'The page could not be loaded.' });
    }
    // The page answered 4xx or 5xx, for example 403 from a bot block.
    if (error.targetStatus) {
      return res.status(502).json({ error: error.message, targetStatus: error.targetStatus });
    }
    if (!error.expose) {
      console.error(error);
    }
    res.status(error.status ?? 500).json({ error: error.expose ? error.message : 'The screenshot failed.' });
  });

  return app;
}

// Checks the header "Authorization: Bearer <key>". Without a key, all requests pass.
function requireApiKey(apiKey) {
  const expected = apiKey ? sha256(apiKey) : null;
  return (req, res, next) => {
    if (!expected) return next();
    const header = req.get('authorization') ?? '';
    const given = header.startsWith('Bearer ') ? header.slice(7) : '';
    // timingSafeEqual needs two buffers of the same length. SHA-256 hashes
    // always have 32 bytes, and the compare time does not show how much matched.
    if (timingSafeEqual(sha256(given), expected)) return next();
    res.status(401).json({ error: 'The API key is missing or wrong.' });
  };
}

function sha256(text) {
  return createHash('sha256').update(text).digest();
}

The API key check:

  • The key comes in the Authorization header, not in the query string. URLs go into access logs and browser history.
  • crypto.timingSafeEqual() compares two buffers in a time that does not depend on their content. A normal === stops at the first wrong character, so the response time can show how much of a guess is correct.
  • timingSafeEqual() throws an error when the two buffers have different lengths (Node.js crypto docs). The check hashes both values with SHA-256 first, so both buffers always have 32 bytes, and the key length does not leak.
  • If API_KEY is not set, all requests pass, and server.js prints a warning. Use this only on your own computer.

The status codes:

  • 200 with the image, or 201 with { "bucket", "key" } when the image went to storage.
  • 400 for a bad parameter, with a message that names it. 401 for a missing or wrong key.
  • 502 when Chromium gets a network error, for example net::ERR_NAME_NOT_RESOLVED or a refused connection. Also 502 when the page answers with status 400 or higher, or ends on Chrome’s error page.
  • 503 when MAX_OPEN_CONTEXTS screenshots run, and 504 when the page or the screenshot takes longer than RENDER_TIMEOUT_MS.

A target page that answers 403 gives status 502 and a JSON body that names the status of the page. This is the request to the /blocked page of the test server:

curl -i -H "Authorization: Bearer change-me" "http://localhost:3000/screenshot?url=http://127.0.0.1:8080/blocked"

The response starts with HTTP/1.1 502 Bad Gateway, and the body is:

{"error":"The page answered with status 403.","targetStatus":403}

The caller can then decide what to do. A 4xx answer from the target will not change if the caller sends the same request again, so do not retry it. Retry only a timeout or a network error, and at most two times.

Create src/server.js:

import { createApp } from './app.js';
import { closeBrowser, getBrowser } from './render.js';

const port = Number(process.env.PORT ?? 3000);

if (!process.env.API_KEY) {
  console.warn('API_KEY is not set: the service accepts requests without a key.');
}

// Start Chromium first. If it cannot start, the service stops here with the error.
await getBrowser();

const server = createApp().listen(port, (error) => {
  if (error) throw error;
  console.log(`Screenshot API on http://localhost:${port}`);
});

// Docker and most process managers send SIGTERM before they stop the service.
for (const signal of ['SIGINT', 'SIGTERM']) {
  process.once(signal, () => {
    server.close(async () => {
      await closeBrowser();
      process.exit(0);
    });
  });
}

It starts Chromium before the first request and closes it on SIGTERM, as in the HTML to PDF tutorial.

Save screenshots to S3 or Cloudflare R2

A background job that makes catalog thumbnails needs a stored file, not image bytes. With store=true, the service uploads the image and returns its key. Create src/storage.js:

// Optional: saves screenshots in Amazon S3 or in an S3-compatible store
// such as Cloudflare R2. Without S3_BUCKET, the service does not use it.
import { randomUUID } from 'node:crypto';
import { PutObjectCommand, S3Client } from '@aws-sdk/client-s3';

export function createStorage(env = process.env, client = null) {
  if (!env.S3_BUCKET) return null;

  // The SDK reads AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY from the environment.
  // R2: S3_ENDPOINT=https://<account id>.r2.cloudflarestorage.com and region "auto".
  const s3 = client ?? new S3Client({
    region: env.S3_REGION ?? 'auto',
    endpoint: env.S3_ENDPOINT,
  });

  return {
    async save(image, contentType, extension) {
      const key = `screenshots/${randomUUID()}.${extension}`;
      await s3.send(new PutObjectCommand({
        Bucket: env.S3_BUCKET,
        Key: key,
        Body: image,
        ContentType: contentType,
      }));
      return { bucket: env.S3_BUCKET, key };
    },
  };
}

Start the service with the bucket settings for Cloudflare R2:

S3_BUCKET=screenshots S3_ENDPOINT=https://<account id>.r2.cloudflarestorage.com AWS_ACCESS_KEY_ID=<key id> AWS_SECRET_ACCESS_KEY=<secret> API_KEY=change-me npm start

Request a stored screenshot:

curl -H "Authorization: Bearer change-me" "http://localhost:3000/screenshot?url=http://127.0.0.1:8080/&format=webp&store=true"

The response has status 201 and a body such as {"bucket":"screenshots","key":"screenshots/<random UUID>.webp"}.

Notes on the storage code:

  • The SDK needs a region, but R2 does not use it. The Cloudflare R2 example for the AWS SDK v3 uses auto. For Amazon S3, set S3_REGION, for example eu-central-1, and do not set S3_ENDPOINT.
  • The SDK reads the credentials from AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY. Keep them out of the code and out of Git.
  • The key is a random UUID, so a caller cannot guess the keys of other screenshots.
  • Keep the bucket private. To give a caller a link, create a presigned URL that expires.
  • The tests use a stub S3 client, not a real bucket. They make sure that the upload sends the bucket, the key, the image and the content type.

Test the screenshot API

The tests start Chromium, the service and a local page server, so they need no internet. They check real images:

  • The default request gives a PNG with the PNG signature and a size of 1280 x 800.
  • JPEG at scale 2 gives 1600 x 1200. WebP at scale 0.25 gives 320 x 200.
  • fullPage on a 3,000 px page gives 3,000 px. On a 25,000 px page, it gives 10,000 px.
  • Status 400 for a file: URL and a bad width, 401 for a missing or wrong key, and 502 for a closed port.
  • Status 502 with "targetStatus": 403 for a page that answers 403, and status 502 for a page whose script sends the browser to an address that does not load.
  • A page with an image request that never answers still gives a 1280 x 800 screenshot, in less than the render timeout. The test sets the idle wait to 500 ms and the timeout to 2,000 ms, so it finishes fast. The page never fires load, so with waitUntil: 'load' it would give 504.
  • Status 504 for a page that never answers, and 503 for a second request while MAX_OPEN_CONTEXTS is 1.
  • store=true returns 201 with the stub storage, and the storage test checks the S3 command.

Run the tests:

npm test

The 20 tests took about 10 seconds on the test Mac. The test files are in the test folder of the repository, and test.sh runs them, then the npm start and curl commands of this tutorial, then the Docker steps.

Run the screenshot service in Docker

Create Dockerfile:

# The official Playwright image: Ubuntu 24.04, Node.js, the browsers and
# their system libraries. Keep its version equal to playwright in package.json.
FROM mcr.microsoft.com/playwright:v1.65.0-noble

WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY src ./src

# Do not run Chromium as root. The image comes with the user pwuser.
USER pwuser
ENV NODE_ENV=production PORT=3000
EXPOSE 3000
CMD ["node", "src/server.js"]

Create .dockerignore:

node_modules
test
out

Build the image:

docker build -t screenshot-api-nodejs .

Start the container:

docker run --rm --init --cap-add=SYS_ADMIN -p 3000:3000 -e API_KEY=change-me screenshot-api-nodejs

Why the image and the flags look like this:

  • The official Playwright image has Chromium, its system libraries and fonts. Its tag must match the playwright version in package.json. With other versions, Playwright cannot find the browser (Playwright Docker docs).
  • The image is large (2.59 GB in the CI build), because it also holds Firefox and WebKit. It brings its own Node.js, 26.13.0 in this tag. A slim image with only the headless shell is smaller, but you must install the libraries yourself.
  • USER pwuser runs the service as the non-root user that comes with the image.
  • --cap-add=SYS_ADMIN lets Chromium create the namespaces for its sandbox. Docker’s default seccomp profile (a filter for Linux system calls) allows them only with this capability. The Playwright Docker docs also describe a custom seccomp profile as an alternative.
  • --init collects the ended Chromium child processes. The HTML to PDF tutorial explains it.

Without --cap-add=SYS_ADMIN, the launch fails. This is the output from the CI run, shortened:

browserType.launch: Target page, context or browser has been closed
Browser logs:
Chromium sandboxing failed!
...
FATAL:content/browser/zygote_host/zygote_host_impl_linux.cc:144] No usable sandbox!

On 9 November 2026, test.sh built the image on Ubuntu 24.04 in GitHub Actions, started it with these flags and requested a PNG and a WebP. The PNG came back as a 1200 x 630 image. The Docker steps did not run again after the review changes to render.js, and the Dockerfile did not change.

If you do not want to run and update Chromium yourself, the APISK Screenshot API gets a screenshot of a web page from its link. It is in early access.

Fix common screenshot API errors

What you see Cause Fix
Executable doesn't exist at .../chromium_headless_shell-1254/... and “Looks like Playwright was just installed or updated” The browser for this Playwright version is not installed Run npx playwright install --only-shell chromium. In Docker, use the image tag that matches package.json.
Host system is missing dependencies to run browsers. Linux libraries for Chromium are missing Run sudo npx playwright install-deps chromium, or install with --with-deps
Chromium sandboxing failed! or No usable sandbox! The container or the host blocks the namespaces for the sandbox Start the container with --cap-add=SYS_ADMIN. On an Ubuntu 23.10 or later host, allow unprivileged user namespaces in AppArmor.
Status 504; the log of a direct Playwright call shows page.goto: Timeout 15000ms exceeded. The server of the page did not send its HTML in time, or the screenshot took too long Open the URL in a browser. If the page is slow but correct, raise RENDER_TIMEOUT_MS.
Status 502 and "targetStatus": 403 (or 404, 500 and so on) The page answered with an error status, for example a bot block Open the URL in a browser. A 403 often means that the site blocks servers. Do not retry a 4xx answer.
Status 502 and The page could not be loaded. while the page itself answered The page ended on Chrome’s error page (chrome-error://) Open the URL in a browser and look for a redirect to an address that does not load
Status 502; Playwright reports net::ERR_NAME_NOT_RESOLVED The host name does not exist, or the server has no DNS Make sure that the URL is correct and that the server can resolve it
The target URL loses its own & parameters The service reads &page=2 of the target URL as its own parameter Encode the URL: curl --get --data-urlencode "url=https://shop.example/search?q=a&page=2" ...
A spinner or an empty area in the image The page loads its data after the idle wait ended (5 seconds at most) Raise NETWORK_IDLE_TIMEOUT_MS, or wait for an element that shows the data before the screenshot
The screenshot of a busy page takes 5 seconds The page never goes idle, so the idle wait runs to its limit Lower NETWORK_IDLE_TIMEOUT_MS if you do not need late content
A cookie banner covers the page The page shows it to every new context Hide the banner with CSS (the style option of page.screenshot())
Text in the image is blurry Scale 1 on a screen with a higher pixel density Request scale=2
The full-page image stops at 10,000 px MAX_FULL_PAGE_HEIGHT in render.js Raise the value, if your server has the memory
Status 503 MAX_OPEN_CONTEXTS screenshots run Try again later, or raise the value if the server has free memory

Before you open it to other people

Four parts are missing before other people can call this service:

  1. SSRF protection: check each address that Chromium requests, also after redirects.
  2. A rate limit for each API key, and keys stored as hashes in a database, so that you can give each client its own key.
  3. A cache, so that the same URL and parameters return the stored image without a new screenshot.
  4. Waits for pages that load data late, and CSS that hides cookie banners and chat widgets.

The PDF version of this service is the HTML to PDF API with Node.js and Puppeteer. The code of this tutorial is in the nodejs-playwright folder, with the tests and the CI job.

Frequently Asked Questions

Can Playwright take WebP screenshots?

Yes, since Playwright 1.62. Pass type: 'webp' to page.screenshot() or locator.screenshot(), or give a path that ends in .webp. For WebP, quality: 100 (the default) gives a lossless image, and lower values give a lossy image. Older versions return only PNG and JPEG, so they need a converter such as sharp.

How do I make a website thumbnail without an image library?

Set deviceScaleFactor to less than 1 in the browser context. With a 1200 x 630 viewport and a factor of 0.25, Chromium lays out the page for 1200 CSS pixels and returns a 300 x 158 image. Lines of 1 px and small text disappear at this size. If you want to control the resize filter, take the screenshot at scale 1 and resize with an image library such as sharp.

Why is my Playwright screenshot blank or missing content?

The service waits for domcontentloaded and at most 5 seconds of network idle, so a page that loads its data later can look empty. Wait for an element that shows the data before the screenshot, for example await page.locator(".chart").waitFor(), or raise NETWORK_IDLE_TIMEOUT_MS. Lazy images load only when they come near the viewport, so a full-page screenshot can show empty boxes. Web fonts can also arrive late: await page.evaluate(async () => { await document.fonts.ready; }) waits for them.

Why does my screenshot show Access denied, or fail with status 502?

Some sites block requests from servers and answer with 403 and a block page. The service reads the status of the page and answers 502 with {"targetStatus": 403}, so you never get a block page as an image. A 4xx answer does not change when you send the same request again, so do not retry it. Try the URL from another network, or ask the site owner to allow your server. Retry only timeouts and network errors.

Playwright or Puppeteer for a screenshot API?

Both control Chromium, and both return PNG, JPEG and WebP. Playwright sets the viewport and the scale when it creates a browser context, and its chromiumSandbox option is off by default. Puppeteer starts Chrome with the sandbox on and downloads Chrome during npm install. The HTML to PDF API with Node.js uses Puppeteer with the same file layout, so you can compare the two services file by file.

Is it safe to run a public screenshot API?

Not without more protection. A URL parameter lets callers make your server open any address, for example an internal service or the cloud metadata address 169.254.169.254. Check each address that the browser requests, also after redirects, and add a rate limit for each API key. Keep the Chromium sandbox on, and run the service as a non-root user.

Share:
Markdown version
↧
Loading PDF…