Advertisement
Beginner 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?

Short answer

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…

Save Node.js mock interview
Advertisement
AModel answer
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 it
Real-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.
Likely follow-ups
  • How would you configure a custom cache duration for static assets served this way?
  • What's the security consideration of exposing an entire directory via express.static() if it accidentally contains sensitive files?
Related topics