Serving Static Files

To serve static files such as images, CSS files, and JavaScript files, use theexpress.static built-in middleware function in Express.

1. Basic Usage

Pass the name of the directory from which you want to serve static assets. Conventionally, this folder is named public.

app.use(express.static('public'));

Now, you can load the files that are in the public directory:

  • http://localhost:3000/images/logo.png
  • http://localhost:3000/css/style.css
  • http://localhost:3000/js/app.js

2. Virtual Path Prefix

You can create a "virtual" path prefix (where the path does not actually exist in the file system) for files that are served by Express.

app.use('/static', express.static('public'));

Now, you access the files with the /static prefix:

  • http://localhost:3000/static/images/logo.png

3. Using Absolute Paths

It is safer to use the absolute path of the directory you want to serve, especially if you run your node app from another directory.

const path = require('path');
app.use('/static', express.static(path.join(__dirname, 'public')));
Tip: You can use express.static multiple times if you want to serve files from multiple directories. Express will look for files in the order you defined the middleware.