Serving Static Files in Express

Mar 12, 2020

Express has a built-in middleware for serving static files from a directory. For example, suppose you have a public directory that contains files like images, CSS, and HTML.

$ ls -l public/
total 48
-rw-r--r--  1 ubuntu  ubuntu   1666 Mar 12 14:17 home.css
-rw-r--r--@ 1 ubuntu  ubuntu  17092 Mar 12 14:17 logo.png
$ 

You can use the express.static middleware to make it possible to access files from this folder via HTTP.

const express = require('express');

const app = express();
app.use(express.static('./public'));

app.listen(3000);

With the above script, you can open http://localhost:3000/home.css in your browser and see the CSS file.

Displaying a CSS file in Google Chrome

Serving HTML Files

The static middleware is how you can use Express to serve static HTML files. If you have a vanilla HTML file test.html, you can open that file in your browser and the browser will render the HTML.

Displaying an HTML file in Google Chrome

This means that you can use express.static() to host an entire frontend web app, including JavaScript, CSS, images, and HTML.


Want to become your team's Express expert? There's no better way to really grok a framework than to write your own clone from scratch. In 15 concise pages, this tutorial walks you through how to write a simplified clone of Express called Espresso. Get your copy!

Espresso supports:
  • Route handlers, like `app.get()` and `app.post()`
  • Express-compatible middleware, like `app.use(require('cors')())`
  • Express 4.0 style subrouters
As a bonus, Espresso also supports async functions, unlike Express.

Get the tutorial and master Express today!

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Express Tutorials