Serving Static Files in Express Framework

Express provides built-in middleware that allows us to serve static files directly from the file system.

express.static() is the middleware that we can use to serve static files to the user.

Here is the simple example code:

const express = require('express);
const router = express.Router();
const app = express();

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

app.use('
/', router);
app.listen(3000);

Assuming you have files stored in the public folder, you can now make the request to the files from the browser.

Tip: The folder name provided in the express.static() function won’t be included in the file request path.

For example, if the file stored is cat.png in the public folder, then request URL would look like this:

localhost:3000/cat.png

If there is a folder inside the public folder, you need to include that in the path.

localhost:3000/images/cat.png

You can also specify the static paths in the custom middleware. For example, if you want the files to serve by the /files route. You can do so by using the following code.

const express = require('express);
const router = express.Router();
const app = express();

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

app.use('
/', router);
app.listen(3000);

I do recommend that you use a reverse proxy or third-party CDN to serve static files in a production environment instead of doing it in Express.

Checkout more Express tutorials.

Pankaj Kumar
Pankaj Kumar
Articles: 208