Serve Static Files in Express
Express·2 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.
Serve 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:
serveris an Express instance created using the top-level function exported by theexpressmodule.rootPathis 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_pathNotes:
In its relative form, the path to the root directory is relative to the location where the Node process is launched from and not the server file.
Unlock the program 🚀
Pay once, own it forever.
€79
30-day money-back guarantee
- 13 modules
- 113 lessons with full-code examples
- 29 projects with commented solutions
- All future lesson and project updates
- Lifetime access
By submitting this form, you agree to the Terms & Conditions and Privacy Policy.