Static files
express.static serves files from a folder, such as images, CSS and client-side JavaScript.
In this page:
Syntax
app.use(express.static('public'));
Static files
app.use(express.static("public")) maps files in the public folder to URLs, so public/logo.png becomes /logo.png. You can add a URL prefix as the first argument. Place it before dynamic routes so files are found first.
Note:
Use path.join(__dirname, "public") for a reliable path.
Example: Static files
const express = require("express");
const path = require("path");
const app = express();
app.use(express.static(path.join(__dirname, "public")));
app.use("/assets", express.static(path.join(__dirname, "assets")));
app.listen(3000);
// public/index.html -> GET /index.html
// assets/logo.png -> GET /assets/logo.png
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Using a path relative to the wrong working directory
- Exposing sensitive folders
- Not setting cache headers in production
Chapter Summary
- express.static serves a folder
- Files map to URLs
- Add a prefix if needed
- Use absolute paths
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: