Serving static files in Express
knowing the built-in static middleware.
app.use with express.static pointing at the public directory, files served relative to that root, often combined with an absolute path.
WHAT THIS TESTS This checks whether you know Express ships a built-in solution for serving assets rather than requiring manual routes, and whether you handle the path robustly.
A GOOD ANSWER COVERS Express provides the express.static middleware for serving files from a folder. You register it with app.use(express.static('public')), and Express then serves any file in that directory at a URL path relative to the directory root: public/css/style.css becomes available at /css/style.css, with no extra routing code. Because a relative path is resolved against the process current working directory, which can vary by how you launch the app, the robust form uses an absolute path: app.use(express.static(path.join(__dirname, 'public'))). You can mount it under a virtual prefix, such as app.use('/static', express.static('public')), so files appear under /static. The middleware also sets caching headers and handles content types automatically.
COMMON WRONG ANSWERS Writing an individual app.get route for each asset, which is unmaintainable. Using a bare relative path and being surprised when files are not found because the working directory differs. Confusing the filesystem path argument with the URL prefix.
LIKELY FOLLOW-UPS How do you mount static files under a URL prefix. Why use __dirname here. How would you set cache-control or maxAge on static assets.
ONE CONCRETE EXAMPLE With app.use(express.static(path.join(__dirname, 'public'))) and a file at public/js/app.js, a browser request to /js/app.js returns that script with the correct Content-Type, no per-file route required. Adding app.use('/assets', express.static(path.join(__dirname, 'public'))) would instead expose it at /assets/js/app.js.
Read the original → expressjs.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.