To serve static resources such as images, CSS and JavaScript files, Express provides a built-in middleware express.static. Here is the signature of this function:

express.static(root, [options])

The root parameter refers to the directory from where you want to serve static resources. options object can be used to specify properties for etag generation and to add headers.

For example, use the following code snippet to serve static resources from a directory named assets:

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

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

const port = process.env.PORT || 3000;

app.listen(port, () =>
    console.log(`App is listening on port ${port}.`)
);

Now if you have styles.css and app.js files in assets directory, they can be accessed as following:

http://localhost:3000/styles.css
http://localhost:3000/app.js

Express looks up the files relative to the static directory, so the name of the static directory is not part of the URL.

Multiple Static Directories

Call the express.static function multiple times to serve static assets from more than one directory:

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

Express look ups the files in the same order as you call the middleware function.

Virtual Path Prefix

Virtual path is the path that does not actually exist in the file system. You can create a virtual path prefix for static files by mapping a route to express.static middleware function:

app.use('/static', express.static('assets'))

Now, you have to add /static path prefix to download files from assets directory:

http://localhost:3000/static/styles.css
http://localhost:3000/static/app.js

That's all for serving static resources in an Express application. Express has a built-in epress.static middleware that can be used to serve static files. You can call this function multiple times to serve contents from multiple directories.

Happy Coding 😍

✌️ Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. β˜• Buy me a coffee (cost $3)


Need help to start a new Spring Boot or MEAN stack project? I am available for contract work. Hire me to accomplish your business goals with engineering and design. Let’s talk about your project: hi@attacomsian.com.