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.