Serving Static files in Express framework

Yu Che Liu
2 min readJan 31, 2021

There are several ways to serve static files in Express.

Photo by Florian Olivo on Unsplash

built-in function: static

We can use express.static built-in middleware function in Express to let users access those files.

The Function is like this:

express.static(root, [options])

The root argument specifies the directory from the server.

For example, if you want to let your homepage folder be one of the routes, you can use app.use(express.static(‘homepage’)); Thus, you can access your homepage file using the URL below: http://localhost:3000/homepage.html.

Ordering:

Express will call the express.static middleware functions in order base on the file. For instance, if there are two same files under the homepage and customer folder, check the code below.

App.use(express.static(‘homepage’));

App.use(express.static(‘customer’));

Express will show the file under the homepage folder first.

Path prefix:

We can also add a virtual path prefix for the file using app.use() function.

App.use(‘/static’, express.static(‘homepage))

The URL will be http://localhost:3000/static/homepage.html

File directory issue: wrong directory

We introduce the expresss.static function to serve the static file. However, the default directory of this function is relative to the directory from where you execute your node command. So it may cause another issue if your application runs in a different location. To solve this issue, we can use path.join to assign the absolute path of the directory. We can use the code like below:

App.use(‘/static’, express.static(path.join(_dirname, ‘homepage’)))

--

--

Yu Che Liu

Java Full stack developer | Google Android Associate developer certified | CompTIA Linux + certified | Teaching Assistant | https://www.linkedin.com/in/yucheliu