Interview Q&A / Node.js

BeginnerQuick answer1 min readUpdated 3 Oct 2026

How do you serve static files such as images and CSS in Express?

SHORT ANSWER

Use the built-in express.static middleware with a folder path. Files inside that folder are served directly by URL, and you can add a prefix and caching options.

Explain it simply

Some files never change per user: logos, stylesheets, a PDF syllabus. Rather than writing a route for each, you tell Express, "This folder is public. Anything inside can be fetched by its filename." It works like a notice board in the corridor: anyone can read what is pinned there.

Example

js
const express = require("express");
const path = require("path");
const app = express();

// public/logo.png is served at GET /logo.png
app.use(express.static(path.join(__dirname, "public")));

// add a URL prefix: public/logo.png at GET /assets/logo.png
app.use("/assets", express.static(path.join(__dirname, "public"), {
  maxAge: "7d",          // browser cache hint
  index: false,          // do not serve index.html for directory URLs
}));

app.listen(3000);

Details:

  • Use an absolute path built with path.join(__dirname, ...). A relative path depends on where you started the process.
  • Only put public files in that folder. Never place .env or database dumps there.
  • If a file is not found, express.static calls next(), so later routes still run.
  • In production, a reverse proxy such as Nginx or a CDN often serves static files faster than Node does.

What to say in the interview

"express.static serves a directory as public files. I give it an absolute path, optionally a URL prefix and cache headers, keep secrets out of the folder, and in production let Nginx or a CDN handle heavy static traffic."

Common mistakes

  • Using a relative folder path that breaks when started from another directory.
  • Exposing a folder that includes config or backup files.

#express#static-files#middleware

Related questions

Practise more Node.js questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Node.js quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.