October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

Puppeteer Screenshot in an Express API: Return an Image Response

Use Puppeteer’s screenshot bytes in an Express route, set the matching image content type, and close browser resources safely.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Capture the page with Puppeteer’s page.screenshot(), then send the resulting bytes from your Express route with a matching image content type. Puppeteer returns binary image data by default and uses PNG unless you choose another supported format; Express otherwise labels a Buffer response as application/octet-stream.

Return a screenshot directly from an Express route

This ES module example captures a fixed URL and returns a PNG. It converts Puppeteer’s Uint8Array result to a Node.js Buffer, sets the response type, and closes the browser even if navigation or capture fails.

As an Amazon Associate I earn from qualifying purchases.

import express from 'express';
import puppeteer from 'puppeteer';

const app = express();

app.get('/screenshot', async (req, res, next) => {
  let browser;
  try {
    browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto('https://example.com', { waitUntil: 'networkidle2' });

    const image = await page.screenshot({ type: 'png' });
    res.type('png').send(Buffer.from(image));
  } catch (error) {
    next(error);
  } finally {
    await browser?.close();
  }
});

app.listen(3000);

Start the app and request http://localhost:3000/screenshot. The response body is the image bytes, not JSON or a base64 string. The fixed example URL is deliberate: if you later accept target URLs from callers, add validation and access controls rather than passing arbitrary URLs straight to a browser.

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

Why the response type and binary handling matter

Send bytes, not a text representation

In current Puppeteer API types, the default screenshot result is a Uint8Array. Buffer.from(image) makes the binary response intent explicit for Express’s res.send(). Do not convert the bytes to a normal string; that can corrupt the image.

#1 Best Overall
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
  • WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
  • A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents

Match the MIME type to the actual format

Express’s 4.x Response API documents that a Buffer sent without a previously set type gets application/octet-stream. For PNG, res.type('png') sets image/png. If you capture JPEG, set image/jpeg instead. The format in Puppeteer and the response header must agree.

Choose what Puppeteer captures

The example captures the current viewport. Puppeteer’s screenshot options let you change the capture area and appearance:

Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
  • SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
  • fullPage: true captures the whole page rather than only the viewport; its documented default is false.
  • clip captures a specified region.
  • omitBackground: true omits the default background for transparency; its documented default is false.
  • type selects a supported output format. PNG is the default.

For example, to capture the full page as PNG, change the screenshot call to await page.screenshot({ type: 'png', fullPage: true }). Decide whether the consumer needs transparency, a full-page image, or a particular region before choosing options and MIME type.

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

Wait for the page you actually need

The example uses waitUntil: 'networkidle2', a navigation option demonstrated in Puppeteer’s guide. It is not a universal readiness signal: pages with ongoing network activity or delayed client-side rendering may need a page-specific condition instead. If the relevant content appears only after rendering, wait for a selector or another readiness condition in your application before calling screenshot(). Avoid treating a timeout or navigation completion alone as proof that the desired content is ready.

Rank #3
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
  • Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
  • Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
  • In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
  • Ultra-thin bezels: Maximize your viewing experience with thin bezels.

Return in-memory bytes or serve a saved image

  • In-memory response: Use res.type(...).send(Buffer.from(image)) when the route generates and returns the screenshot in the same request.
  • Saved file: Use Express res.sendFile() if the generated image is written to disk. Constrain the file path to a trusted root; do not let a caller choose an unchecked path.
  • Static assets: Use express.static() for images in a known directory that are already static assets.

Browser lifecycle, reliability, and load

The sample launches a new browser for each request because it makes the lifecycle easy to see. That can be costly at higher request volumes; no performance benchmark establishes a particular strategy as fastest. A production service may instead reuse a managed browser process and create an isolated page or context for each request. Whichever design you choose, ensure cleanup happens after both successful captures and failures.

The route passes errors to Express with next(error). If you add custom error handling, do not try to send a second response once screenshot bytes have begun: Express exposes res.headersSent so an error handler can check whether headers were already sent. Also set application-appropriate timeouts and concurrency limits; the API references do not prescribe values for your workload.

Rank #4
Sale
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor | 100Hz, Game Mode, Advanced Eye Comfort, HDMI and D-sub Ports (LS27D366GANXZA)
  • CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
  • SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
  • MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
  • KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
  • INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient

Troubleshooting

  • The browser displays a download or generic binary response: Set the type before send(). Use res.type('png') for PNG or res.type('jpeg') for JPEG.
  • The image is corrupted: Keep the response binary. Send the Buffer returned by Buffer.from(image), not a text-encoded or JSON-transformed version.
  • The screenshot is blank or misses content: The page may not be ready when capture runs. Choose a suitable navigation condition, then wait for the selector or application-specific readiness signal for the content you need.
  • The request fails or hangs during navigation: Check whether the target is reachable from the server and whether your chosen navigation condition suits that page. Handle errors and ensure the browser closes in finally.
  • Browser processes remain after errors: Put cleanup in a finally block, as in the example, rather than closing the browser only on the success path.
  • Later errors cause a headers-sent error: Avoid sending a second response after the screenshot response has started; check res.headersSent in custom error handling.
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 returns an image or PDF from one GET request, and its parameters also work with names used by other screenshot APIs. Cookie banners are accepted and removed, along with known consent platforms, newsletter popups, and chat widgets; each cleanup step can be turned off. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers identify the page verdict and billing status. It also provides an MCP server with screenshot, page-info, and PDF tools for AI agents.

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.

For example, this cURL request returns a WebP screenshot of Stripe:

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 the request options. One thousand screenshots per month are free with no card; paid plans start at $5 for 3,000. Learn about ScreenshotNeo or sign up for the free plan.

Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
  • 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
  • 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.

Frequently Asked Questions

Can I return a screenshot as JSON?

You can, but this route returns raw image bytes with an image MIME type, which is the direct choice when the client needs an image response.

Does this example use Express 5?

It uses familiar Express route and response APIs; the cited response reference is for Express 4.x. Check the documentation for the major version used by your application.

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 *

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

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
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.