Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

To take a website screenshot from TypeScript, send an HTTP request to a screenshot provider, check that the response succeeded, and save its image bytes. The endpoint, authentication, request parameters, and response format depend on the provider: there is no universal screenshot API contract. This guide uses ScreenshotEngine for a direct TypeScript example, then explains SDK alternatives and a ScreenshotNeo option.

How do I take a screenshot with an API in TypeScript?

Choose a provider, keep its API key on your server, and make a request using that provider’s documented endpoint and authentication scheme. The following example uses ScreenshotEngine’s documented quick-start contract: a POST to https://api.screenshotengine.com/v1/screenshot, bearer-token authentication, and JSON containing a URL, format, and height. ScreenshotEngine documents successful responses as image bytes and errors as JSON. Do not reuse this endpoint or body with another provider.

Prerequisites

  • Node.js 20 or later, which provides built-in fetch.
  • A ScreenshotEngine API key stored in an environment variable named SCREENSHOTENGINE_API_KEY.
  • A target page that the capture service can access. A local URL such as localhost may not be reachable from a hosted provider.

Set the key in your shell before running the program. For example, on macOS or Linux: export SCREENSHOTENGINE_API_KEY='your-key'. Do not place a real key in source code, commit it to a repository, or send it to a browser client.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Runnable TypeScript example

Save this as screenshot.ts. It checks the HTTP status before writing the response as a PNG, and prints a JSON error body when the provider returns one. The height and format values are examples of ScreenshotEngine request fields, not universal screenshot parameters.

import { writeFile } from "node:fs/promises";

const apiKey = process.env.SCREENSHOTENGINE_API_KEY;
if (!apiKey) {
  throw new Error("Set SCREENSHOTENGINE_API_KEY before running this script");
}

const response = await fetch("https://api.screenshotengine.com/v1/screenshot", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${apiKey}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    url: "https://example.com",
    format: "png",
    height: 900,
  }),
  // A client-side limit, not a promise about the provider's response time.
  signal: AbortSignal.timeout(120_000),
});

if (!response.ok) {
  const errorBody = await response.text();
  throw new Error(`ScreenshotEngine returned HTTP ${response.status}: ${errorBody}`);
}

const image = Buffer.from(await response.arrayBuffer());
await writeFile("screenshot.png", image);
console.log(`Saved screenshot.png (${image.byteLength} bytes)`);

Run it with a TypeScript runner such as tsx, installed in your project, using npx tsx screenshot.ts. Alternatively, compile it with your project’s TypeScript build setup and run the generated JavaScript on Node.js 20 or later. The 120-second timeout is a client-side example budget; ScreenshotEngine’s documentation does not describe it as an API response-time guarantee.

How do I save the screenshot returned by an API?

For a provider that returns image bytes directly, read the response as binary data, not as text or JSON. In the example, response.arrayBuffer() obtains the bytes and Buffer.from makes them suitable for Node’s file-writing API. Only do this after checking response.ok: an error response may be JSON, and saving it as .png would create a file that is not an image.

Use a file extension that matches the requested format and the provider’s documented response. If you request JPEG or WebP, for example, use a matching filename rather than screenshot.png. If you need to return the capture from a server route instead of saving it to disk, forward the image bytes with an appropriate content type and avoid converting them through a text encoding.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Not every provider returns image bytes in the same way. The Screenshot API REST reference describes GET and POST behavior and includes a path that can return JSON or redirects. Follow the selected provider’s response contract; do not assume every successful response is a PNG buffer.

Rank #2
TypeScript Programming Language - Software Engineer & Coder T-Shirt
  • TypeScript implements a superset of syntax for strictly typed development, facilitating deep static analysis and enhanced development environment integration. The compiler translates source into standard script formats, ensuring parity across any runtime.
  • TypeScript is ideal for front-end developers, full-stack engineers, and software architects who build large-scale web applications. It serves those looking to improve code excellence, reduce bugs through static checking, and maintain complex projects more.
  • Lightweight, Classic fit, Double-needle sleeve and bottom hem

How do I call a screenshot API from Node.js?

The TypeScript example above is also valid modern Node.js JavaScript after removing its type-oriented context: Node.js 20 and later includes fetch. For a plain JavaScript version using the ScreenshotEngine endpoint and request fields, use:

const apiKey = process.env.SCREENSHOTENGINE_API_KEY;
if (!apiKey) throw new Error("Set SCREENSHOTENGINE_API_KEY");

const response = await fetch("https://api.screenshotengine.com/v1/screenshot", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${apiKey}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ url: "https://example.com", format: "png", height: 900 }),
});

if (!response.ok) {
  throw new Error(`ScreenshotEngine returned HTTP ${response.status}: ${await response.text()}`);
}

const { writeFile } = await import("node:fs/promises");
await writeFile("screenshot.png", Buffer.from(await response.arrayBuffer()));

This example deliberately names the provider. Other services have different endpoints, authentication choices, options, and response modes. ScreenshotEngine recommends POST for server integrations so the API key is not exposed in a request URL; keep credentials in server-side environment configuration.

Direct HTTP or a TypeScript SDK?

Direct HTTP is a good fit when you want to keep dependencies small, control the exact request, or implement an endpoint in a server that already has an HTTP client. An SDK can offer provider-specific types, helpers, URL construction, download handling, and error objects, but it adds a dependency and remains tied to that vendor’s contract. Neither route is inherently faster or more reliable based on the provider documentation described here.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Option Documented package or endpoint What to consider
ScreenshotNeo API ScreenshotNeo; one GET request to its API Direct call or MCP tools; the API supports screenshot and PDF output.
ScreenshotEngine direct HTTP https://api.screenshotengine.com/v1/screenshot Bearer token and POST JSON in the quick start; successful response is image bytes.
Screenshot API Node package @screenshot-api/js Its REST reference documents its own endpoint, authentication choices, and response behavior.
ScreenshotOne JavaScript/TypeScript SDK screenshotone-api-sdk The official repository describes client-based capture, URL generation, download handling, and API error information.
ScreenshotMAX TypeScript SDK @screenshotmax/sdk The official repository demonstrates setting options, fetching a result, and writing image bytes.

For the Screenshot API package, its documentation gives the install command npm install @screenshot-api/js. ScreenshotOne’s repository gives npm install screenshotone-api-sdk, and ScreenshotMAX’s gives npm install @screenshotmax/sdk. Consult the relevant package’s current documentation for exact imports, types, and option names rather than guessing from another SDK’s interface. The Screenshot API documentation also lists guides for Next.js, Remix, Nuxt, SvelteKit, Storybook, Express, CMS, and commerce contexts.

What should I compare when choosing a screenshot API?

Start with how you plan to use the result. A one-off capture saved by a backend has different needs from a batch job, a PDF workflow, or an AI agent that invokes tools. Confirm each requirement against the provider’s own reference before writing integration code.

  • Authentication and request shape: Determine whether the provider expects bearer authentication, another header, a query parameter, or a particular POST body. Keep credentials server-side.
  • Response contract: Establish whether success returns image bytes, a JSON object, a redirect, or a job identifier. Check error behavior separately.
  • Capture controls: Verify the exact options for image format, viewport dimensions, full-page capture, and any device or rendering controls you need.
  • Workload support: If you need batch capture or asynchronous processing, check that the selected API documents those features and how results are retrieved.
  • Implementation fit: Compare the official SDK’s language support and helpers with the control and reduced dependency footprint of direct HTTP.

The Screenshot API REST reference documents a batch endpoint and advanced POST-only settings. ScreenshotOne and ScreenshotMAX publish JavaScript or TypeScript SDKs, while Screenshot Studio is a separate open-source project whose developer portal describes an unauthenticated API with per-IP limits, OpenAPI 3.1 documentation, a curl quick start, and local self-hosting. Do not confuse that self-hostable project with a commercial hosted provider. The documentation establishes these implementation differences, but does not provide independent speed, reliability, or cost tests that would justify ranking those other providers against one another.

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server. It accepts a URL in one GET request and can return PNG, JPEG, WebP, or PDF. Here is its Node.js request, compatible with TypeScript projects that use Node’s built-in fetch:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

For a complete API reference, see the ScreenshotNeo documentation. Keep the access key on your server; do not expose it in browser code or a public URL. ScreenshotNeo’s clean-shot options accept cookie or consent banners like a visitor and remove more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers report the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf for AI agents and MCP clients. The free plan includes 1,000 shots per month without a card; paid plans start at $5 for 3,000 shots. Sign up for ScreenshotNeo’s free plan.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting a TypeScript screenshot integration

HTTP error instead of an image

Do not write the response body to an image file until the status check passes. Read the error body as text or JSON and inspect the status code. Confirm the key is present, the authentication header matches the provider’s instructions, and the request uses that provider’s endpoint and method.

The saved file is corrupt or has the wrong extension

Check the requested format and the provider’s success response. For direct image bytes, use arrayBuffer() and save those bytes without converting them to a string. If the provider returns JSON, a redirect, or an asynchronous job result instead, handle that documented response rather than treating it as the image itself.

Fetch is unavailable or TypeScript rejects the code

Use Node.js 20 or later for the built-in fetch flow shown here. Confirm that your TypeScript module settings support top-level await, or place the request in an async function and call it from your entry point. A provider SDK may simplify typed request construction, but its installed version and usage instructions should be checked in its official repository.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The request times out

A client timeout only determines how long your program waits; it does not establish how long the provider takes to capture a page. ScreenshotEngine’s example uses 120 seconds as a client budget and explicitly does not promise an API response time. Check the provider’s current guidance for timeout behavior and whether it offers asynchronous jobs. Also check that the target page is publicly reachable by the capture service.

A local or protected page cannot be captured

A hosted screenshot service cannot automatically access a developer’s private localhost. For a local preview, use a permitted staging URL or an approach supported by the provider. For protected pages, consult the selected API’s documentation for its supported authentication, headers, or cookies; do not assume another provider’s options apply.

Cost, performance, and reliability considerations

API documentation and SDK examples do not establish a fair cross-provider benchmark for capture speed, success rate, or cost. Before choosing a service for production, check its current pricing and limits directly, then test the kinds of pages your application actually needs to capture. Pay attention to whether your workflow is synchronous or asynchronous, how failures are represented, and whether repeated captures can be avoided or cached if the provider supports it.

For operational safety, avoid retrying every failure blindly: invalid credentials or unsupported parameters will not be fixed by an immediate retry, and repeated requests may create unnecessary work. Log status codes and provider error details without logging secret keys. If you process captures in a background job, record enough context to retry safely and distinguish a capture failure from a file-write or downstream storage failure.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Can I call a screenshot API from browser-side TypeScript?

A browser call would expose any API key embedded in the client. Use a server endpoint or backend job to hold credentials and make the provider request.

Is Screenshot Studio the same service as Screenshot API?

No. Screenshot Studio is an open-source project with a developer portal describing self-hosting; Screenshot API is a separate provider with its own REST reference and Node package.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.