A Next.js link can appear to “download a PDF” while the route actually returns an HTML error page, JSON, or an empty response. Debug the request in four boundaries: verify the HTTP response, verify that Chromium launches, verify that page.pdf() finishes, and verify that the resulting bytes are returned with download headers. The code below uses an App Router Route Handler and returns Puppeteer’s in-memory PDF bytes directly.
Start by proving what the endpoint returned
Open browser developer tools, select the request in Network, and check its status, response headers, and body. You can make the same check from a shell:
curl -i http://localhost:3000/api/report
- Status: a 4xx or 5xx means validation, authorization, route code, or deployment failed before a usable PDF was delivered.
- Content-Type: a successful PDF should be
application/pdf. - Content-Disposition:
attachment; filename="report.pdf"asks the browser to download the response with that suggested name. - Body: a real PDF normally begins with the bytes
%PDF-. A response can still have download headers while containing a Next.js error page or serialized JSON.
Save the response to a file and inspect it with a PDF reader or a hex/text viewer. Do not infer successful generation merely because a download prompt appeared.
Return Puppeteer bytes from an App Router handler
page.pdf() returns PDF data as bytes. Its optional path writes a file relative to the process working directory; it is not required for an HTTP download. Omitting path avoids a temporary-file cleanup problem and lets the route construct a standard Web API Response.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallCrashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minute#1 Best Overall
- 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.
import puppeteer from 'puppeteer'
export const runtime = 'nodejs'
export async function GET() {
let browser
try {
browser = await puppeteer.launch()
const page = await browser.newPage()
await page.goto('https://example.com/report', {
waitUntil: 'networkidle2',
timeout: 30_000,
})
const pdf = await page.pdf({
format: 'A4',
printBackground: true,
})
return new Response(pdf, {
status: 200,
headers: {
'Content-Type': 'application/pdf',
'Content-Disposition': 'attachment; filename="report.pdf"',
'Cache-Control': 'no-store',
},
})
} catch (error) {
console.error('PDF generation failed', error)
return Response.json(
{ error: 'Failed to generate PDF' },
{ status: 500 },
)
} finally {
await browser?.close()
}
}
Place this in a route such as app/api/report/route.ts. Adapt authentication, the target URL, data loading, and error policy to your application. Validate user-controlled URLs and enforce authorization before rendering private pages; otherwise the endpoint could be used to access internal or confidential content.
Next.js App Router handlers use standard Web API Response objects, so headers and a binary body are returned in the same way as any other HTTP endpoint. The nodejs runtime is the appropriate default for a route that launches a local browser; do not move this code to an edge runtime unless your browser architecture explicitly supports it. See Next.js Route Handlers and Route Segment Config.
Choose between memory and a temporary file
In-memory bytes
The example above is simplest: Puppeteer returns a byte buffer and the response sends it immediately. It avoids file permissions and cleanup races, but the PDF occupies memory until the response is handed off. Keep an eye on concurrent requests and unusually large documents.
Disk-backed output
const filePath = '/tmp/report.pdf'
await page.pdf({ path: filePath, format: 'A4' })
// Read the file, return it, and delete it in finally.
Puppeteer documents that path is relative to the process working directory when a relative path is supplied. In serverless deployments, writable storage may be temporary, unavailable, or limited. If you choose this method, use an explicitly writable directory, handle concurrent filenames, close the file before reading it, and delete it in a finally block. It does not make the browser output more valid than the in-memory method.
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Fix the driver behind crashes, sound loss and screen glitches3Repair Windows errors before they cause bigger problemsMake the browser finish before generating the PDF
A blank document usually means the page was printed before the application rendered its content, not that the download header is wrong. Select the wait condition that matches the page:
Rank #2
- 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.
waitUntil: 'domcontentloaded'waits for the initial document.waitUntil: 'networkidle2'waits until network activity is low; applications with polling may never become truly idle.await page.waitForSelector('#report-ready')waits for an application-specific readiness marker.await page.evaluate(() => document.fonts.ready)can make font-dependent layouts deterministic when your page has additional font work.
Puppeteer’s current documentation (version 25.12.0 at the cited access date) says PDF generation waits for fonts by default. PDF options also include a default 30,000 ms timeout, paper format, margins, background graphics, and a path destination. Tune only the wait or option associated with the observed failure; increasing every timeout can conceal a page that never finishes.
Puppeteer prints with print media by default. If your stylesheet hides content under @media print, that is expected. Use print-specific CSS intentionally, and use printBackground: true when background colors or images are part of the design. Color conversion for print can differ from screen rendering; CSS print-color-adjust rules may be needed for exact appearance.
Fix the download link and filename
For a same-origin endpoint, a normal anchor is usually sufficient:
<a href="/api/report">Download report</a>
The server’s Content-Disposition: attachment directive controls download behavior. An HTML download attribute may also influence same-origin links:
<a href="/api/report" download="report.pdf">Download report</a>
Browser behavior for cross-origin resources varies, so test the actual browsers and origin relationship. Quote filenames containing spaces. For internationalized names, MDN documents the filename* parameter and explains that clients supporting both filename and filename* prefer the encoded form; provide a safe ASCII fallback and test it. See MDN’s Content-Disposition reference.
Rank #3
- 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.
Diagnose each failure boundary
The route returns JSON or HTML
Log the incoming parameters, authentication result, and exception. Confirm that the deployed URL maps to the route file you edited. A route that catches an exception and returns JSON with status 500 is behaving correctly; fix the underlying exception rather than adding more download markup.
Chromium will not launch
Local success does not prove production readiness. Linux images and container hosts need the shared libraries, fonts, sandbox configuration, memory, and compatible Chromium binary required by your Puppeteer version. Read the launch error and follow Puppeteer’s official troubleshooting guide. On Linux, its documented check is:
Free tools Windows power users keep installed
One-click scans. No signup required.
ldd chrome | grep not
Run that against the actual Chrome/Chromium executable in the deployed image. Do not copy a dependency list from an unrelated distribution or old browser build. Container base image, operating-system packages, and the browser revision all matter.
Navigation fails
Capture the navigation exception and response status. Check DNS, outbound network policy, TLS certificates, redirects, authentication cookies, and whether the target page blocks automated browsers. A route that cannot reach its own protected page needs an explicit server-side authentication design; adding a longer timeout will not solve a 401, 403, or DNS failure.
page.pdf() times out or produces unsuitable output
Record timestamps around launch, goto, readiness waits, PDF generation, and browser shutdown. Inspect page console errors and verify that the intended content exists before printing. Check fonts, images, lazy-loaded sections, paper size, margins, and print CSS. Keep the timeout tied to the slow stage and ensure the platform’s function duration is longer than the worst legitimate request.
Rank #4
- 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
The function hangs or is killed
Always close the browser in finally. Reuse a browser carefully only if your deployment model supports it; isolate pages and handle crashed processes. Review memory limits, concurrent invocations, and the platform’s maximum duration. Next.js exposes a maxDuration route setting, but the effective limit is platform-defined, so verify the deployed provider’s current limits.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Symptom-to-check table
| Symptom | First checks |
|---|---|
| Tiny or corrupt “PDF” | Inspect status, headers, and the first response bytes; look for JSON or HTML error content. |
| Link opens a page | Confirm Content-Disposition: attachment, same-origin behavior, and the actual response URL. |
| Works locally, fails after deploy | Read launch logs; verify Node runtime, Chromium libraries, fonts, memory, and duration limits. |
| Blank or incomplete pages | Wait for the real readiness condition and inspect browser/application console errors. |
| Fonts or colors differ | Check print media CSS, font loading, printBackground, and print color adjustment. |
| Request times out | Identify whether launch, navigation, font waiting, PDF generation, or the platform limit is responsible. |
Test the endpoint outside the browser
cURL
curl -i -L "http://localhost:3000/api/report" -o report.pdf
Use -i while diagnosing headers; remove it when saving a clean binary file. Add the same authorization header or cookie your application requires.
Python
import requests
r = requests.get('http://localhost:3000/api/report', timeout=90)
print(r.status_code, r.headers.get('content-type'), r.headers.get('content-disposition'))
r.raise_for_status()
open('report.pdf', 'wb').write(r.content)
Node.js
const res = await fetch('http://localhost:3000/api/report');
console.log(res.status, res.headers.get('content-type'), res.headers.get('content-disposition'));
if (!res.ok) throw new Error(await res.text());
const bytes = Buffer.from(await res.arrayBuffer());
require('node:fs').writeFileSync('report.pdf', bytes);
Or skip the browser setup
If your requirement is a clean screenshot or PDF of a URL rather than custom Puppeteer code, ScreenshotNeo provides a website screenshot API and MCP server. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be disabled. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing result.
One GET request returns an image or PDF:
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 documentation for PDF parameters, waiting rules, authentication, signed webhooks, and other options. An MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients. The Free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. Sign up for the free plan.
Keep production behavior predictable
- Pin compatible Node.js, Puppeteer, and browser versions, then rebuild the deployment image when any changes.
- Emit a request ID and stage timings for launch, navigation, readiness, PDF generation, and cleanup.
- Return a non-PDF status and JSON error for failures; never label an error body as
application/pdf. - Set limits for URL input, document size, concurrency, and execution time.
- Decide whether generated documents may be cached. User-specific or sensitive PDFs generally need
Cache-Control: no-store. - Test both a fast static page and the slowest legitimate report in the deployed environment, not only on a laptop.
Frequently asked questions
Does adding download fix a corrupt PDF?
No. It changes browser handling of a successful response. A corrupt file requires inspection of the status, headers, and body and then correction of the failing generation or route stage.
Must I use page.pdf({ path })?
No. Omit path to receive PDF bytes and return them directly. Use a path only when your storage and cleanup design calls for one.
Best Value
- 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.
Can this route run on an Edge runtime?
A route launching a local Puppeteer browser should use a compatible Node.js runtime. Edge support depends on a separate browser service and its API, not on this local-launch pattern.
Why is my PDF different from the screen?
Puppeteer uses print media and waits for fonts by default. Print CSS, background settings, font availability, and color-adjust rules can all change the result.
Frequently Asked Questions
What should the first bytes of a valid PDF be?
A valid PDF normally begins with %PDF-. If the bytes instead contain HTML or JSON, the route returned an error body despite any download headers.
Recommended Free Tools
Where should I look when production launch fails?
Read the Chromium launch error and check the deployed image’s shared libraries, fonts, sandbox, memory, Node runtime, and browser revision using Puppeteer’s troubleshooting guidance.
Quick Recap
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.

