Node.js › Express & Middleware
What is the purpose of the express.static() built-in middleware, and how would you use it to serve a folder of static assets?
BeginnerAnswer
express.static() serves files directly from a specified directory (images, CSS, client-side JavaScript, HTML) without needing a custom route handler for each individual file -- it automatically handles setting appropriate Content-Type headers, supports conditional GET requests via ETags for caching, and maps request URLs directly to file paths within the configured directory.
app.use(express.static('public'));
// A request to /images/logo.png automatically serves ./public/images/logo.png
// without needing an explicit route defined for itReal-world example A single-page application's Express backend serves its built frontend assets (HTML, CSS, JS bundle) directly via express.static('dist'), letting the same Node.js server that handles the API also serve the frontend, without a separate static file server.