How to serve static files in Express

· Category: Node.js

Short answer

Use the built-in express.static middleware to serve files from a directory such as public.

Steps

  1. Create a directory named public in your project root.
  2. Add the middleware: app.use(express.static('public'));.
  3. Place files like style.css inside public.
  4. Access them via http://localhost:3000/style.css.
  5. Use a virtual path prefix: app.use('/static', express.static('public'));.

Tips

  • Use an absolute path with path.join(__dirname, 'public') to avoid issues when the working directory changes.
  • Place the static middleware early so it can short-circuit requests before they hit route handlers.

Common issues

  • If a requested file does not exist, static middleware passes to the next handler instead of sending a 404 by default.
  • MIME types are inferred from file extensions; missing extensions may cause incorrect Content-Type headers.