Chapter 6 of 10
Serving static files โ HTML, CSS, JavaScript, images โ is a common need when building full-stack apps with Express.
// Serve files from the 'public' directory
app.use(express.static("public"));
// GET /logo.png โ serves public/logo.png
// GET /css/style.css โ serves public/css/style.css
// GET / โ serves public/index.html (if it exists)
// Mount at a virtual path prefix
app.use("/assets", express.static("public"));
// GET /assets/logo.png โ serves public/logo.png
// Serve a React build
app.use(express.static(path.join(__dirname, "../client/build")));
// Catch-all for SPA routing (client-side routing)
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "../client/build/index.html"));
});