It’s common to have images, css, js and more assets in a public folder, and expose them to the root level. To do that we just simple use the express.static built-in middleware function in Express static of express

express.static(root, [options]);

This middleware takes two arguments. The first one is the root that specifies the directory from which to serve static assets. The second is optional and is the options for more information about the options argument, see express.static .

Now let’s create a basic server with express and serve the folder public

const express = require('express');
const app = express();


app.listen(3000, () => console.log('Server listening on port 3000'));

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

If you want to use multiple static assets directories, call the express.static middleware function multiple times:


To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by the express.static function, specify a mount path for the static directory, as shown below:

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

However, the path that you provide to the express.static function is relative to the directory from where you launch your node process. If you run the express app from another directory, it’s safer to use the absolute path of the directory that you want to serve:

const path = require('path');

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

Now, you can load the files that are in the public directory from the /static path prefix.