Node.js Web Apps With Express Serving static files


Example

When building a webserver with Express it's often required to serve a combination of dynamic content and static files.

For example, you may have index.html and script.js which are static files kept in the file system.

It is common to use folder named 'public' to have static files. In this case the folder structure may look like:

project root
├── server.js
├── package.json 
└── public
    ├── index.html
    └── script.js

This is how to configure Express to serve static files:

const express = require('express');
const app = express();

app.use(express.static('public'));

Note: once the folder is configured, index.html, script.js and all the files in the "public" folder will be available in at the root path (you must not specify /public/ in the url). This is because, express looks up for the files relative to the static folder configured. You can specify virtual path prefix as shown below:

app.use('/static', express.static('public'));

will make the resources available under the /static/ prefix.

Multiple folders

It is possible to define multiple folders at the same time:

app.use(express.static('public'));
app.use(express.static('images'));
app.use(express.static('files'));

When serving the resources Express will examine the folder in definition order. In case of files with the same name, the one in the first matching folder will be served.