# How to serve static resources in Express

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Apr 10, 2019, updated Oct 1, 2022. Topics: Node.js, Express.js.
Canonical URL: https://attacomsian.com/blog/static-resources-express

> A quick article to learn how to serve static resources in a Node.js and Express.js web application.

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:

```typescript
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`:

```typescript
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:

```plaintext
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:

```typescript
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:

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

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

```plaintext
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.
