Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk9 min

How to Use a Screenshot API with Next.js

A practical guide to adding screenshots to a Next.js app: choose Playwright or a hosted API, validate requests, return image bytes, and troubleshoot missing content.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Build the capture flow as a server-side Next.js endpoint: validate the target URL, send it to a browser you run with Playwright or to a hosted screenshot API, then return the image bytes or a URL to a stored image. Keep provider credentials on the server, set bounded timeouts, and check the upstream response before treating it as a screenshot.

Choose how your Next.js app will render the page

A screenshot is the output of a browser rendering a page. Your app can run that browser itself with Playwright, or delegate rendering to a hosted API over HTTP.

Approach What your app does Best fit Trade-offs to assess
Playwright Runs browser automation, navigates to the target and captures a file or image buffer. Playwright screenshots and its Page API document this flow. Teams that need direct browser control and can operate the browser runtime. You manage runtime compatibility, concurrency, memory and deployment constraints for your chosen host.
Hosted screenshot API Sends an authenticated request to a provider’s endpoint and receives image content. Browserless documents a POST to /screenshot with a token. Browserless Screenshot API Teams that prefer to delegate browser execution. Evaluate the provider’s authentication, request limits, latency, data handling and service terms; these vary and are not established by endpoint documentation alone.

In either design, your Next.js server is the boundary between the browser client and the capture engine. The client should call your route, not send a private provider token or an unrestricted target URL directly to a third party.

Build a server-side route for the capture

The examples below show the request and response logic using the Next.js App Router route-handler pattern. Confirm the route conventions and runtime support for the Next.js version and deployment host you use in the Next.js Route Handlers documentation. Do not assume that a browser-dependent runtime is available in every deployment environment.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

1. Validate the target

Accept a URL in the request body, parse it, allow only HTTP or HTTPS, and apply your product’s host policy. A public screenshot feature that accepts arbitrary URLs can be abused to request internal services or unexpectedly expensive pages. For private applications, use an explicit allowlist of permitted hosts; do not rely on URL parsing alone as a complete server-side request forgery defense.

2. Keep credentials and execution on the server

Put any hosted-provider access key in a server environment variable, such as SCREENSHOT_API_KEY. Do not prefix a secret with NEXT_PUBLIC_ or return it to the browser. A hosted token-authenticated request, such as the one Browserless documents, makes server-side credential handling essential. Browserless REST API overview

3. Decide whether to return bytes or a URL

For a small synchronous capture, return the image bytes with the correct Content-Type. If the result needs caching, reuse, or asynchronous processing, store it and return a URL your application controls. Storage, caching and job handling are application design choices, not behavior supplied automatically by a screenshot endpoint.

Option A: capture with Playwright

Install Playwright and its required browser in the environment where your Next.js route runs, following the current Playwright installation instructions. The route must run where a Playwright browser can launch; configure the route’s runtime and browser installation for your hosting platform rather than assuming a browser binary is present.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

This illustrative App Router handler validates the URL, navigates, and returns a PNG buffer. The exact Next.js route syntax should be checked against the documentation for your installed version.

import { chromium } from 'playwright';

export const runtime = 'nodejs';

export async function POST(request: Request) {
  let target: URL;
  try {
    const body = await request.json();
    target = new URL(body.url);
  } catch {
    return Response.json({ error: 'Provide a valid URL.' }, { status: 400 });
  }

  if (!['http:', 'https:'].includes(target.protocol)) {
    return Response.json({ error: 'Only HTTP and HTTPS URLs are allowed.' }, { status: 400 });
  }

  // Add an explicit host allowlist or other SSRF protections for your use case.
  const browser = await chromium.launch();
  try {
    const page = await browser.newPage({ viewport: { width: 1280, height: 800 } });
    await page.goto(target.toString(), { waitUntil: 'networkidle', timeout: 30000 });
    const image = await page.screenshot({ type: 'png', fullPage: true });
    return new Response(image, {
      headers: {
        'Content-Type': 'image/png',
        'Cache-Control': 'no-store'
      }
    });
  } catch (error) {
    return Response.json({ error: 'Screenshot capture failed.' }, { status: 502 });
  } finally {
    await browser.close();
  }
}

Playwright’s page.screenshot() can write a file or return image data as a buffer for further processing or transport. The example uses a buffer so the route can return the image directly. Playwright screenshots

Wait for the content you actually need

networkidle can be unsuitable for pages that keep connections open or load content after the initial navigation. If the target’s required content appears later, wait for a meaningful selector instead, or use a bounded delay when no stable selector exists. Set an explicit timeout and return an error when the page does not become ready; do not turn a partial or blank capture into a success response.

For long pages with lazy-loaded images, scrolling may be necessary before full-page capture. Playwright provides full-page screenshot mode via fullPage: true; test target pages because lazy content and access restrictions can change what is visible. Playwright screenshots

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Option B: use a hosted screenshot API

Browserless documents a token-authenticated POST request to /screenshot that returns image bytes. The endpoint supports options including full-page capture, image format, quality, clipping, viewport and selector-based capture. Check its current documentation for the exact request schema and supported settings. Browserless Screenshot API

A generic Next.js handler can forward a validated target and its allowed capture settings. Adapt the endpoint URL and JSON body to the provider’s documented schema; do not assume that one provider’s parameters work with another.

export const runtime = 'nodejs';

export async function POST(request: Request) {
  const token = process.env.BROWSERLESS_TOKEN;
  if (!token) {
    return Response.json({ error: 'Screenshot provider is not configured.' }, { status: 500 });
  }

  let body: { url?: string };
  try {
    body = await request.json();
  } catch {
    return Response.json({ error: 'Invalid JSON body.' }, { status: 400 });
  }

  let target: URL;
  try {
    target = new URL(body.url ?? '');
  } catch {
    return Response.json({ error: 'Provide a valid URL.' }, { status: 400 });
  }
  if (!['http:', 'https:'].includes(target.protocol)) {
    return Response.json({ error: 'Only HTTP and HTTPS URLs are allowed.' }, { status: 400 });
  }

  // Apply your host policy here before forwarding the URL.
  const upstream = await fetch(`https://production-sfo.browserless.io/screenshot?token=${encodeURIComponent(token)}`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ url: target.toString(), options: { fullPage: true, type: 'png' } }),
    signal: AbortSignal.timeout(45000)
  });

  if (!upstream.ok) {
    return Response.json({ error: `Screenshot provider returned ${upstream.status}.` }, { status: 502 });
  }

  const image = await upstream.arrayBuffer();
  if (image.byteLength === 0) {
    return Response.json({ error: 'Screenshot provider returned an empty image.' }, { status: 502 });
  }
  return new Response(image, {
    headers: {
      'Content-Type': upstream.headers.get('content-type') ?? 'image/png',
      'Cache-Control': 'no-store'
    }
  });
}

The URL and option shape in the request body must match the chosen provider’s current documentation. The example’s illustrative Browserless host and options should be verified before deployment; use the provider’s documented endpoint for your account and region. Never forward an upstream error body as though it were an image.

Capture options that change the result

Choose settings based on the output the application needs. More extensive rendering—such as a full-page view or a large viewport—can take longer and use more resources than a viewport-sized capture.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
  • Full page: capture beyond the initial viewport; lazy-loaded content may require scrolling or an explicit wait before capture.
  • Format and quality: PNG is useful when preserving crisp text or transparency matters; JPEG and WebP may suit smaller image delivery. The hosted endpoint’s supported formats and quality controls are provider-specific.
  • Viewport and device scale: set a viewport matching the layout you intend to inspect, and use device-scale options where the API supports them.
  • Clip or selector: capture a region or a selected element instead of the whole page when the use case calls for it.
  • Readiness: wait for a selector or content condition rather than assuming navigation completion means the page is visually ready.

Playwright’s documented screenshot API includes full-page capture and output options such as image type and clip area. Hosted APIs expose their own subset; Browserless documents full-page, format, quality, clip, viewport and selector controls. Playwright Page API · Browserless Screenshot API

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

Or skip the browser setup

ScreenshotNeo is a hosted website screenshot API and MCP server for developers. It accepts a URL in one GET request and returns a screenshot or PDF. Its clean-shot flow accepts cookie or consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups and chat widgets before capture; each step can be turned off. Only clean shots are billed: bot checks or CAPTCHAs, blank pages, timeouts, failed loads and cache hits cost nothing, and response headers identify the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info and capture_pdf tools for AI agents. ScreenshotNeo

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for request options and response details. You can also use this endpoint from Python:

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)

Or Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo includes 1,000 shots a month on its free plan with no card; paid plans start at $5 for 3,000 shots. Sign up free for ScreenshotNeo.

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

Reliability, performance and cost considerations

Bound the work

Set limits for the route’s request duration, browser navigation, and any readiness wait. A route should fail clearly when a page stalls rather than waiting indefinitely. Consider limiting page dimensions and capture frequency, especially when callers can submit targets.

Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Account for concurrency

With Playwright, each capture consumes browser and host resources, so evaluate memory, process lifecycle and concurrency for your deployment. With a hosted service, browser execution is delegated, but your route still depends on network requests and the provider’s service behavior. The cited provider pages do not establish universal latency, quotas or reliability figures; consult the provider and hosting documentation for the plan and environment you actually use.

Control repeat work

If a result can be reused, cache it using a key that includes the target URL and every option that changes the image. Avoid caching authenticated or user-specific pages across users. For larger workflows, store images and return an application-owned retrieval URL instead of keeping a request open while a long capture completes.

Protect the endpoint

  • Restrict schemes and hosts, and block access to private or link-local network destinations using defenses appropriate to your hosting environment.
  • Authenticate or rate-limit callers if captures have meaningful compute or provider cost.
  • Do not expose provider credentials in client bundles, URLs visible to users, or logs.
  • Decide whether target pages may contain sensitive information before storing or returning captures.

Troubleshooting incomplete or failed captures

Symptom Likely cause What to check
Blank or nearly blank image The page had not rendered its content, navigation failed, or the target presented a blocking page. Check navigation status and logs; wait for a meaningful selector; confirm the target is accessible from the capture environment.
Missing images or below-the-fold content Lazy loading has not been triggered before capture. Scroll through the page or wait for the required content before full-page capture, then test the specific target again.
CAPTCHA, access denied or HTTP 403 view The site may be blocking automation or applying access controls. Treat the result as a blocked capture, not a valid screenshot. A provider’s documented troubleshooting suggestions are not a guarantee that the target can be captured.
Broken or missing elements Resources may not have loaded, or the automated view may differ from a normal browser session. Inspect the target’s access requirements, readiness conditions and network behavior; test with the same viewport and settings used in production.
Route times out Slow target loading, an unsuitable readiness condition, or a limit in the route’s hosting environment. Use a bounded, target-appropriate wait and confirm the route’s execution limits. Do not simply remove the timeout.
Route returns an image that is actually an error The handler forwarded upstream error content or assumed every response was image data. Check HTTP status and content type before returning bytes; convert provider failures into an application error response.

Browserless specifically describes blank captures, CAPTCHA pages, 403/access-denied pages, and missing or broken elements as possible signs of blocking or differences from a normal browser view. Browserless Screenshot API

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

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

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

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.