How to Serve HTML Files in Express: Simple Guide
To serve HTML files in Express, use the
express.static middleware to serve files from a folder or use res.sendFile() to send a specific HTML file. Place your HTML files in a public folder and configure Express to serve them easily.Syntax
There are two main ways to serve HTML files in Express:
express.static('folder'): Serves all static files (HTML, CSS, JS) from the specified folder.res.sendFile(path): Sends a specific HTML file as a response.
Use express.static for multiple files and res.sendFile for sending one file dynamically.
javascript
const express = require('express'); const app = express(); // Serve all files in 'public' folder app.use(express.static('public')); // Send a specific HTML file app.get('/', (req, res) => { res.sendFile(__dirname + '/public/index.html'); });
Example
This example shows how to serve an HTML file named index.html located in a public folder. It uses express.static to serve all static files and res.sendFile to send the main HTML file on the root URL.
javascript
const express = require('express'); const path = require('path'); const app = express(); const PORT = 3000; // Serve static files from 'public' folder app.use(express.static(path.join(__dirname, 'public'))); // Route to send index.html explicitly app.get('/', (req, res) => { res.sendFile(path.join(__dirname, 'public', 'index.html')); }); app.listen(PORT, () => { console.log(`Server running at http://localhost:${PORT}`); });
Output
Server running at http://localhost:3000
Common Pitfalls
- Not using
path.joinor absolute paths can cause errors on different operating systems. - Forgetting to place HTML files in the folder served by
express.staticmeans files won't be found. - Using
res.sendFilewithout the correct absolute path leads to "file not found" errors. - Not calling
next()or missing middleware order can block static file serving.
javascript
/* Wrong way: Using relative path without path.join */ app.get('/', (req, res) => { res.sendFile('public/index.html'); // May cause error }); /* Right way: Use path.join for absolute path */ const path = require('path'); app.get('/', (req, res) => { res.sendFile(path.join(__dirname, 'public', 'index.html')); });
Quick Reference
| Method | Purpose | Usage Example |
|---|---|---|
| express.static | Serve all static files in a folder | app.use(express.static('public')) |
| res.sendFile | Send a specific HTML file | res.sendFile(path.join(__dirname, 'public', 'index.html')) |
Key Takeaways
Use express.static middleware to serve all static HTML files from a folder easily.
Use res.sendFile with an absolute path to send a specific HTML file in response.
Always use path.join or absolute paths to avoid file path errors.
Place your HTML files inside the folder served by express.static for automatic serving.
Check middleware order to ensure static files are served correctly.