Skip to content

How to serve static files with Express

Last updated on November 21, 2022

In many instances you are required to serve static assets such as images, CSS files, and JavaScript files, so today we gonna show you, how you can serve static files using the express framework.

For example, If you have the following directories under the public directory
css – which holds the CSS files
js – which holds the js files
images -which holds the images.

By default, Express does not allow you to serve static files. You need to enable it using the built-in express.static() middleware function.

Let’s serve static files of public directory

const express = require('express');
const app = express();
const path = require('path');
app.use(express.static(path.join(__dirname,'pulbic')));
app.listen(3000);

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

It means you can access assets something like the below-shown URLs.

http://localhost:3000/js/app.js,
http://localhost:3000/hello.html, 
http://localhost:3000/images/kitten.jpg,
http://localhost:3000/css/style.css

See above URLs public is not part of the URL; public directory act as the root directory.

Multiple Static Directories

We can also set multiple static assets directories, by calling the express.static middleware function multiple times.

const express = require('express');
const app = express();
const path = require('path');
app.use(express.static(path.join(__dirname,'pulbic')));
app.use(express.static(path.join(__dirname,'files')));
app.listen(3000);

Virtual Path Prefix

You can also provide a path prefix for serving static files. For example, if you want to provide a path prefix like ‘/static’, you need to use the static middleware as shown below.

const express = require('express');
const app = express();
const path = require('path');
app.use('/static',express.static(path.join(__dirname,'pulbic')));
app.use('/static',express.static(path.join(__dirname,'files')));
app.listen(3000);

Now, you can load the files that are in the public directory from the /static path prefix.

http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html
0 0 votes
Article Rating
Subscribe
Notify of
guest

2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments