How to serve static resources in Express

To serve static resources such as images, CSS, and JavaScript files, Express provides a built-in middleware express.static.

The following 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. The 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 the assets directory, they can be accessed as follows:

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

Note: 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 lookups the files in the same order as you call the middleware function.

Virtual Path Prefix

A virtual path is a 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 the express.static middleware function:

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

Now, you have to add the /static path prefix to download files from the 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 express.static middleware that can be used to serve static files. You can call this function multiple times to serve content from multiple directories.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.