Q1. How do you serve static files in Express?
Use the built-in express.static middleware. Example: app.use(express.static('public')). This serves files from the 'public' directory. If you have a file public/images/logo.jpg, it's accessible at http://localhost:3000/images/logo.jpg.
Q2. Can you serve static files from multiple directories?
Yes, you can call express.static multiple times. Example: app.use(express.static('public')); app.use(express.static('uploads')). Express looks for files in the order middleware are defined. If a file exists in both, the first one found is served.
Q3. How do you create a virtual path prefix for static files?
Mount the middleware at a path. Example: app.use('/static', express.static('public')). Now files are accessible under /static, e.g., http://localhost:3000/static/images/logo.jpg. This is useful for organization.
Q4. What types of files can be served as static?
Any file type: HTML, CSS, JavaScript, images (PNG, JPG, SVG), fonts, PDFs, etc. Express automatically sets the correct Content-Type based on file extension. It also handles caching headers (Cache-Control) based on options.
Q5. What are best practices for serving static files?
In production, consider using a reverse proxy like Nginx to serve static files for better performance. Enable caching with maxAge option: express.static('public', { maxAge: '1d' }). Use a CDN for global distribution. Keep static files organized.
