QA
Beginner LevelExpress JS

How does express.static() serve public assets like images, CSS, and client bundles?

❓ Interview Prompt: Explain built-in express.static() middleware, absolute directory paths, MIME types, and static caching headers.

'express.static()' is the built-in middleware for serving static assets (HTML, CSS, JS bundles, images) directly from disk.

Best Practices:

1
Absolute Paths: Always use 'path.join(__dirname, "public")' to ensure reliable file resolution regardless of process launch location.
2
Caching Headers: Pass an options object specifying 'maxAge', 'etag', and 'immutable' to instruct client browsers to cache static assets effectively.

Code Implementation Example

javascript
import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const app = express();

// Serve static assets from /public folder with 1-day maxAge caching
app.use('/static', express.static(path.join(__dirname, 'public'), {
  maxAge: '1d',
  etag: true
}));
💡Serving static public assets with absolute path resolution and caching headers.
🎯 Interview Key Takeaway

Use express.static() with path.join(__dirname, "public") to serve static assets with automatic MIME-type recognition.

#express.static#Static Files#Middleware#Beginner
Back to all Express JS Questions→

More Express JS Interview Questions

Beginner LevelExpress JS

What is Express.js and how does the middleware pipeline work?

Beginner LevelExpress JS

What is the difference between req.params, req.query, and req.body?

Beginner LevelExpress JS

How does express.Router() work for building modular route controllers?