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

Preview a PDF by serving the actual PDF bytes from a dedicated Express GET route with Content-Type: application/pdf and an inline content disposition. Navigate to that URL directly or place it in an <iframe>. Keep a separate open/download link because inline rendering depends on the browser, viewer settings, authentication, and deployment path.

Use a dedicated preview endpoint

A preview route should do four things:

  • Authorize the requested document.
  • Resolve a server-controlled identifier to a trusted PDF path or buffer.
  • Send real PDF bytes with the application/pdf media type.
  • Request inline handling with Content-Disposition: inline.

Do not use res.download() for this route. Express documents that method as an attachment transfer and it sets Content-Disposition: attachment, which normally prompts a save dialog. Use it on a separate download action instead.

Preview a PDF file stored on disk

The following route assumes that findAuthorizedPdfPath checks the logged-in user and maps a document ID to a known file. It must not concatenate an unchecked request value into a filesystem path.

const express = require('express');
const app = express();

app.get('/documents/:id/preview', async (req, res, next) => {
  try {
    const filePath = await findAuthorizedPdfPath(req.params.id);
    if (!filePath) return res.sendStatus(404);

    res.type('application/pdf');
    res.set('Content-Disposition', 'inline; filename="document.pdf"');
    res.sendFile(filePath, (err) => {
      if (err && !res.headersSent) next(err);
    });
  } catch (err) {
    next(err);
  }
});

app.listen(3000);

Replace findAuthorizedPdfPath with your database and authorization logic. The filename is supplementary; inline is the disposition value that requests normal media-type processing under RFC 6266. Generate a safe filename rather than copying arbitrary user input into the header.

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.
#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.

Using a fixed root safely

res.sendFile() requires an absolute path unless you supply its root option. A fixed absolute root lets Express validate that a relative filename remains inside that directory:

app.get('/documents/:id/preview', async (req, res, next) => {
  try {
    const relativeName = await findAuthorizedRelativePdfName(req.params.id);
    if (!relativeName) return res.sendStatus(404);

    res.type('application/pdf');
    res.set('Content-Disposition', 'inline; filename="document.pdf"');
    res.sendFile(relativeName, { root: '/srv/app/private-pdfs' }, (err) => {
      if (err && !res.headersSent) next(err);
    });
  } catch (err) {
    next(err);
  }
});

Authorization still belongs in your application. A root directory prevents path escape; it does not decide whether the requester may read a document.

Preview a PDF held in a Buffer

When a PDF comes from object storage, a database, or a PDF-generation library, send the buffer directly and set its type explicitly. Express otherwise defaults a Buffer response to application/octet-stream unless a type has already been set.

app.get('/reports/:id/preview', async (req, res, next) => {
  try {
    const pdf = await loadAuthorizedPdfBuffer(req.params.id);
    if (!pdf) return res.sendStatus(404);

    res.type('application/pdf');
    res.set('Content-Disposition', 'inline; filename="report.pdf"');
    res.send(pdf);
  } catch (err) {
    next(err);
  }
});

Ensure the value really contains PDF bytes. A JSON error, HTML login page, or truncated buffer cannot be rendered merely by assigning a PDF content type.

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.

Embed the route in an HTML page

An iframe uses the browser’s built-in PDF viewer when one is available:

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.
<iframe
  src="/documents/123/preview"
  title="PDF preview"
  width="100%"
  height="720"
></iframe>
<p><a href="/documents/123/preview">Open the PDF separately</a></p>

Keep the outside link. An iframe has no child fallback content when the browser cannot display the document, while a direct link lets the user open or download it in another viewer. Avoid an iframe sandbox configuration that blocks the browser’s PDF viewer. If the page and PDF are on different origins, configure authentication, CORS, and framing policies for your deployment; there is no universal cross-origin setting that fits every application.

Direct navigation versus an iframe

Pattern Use it when What to provide
Direct URL The PDF should occupy its own tab or be opened from a button. A normal link to the preview endpoint and, if needed, a separate download endpoint.
Iframe The preview belongs inside an application page with surrounding controls. An iframe title, a useful height, and an outside link for browsers that cannot embed PDFs.

Both patterns depend on client PDF handling. Content-Disposition: inline requests normal processing; it cannot force a browser or enterprise policy to render PDFs inside a tab.

Why a PDF downloads instead of displaying

The route uses res.download()

Move download behavior to a separate route. For example, keep /preview inline and use res.download() only for an explicit “Download” button.

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

The response says attachment

Inspect the final response headers, including headers added by a reverse proxy or object-storage service. Change the disposition to inline for the preview route.

The media type is wrong

Set application/pdf for both file and Buffer responses. Check that an authentication failure is not returning HTML with a successful-looking status.

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.

The client cannot render PDFs inline

MDN documents navigator.pdfViewerEnabled as a read-only indication of whether the browser can display PDFs when navigating to one:

if (navigator.pdfViewerEnabled === false) {
  document.querySelector('#pdf-warning').textContent =
    'Inline PDF viewing is unavailable; use the open or download link.';
}

This is a capability hint, not a guarantee for every iframe, extension, device, or managed-browser policy. Always retain a usable link.

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

An iframe policy blocks the viewer

Review the iframe’s sandbox, your framing headers, and the origin of the PDF. Remove only the restriction that prevents the viewer, while preserving the security policy your application requires.

Authorization and path-safety checklist

  • Authenticate before resolving the document.
  • Authorize the specific document ID for the current user or service.
  • Map IDs to server-known paths or storage keys; never trust a raw path query parameter.
  • Return 404 when the document is absent, and avoid leaking whether an unauthorized ID exists.
  • Keep private PDFs outside a publicly served static directory.
  • Use a short, safe filename in Content-Disposition.
  • Make sure proxy authentication, cookies, and CORS rules allow the iframe or direct navigation to receive the same authorized response.

Byte ranges, caching, and production behavior

Express sendFile enables byte-range requests by default through its acceptRanges option. A viewer may request only portions of a PDF, but whether that improves startup depends on the browser, reverse proxy, CDN, and storage layer. Verify the production path if range behavior matters; do not promise faster previews solely because the option is enabled.

Choose caching deliberately. Public, immutable documents can use a CDN-friendly cache policy. Private documents need user-aware authorization and cache controls that prevent one user’s response being reused for another. If a proxy rewrites headers, inspect the response at the browser as well as at the Node.js process.

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

Or skip the browser setup

ScreenshotNeo can capture a URL or produce a PDF through one GET request, which is useful when your goal is a rendered document rather than maintaining browser automation yourself. Its API can remove cookie-consent banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, timeouts, failed loads, and cache hits are not billed. It also offers an MCP server so Claude, Cursor, or another MCP client can call take_screenshot, get_page_info, and capture_pdf.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

For PDF output, configure the request for the PDF response using the options documented in the ScreenshotNeo API documentation. The same service supports full-page captures, CSS-selector elements, device and viewport settings, custom CSS and JavaScript, waits, request blocking, headers and cookies, geolocation, transparent backgrounds, resizing, caching TTLs, signed links, asynchronous jobs, webhooks, bulk capture, and a usage API. Every response identifies whether it was a clean page and whether it was billed.

The Free plan includes 1,000 shots per month with no card. Paid plans start at $5 for 3,000 shots; every feature is available on every plan. Create a free ScreenshotNeo account to try it without adding a card.

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

Troubleshooting the endpoint

“Cannot set headers after they are sent”

Do not send a second response from both your route and error handler. Return immediately after res.sendStatus(404), and use the sendFile callback pattern shown above so errors that occur after headers are sent are not forwarded as a second response.

A 404 appears only in production

Log the resolved, authorized storage key and verify the production filesystem or object-storage configuration. Relative paths that worked from a development directory often fail after deployment; use an absolute path or a configured root.

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

The iframe is blank but the direct link works

Compare origins, cookies, CORS, framing headers, and iframe sandbox attributes. A direct navigation may have access to credentials that an embedded request does not.

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.

The PDF opens but shows an error page

Check the first bytes and length of the response, status code, and content type. Confirm that middleware has not converted the Buffer to JSON or compressed a non-PDF error response.

FAQ

Can I guarantee that every browser will show the PDF inline?

No. Inline is a request for normal media-type processing. Viewer availability, extensions, device settings, and enterprise policies can instead cause a download or external application launch.

Should preview and download use the same URL?

They can, but separate routes make intent and headers clearer: inline for preview and attachment for an explicit download.

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

Do I need a PDF JavaScript library in Node.js?

Not to preview an existing PDF. Node.js only needs to authorize and deliver the bytes; rendering is performed by the browser or an external viewer.

Frequently Asked Questions

Can I guarantee that every browser will show the PDF inline?

No. Inline is a request for normal media-type processing. Viewer availability, extensions, device settings, and enterprise policies can instead cause a download or external application launch.

Should preview and download use the same URL?

They can, but separate routes make intent and headers clearer: inline for preview and attachment for an explicit download.

Do I need a PDF JavaScript library in Node.js?

Not to preview an existing PDF. Node.js only needs to authorize and deliver the bytes; rendering is performed by the browser or an external viewer.

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

The Bottom Line

Serve authorized PDF bytes as application/pdf, request Content-Disposition: inline, and expose both an iframe preview and a direct link. Treat inline rendering as best effort, validate paths and permissions, and keep download behavior on a separate attachment route.

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.