🚀 Express.js
Beginner
How do you serve static files in Express.js?
Answer
Use the built-in express.static() middleware to serve static files (HTML, CSS, JavaScript, images) from a directory. app.use(express.static('public')) serves files from the public folder — a file at public/images/logo.png is accessible at /images/logo.png. You can mount it at a URL prefix: app.use('/static', express.static('public')). Use path.join(__dirname, 'public') for a reliable absolute path. The middleware sets appropriate Cache-Control and ETag headers automatically for browser caching. In production, serving static files through a CDN or Nginx is preferred over Express for better performance.
Previous
What are query parameters in Express.js?
Next
What is the difference between req.params, req.query, and req.body?