Premium lesson

Serving Static Files in Express.js

Express.js·3 min read·Jan 1, 2025

Although the primary objective of an API is to deliver dynamic data to clients, serving static assets like HTML files, PDFs, images, and more can help enhance its overall capabilities, usability, and integration.

For example, your API could serve documentation pages in the HTML format to allow the developers integrating with it to easily understand its endpoints, or it could serve digital products, like e-books.

Serving static files

To serve static files in Express, you can mount the built-in express.static() middleware to the server instance through its use() method:

server.use(express.static(rootPath));

Where:

  • server is an Express instance created using the top-level function exported by the express module.

  • rootPath is a string representing the relative or absolute path to the directory containing the static assets, also called the root directory in this context.

These files will then be available on the root path of the server:

http://server_address[:server_port]/file_path
icon light bulb key

Unlock the Build RESTful APIs in Node.js module

Learn how to build real database-backed and framework-powered RESTful APIs with MySQL, Sequelize, and Express.

You get immediate access to:

  • 37 focused lessons across MySQL, Sequelize, backend, and Express
  • 4 real-world projects with commented solutions
  • Ongoing updates to this bundle
  • Lifetime access to this bundle
Unlock this module