Serve Static Files in Node.js with Express

OpenJavaScript 0

Last updated: February 5, 2023.

The Express framework for Node.js can be used to serve static resources to users.

Doing so, you can host a static HTML website or a Single Page Application – also in conjunction with a REST API.

How to serve static files

First, in a new project folder, create a new Node project and install Express:

cd C:/path/to/project/folder
npm init --y
npm i express

Now, inside your app.js file in the project root directory, you can start serving static files from a subfolder of your choosing using the following syntax:

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

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

app.listen(port, () => {
  console.log(`App listening  on port ${port}`);
})

Calling express.static('public') within app.use() applies as a global setting that static files should be served from the folder named public within the root directory.

Like this, static files will be served from the root URL (the path will not include /public on the frontend):

http://localhost:3000/index.html
http://localhost:3000/css/styles.css
http://localhost:3000/js/script.js

To make the static files accessible from within a subdirectory on the frontend, include a path as a first argument when calling app.use().

In the following example, files will be accessible at http://localhost:3000/static:

app.use('/static', express.static('public'));
http://localhost:3000/static/index.html
http://localhost:3000/static/css/styles.css
http://localhost:3000/static/js/script.js

It is possible to serve files to the same frontend location from multiple directories:

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

In this case, the directories will be searched in the order they appear for static files.

Best practice: use absolute path to static files folder

To be on the safe side, it is best to set the location of a static files directory relative to the folder where app.js was launched. Otherwise, the path to the directory is realtive to the current command line working directory. This is often the location of app.js, but not always (e.g. if you launch from a subfolder such as node files/app.js).

You can do this by using the absolute path to app.js (available as __dirname in Node.js). And joing to this the from where your static files are located using path.join(). The path module takes care of any unpredictable trailing slashes when joining to create the path:

const path = require('path');

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

Adding a 404 error message

To add a 404 page, you can write some basic middleware that will run after Express has tried to serve a static file.

In this case, standard 404 response is served to the user:

app.use(function(req, res) {
  res.status(400);
  return res.send('404 Error: Resource not found');
});

Boilerplate code for serving static files

A complete boilerplate setup for serving static files would be the following:

const express = require('express');
const path = require('path');
const app = express();
const port = 3000;

app.use(express.static(path.join(__dirname, 'public')));

app.use(function(req, res) {
  res.status(400);
  return res.send(`

404 Error: Resource not found

`); }); app.listen(port, () => { console.log(`App listening on port ${port}`); })

Serving a HTML website or Single Page Application

You can use this setup to host a static website or application.

All you need to do in this case is place your index.html file and all its dependencies in the directory you have chosen to serve static files.

Below is an example of some boilerplate code that would serve static files to the root URL from a public folder:

const express = require('express');
const path = require('path');
const app = express();
const port = 3000;

app.get('/api', (req, res) => {
  res.json(`HTTP GET request received`);
})

app.use(express.static(path.join(__dirname, 'public')));

app.use(function(req, res) {
  res.status(400);
  return res.send(`

404 Error: Resource not found

`); }); app.listen(port, () => { console.log(`App listening on port ${port}`); })

Related posts