Nutrient

Home

SDK

Software Development Kits

Low-Code

IT Document Solutions

Workflow

Workflow Automation Platform

DWS API

Document Web Services

T
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Company

About

Team

Careers

Contact

Security

Partners

Legal

Resources

Blog

Events

Try for free

Contact Sales
Contact sales
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

products

Web

Web

Document Authoring

AI Assistant

Salesforce

Mobile

iOS

Android

visionOS

Flutter

React Native

MAUI

Server

Document Engine

Document Converter Services

.NET

Java

Node.js

AIDocument Processing

All products

solutions

USECASES

Viewing

Editing

OCR and Data Extraction

Signing

Forms

Scanning & Barcodes

Markup

Generation

Document Conversion

Redaction

Intelligent Doc. Processing

Collaboration

Authoring

Security

INdustries

Aviation

Construction

Education

Financial Services

Government

Healthcare

Legal

Life Sciences

All Solutions

Docs

Guides overview

Web

AIAssistant

Document Engine

iOS

Android

visionOS

Java

Node.js

.NET

Document Converter Services

Downloads

Demo

Support

Log in

Resources

Blog

Events

Pricing

Try for free

Free Trial

Company

About

Security

Partners

Legal

Contact Sales
Contact Sales
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

products

Products overview

Document Converter

Document Editor

Document Searchability

Document Automation Server

Integrations

SharePoint

Power Automate

Nintex

OneDrive

Teams

Window Servers

solutions

USECASES

Conversion

Editing

OCR Data Extraction

Tagging

Security Compliance

Workflow Automation

Solutions For

Overview

Legal

Public Sector

Finance

All Solutions

resources

Help center

Document Converter

Document Editor

Document Searchability

Document Automation Server

learn

Blog

Customer stories

Events

Support

Log in

Pricing

Try for free

Company

About

Security

Partners

Legal

Contact Sales
Contact Sales
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Product

Product overview

Process Builder

Form Designer

Document Viewer

Office Templating

Customization

Reporting

solutions

Industries

Healthcare

Financial

Manufacturing

Pharma

Education

Construction

Nonprofit

Local Government

Food and Beverage

Departments

ITServices

Finance

Compliance

Human Resources

Sales

Marketing

Services

Overview

Capex-accelerator

Process Consulting

Workflow Prototype

All Solutions

resources

Help center

guides

Admin guides

End user guides

Workflow templates

Form templates

Training

learn

Blog

Customer stories

Events

Support

Pricing

Support

Company

About

Security

Partners

Legal

Try for Free
Contact Sales
Try for Free
Contact Sales
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Services

Generation

Editing

Conversion

Watermarking

OCR

Table Extraction

Pricing

Docs

Log in

Try for Free
Try for Free

Free trial

Blog post

Serving PDFs with Express.js

William Meleyal William Meleyal

Table of contents

  • Getting started
  • Opening PDFs
  • Downloading PDFs
  • Viewing PDFs
  • Conclusion
  • FAQ
Illustration: Serving PDFs with Express.js

This post will cover how to serve PDF files with Express.js, the de facto web framework for Node.js. We’ll show three different ways you can serve files and explain how to use the Content-Disposition header to tell the browser how to handle a file on the client side.

Getting started

First, scaffold out a simple Express app:

mkdir pdf-express && cd pdf-express

npm init -y
touch app.js

sed -i '' 's/index/app/g' package.json

mkdir public views

npm install express ejs

npm install nodemon -D

Here, you’ve downloaded express and ejs as dependencies. Also, you’ve installed nodemon as a development dependency. nodemon is a utility that will monitor for any changes in your source and automatically restart your server.

Next, update app.js with some basic boilerplate:

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

app.get('/', (req, res) => res.send('Hello World!'));
app.set('view engine', 'ejs');

app.listen(port, () => console.log(`app listening on port ${port}`));

Finally, add a "start" script to package.json:

"scripts": {
+   "start": "nodemon app.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },

And then test that your app runs successfully:

npm start

If all goes well, you’ll see your “Hello World!” message shown in the browser.

Opening PDFs

Your initial goal is to render a list of PDFs and provide links for opening them using the browser’s default PDF handler.

Example files

First, you’ll need some PDFs to work with. The following command will download a few example files and place them in the public/pdfs folder in your project:

curl https://pspdfkit.com/images/blog/serving-pdfs-with-expressjs/pdfs.zip | tar -xz - -C ./public

Index route

At the index (/) route of your app, you’ll read the files from public/pdfs and show a list of them using a template. Then you’ll update app.js as follows:

const express = require('express');
const ejs = require('ejs');
const path = require('path');
const fs = require('fs');

const app = express();
const dirPath = path.join(__dirname, 'public/pdfs');
const port = 3000;

const files = fs.readdirSync(dirPath).map((name) => {
	return {
		name: path.basename(name, '.pdf'),
		url: `/pdfs/${name}`,
	};
});

app.set('view engine', 'ejs');
app.use(express.static('public'));

app.get('/', (req, res) => {
	res.render('index', { files });
});

app.listen(port, () => console.log(`app listening on port ${port}`));

Index template

Now it’s time to create the views/index.ejs file and update it as follows:

<html>
	<head>
		<title>PDF Express</title>
		<style>
			body {
				margin: 30px;
				background: Aquamarine;
				font: 30px/1.5 'Futura';
				display: flex;
			}
			header {
				margin-right: 80px;
			}
			ul {
				list-style: none;
				padding-left: 0;
			}
		</style>
	</head>
	<body>
		<header>
			<h1>
				<img src="/img/logo.svg" width="200" />
			</h1>
			<ul>
				<% files.map(file => { %>
				<li>
					<a href="<%= file.url %>"><%= file.name %></a>
				</li>
				<% }) %>
			</ul>
		</header>
	</body>
</html>

You can download the logo file here. Place the file under the public directory and create the img folder.

Result

Your files will now be listed on the page.

index

Clicking any of the links will open a file using your browser’s default PDF handler.

open

Downloading PDFs

That’s all good, but what if your requirements change and you want to download a PDF when clicking a link, rather than opening it?

Content-Disposition: attachment

You can instruct the browser to download the file using the Content-Disposition HTTP header. Its default value is inline, indicating the file “can be displayed inside the Web page, or as the Web page.” Setting it to attachment instead tells the browser to download the file.

res.attachment()

Express provides a shortcut for setting the Content-Disposition header with the res.attachment() method.

Note that you can change the name of the file when it’s downloaded by passing the new file name to res.attachment(). This is useful if your file names are opaque (e.g. a digest) and you want to make them more meaningful to the user. It’s worth mentioning that this can also be achieved on the client side with the download attribute of the <a> element.

app.use(
	express.static('public', {
		setHeaders: (res, filepath) =>
			res.attachment(`pdf-express-${path.basename(filepath)}`),
	}),
);

Setting the header manually

res.attachment() is just shorthand for setting the header manually. The code below achieves the same result:

app.use(
  express.static("public", {
    setHeaders: (res, filepath) =>
      res.set(
        "Content-Disposition",
        `attachment; filename="pdf-express-${path.basename(filepath)}"`
      );
  })
);

Result

With your header in place, clicking any of the links will download a file.

download

Viewing PDFs

Predictably, your requirements have changed again. This time, you’re tasked with showing the PDF inline on your page.

Show route

Start by adding a new show route in app.js that will first find the file from your list using the :file parameter in the URL, and then pass it to your template as the file variable:

app.get('/:file', (req, res) => {
	const file = files.find((f) => f.name === req.params.file);
	res.render('index', { files, file });
});

You also need to revert your changes to the Content-Disposition header. You can change the value from attachment to inline, or else remove the header-related code and the response will default back to inline.

Index template

For this example, reuse the views/index.ejs template and add a conditional check to render the file if it’s present. Typically, you’d want to move this to a dedicated show template and move the shared content to a layout.

You can use a really neat trick combining Content-Disposition: inline with the <embed> tag to prompt the browser to show the file inside the <embed> tag:

<ul>
   	<% files.map(file => { %>
   	<li>
      	<a href="<%= file.name %>"><%= file.name %></a>
   	</li>
   	<% }) %>
</ul>
</header>
   <section>
   	<% if((typeof(file) !== 'undefined')) { %>
      <embed src="<%= file.url %>" width="1000px" height="100%" /> <% } %>
   </section>

Result

With that, your PDF is rendered using the browser’s PDF handler, but right inside your page!

show

Conclusion

This post looked at three different ways to provide PDF files via Express:

  1. Serving a file and letting the browser decide how to show it.

  2. Instructing the browser to download the file with the Content-Disposition: attachment header.

  3. Combining Content-Disposition: inline with the <embed> tag to show the file inline on your page.

All three methods can come in handy, depending on your use case. And if you want to offer functionality that’s more advanced than simply downloading or showing PDFs, I’d be remiss if I didn’t mention our awesome PDF SDK, Nutrient Web SDK.

FAQ

How can I serve PDFs in an Express.js application?

You can serve PDFs using Express’s static middleware by placing the files in a public directory and serving them with express.static().

How do I make a PDF download instead of opening in the browser?

You can use the Content-Disposition header set to attachment or the res.attachment() method to trigger downloads.

Can I display PDFs inline on a webpage using Express.js?

Yes, you can use the <embed> tag in combination with Express to display PDFs inline within the browser.

What is the role of res.attachment() in Express.js?

res.attachment() is a method that sets the Content-Disposition header to ensure the browser downloads the file instead of opening it.

Is there a way to list all available PDF files dynamically in Express.js?

Yes, you can use Node.js’s fs.readdirSync() method to read files from a directory and generate a list dynamically.

Explore related topics

Web Express.js JavaScript How To
Free trial Ready to get started?
Free trial

Related articles

Explore more
SDKTUTORIALSWebJavaScriptHow ToPDFRenderingViewing

What is a vector PDF? Understanding the difference between vector, raster, and text elements in PDF documents

SDKTUTORIALSWebJavaScriptHow ToPDFRenderingViewing

The ultimate guide to PDF rendering vs. PDF viewing (and when each is applicable)

SDKTUTORIALSWebPDF.jsJavaScriptNutrient Web SDK

PDF.js vs. Nutrient Web SDK: A comprehensive PDF viewer comparison

Company
About
Security
Team
Careers
We're hiring
Partners
Legal
Products
SDK
Low-Code
Workflow
DWS API
resources
Blog
Events
Customer Stories
Tutorials
News
connect
Contact
LinkedIn
YouTube
Discord
X
Facebook
Popular
Java PDF Library
Tag Text
PDF SDK Viewer
Tag Text
React Native PDF SDK
Tag Text
PDF SDK
Tag Text
iOS PDF Viewer
Tag Text
PDF Viewer SDK/Library
Tag Text
PDF Generation
Tag Text
SDK
Web
Tag Text
Mobile/VR
Tag Text
Server
Tag Text
Use Cases
Tag Text
Industries
Tag Text
Resources
Blog
Tag Text
Events
Customer Stories
Tag Text
Tutorials
Tag Text
Features List
Tag Text
Compare
Tag Text
community
Free Trial
Tag Text
Documentation
Tag Text
Nutrient Portal
Tag Text
Contact Support
Tag Text
Company
About
Tag Text
Security
Tag Text
Careers
Tag Text
Legal
Tag Text
Pricing
Tag Text
Partners
Tag Text
connect
Contact
Tag Text
LinkedIn
Tag Text
YouTube
Tag Text
Discord
Tag Text
X
Tag Text
Facebook
Tag Text
low-code
Document Converter
Tag Text
Document Editor
Tag Text
Document Automation Server
Tag Text
Document Searchability
Tag Text
Use Cases
Tag Text
Industries
Tag Text
Resources
Blog
Tag Text
Events
Customer Stories
Tag Text
Support
Help Center
Tag Text
Contact Support
Tag Text
Log In
Tag Text
Company
About
Tag Text
Careers
Tag Text
Security
Tag Text
Legal
Tag Text
Pricing
Tag Text
Partners
Tag Text
connect
Contact
Tag Text
LinkedIn
Tag Text
YouTube
Tag Text
Discord
Tag Text
X
Tag Text
Facebook
Tag Text
Popular
Approvals matrix
Tag Text
BPMS
Tag Text
Budgeting process
Tag Text
CapEx approval
Tag Text
CapEx automation
Tag Text
Document approval
Tag Text
Task automation
Tag Text
workflow
Overview
Tag Text
Services
Tag Text
Industries
Tag Text
Departments
Tag Text
Resources
Blog
Tag Text
Events
Customer Stories
Tag Text
Support
Help Center
Tag Text
FAQ
Tag Text
Troubleshooting
Tag Text
Contact Support
Tag Text
Company
About
Tag Text
Careers
Tag Text
Security
Tag Text
Legal
Tag Text
Pricing
Tag Text
Partners
Tag Text
connect
Contact
Tag Text
LinkedIn
Tag Text
YouTube
Tag Text
Discord
Tag Text
X
Tag Text
Facebook
Tag Text
DWS api
PDF Generator
Tag Text
Editor
Tag Text
Converter API
Tag Text
Watermark
Tag Text
OCR
Tag Text
Table Extraction
Tag Text
Resources
Log in
Tag Text
Help Center
Tag Text
Support
Tag Text
Blog
Tag Text
Company
About
Tag Text
Careers
Tag Text
Security
Tag Text
Pricing
Tag Text
Legal
Privacy
Tag Text
Terms
Tag Text
connect
Contact
Tag Text
X
Tag Text
YouTube
Tag Text
Discord
Tag Text
LinkedIn
Tag Text
Facebook
Tag Text

Copyright 2025 Nutrient. All rights reserved.

Thank you for subscribing to our newsletter!

We’re thrilled to have you join our community. You’re now one step closer to receiving the latest updates, exclusive content, and special offers directly in your inbox.

This builtin is not currently supported: DOM

PSPDFKit is now Nutrient. We've consolidated our group of trusted companies into one unified brand: Nutrient. Learn more

This builtin is not currently supported: DOM

PSPDFKit is now Nutrient. We've consolidated our group of trusted companies into one unified brand: Nutrient. Learn more

This builtin is not currently supported: DOM

New Feature Release. Tap into revolutionary AI technology to instantly complete tasks, analyze text, and redact key information across your documents. Learn More or View Showcase

This builtin is not currently supported: DOM

Aquaforest and Muhimbi are now Nutrient. We've consolidated our group of trusted companies into one unified brand: Nutrient. Learn more

This builtin is not currently supported: DOM

Integrify is now Nutrient. We've consolidated our group of trusted companies into one unified brand: Nutrient. Learn more

This builtin is not currently supported: DOM

Join us on April 15th. Join industry leaders, product experts, and fellow professionals at our exclusive user conference. Register for conference