How To Serve Static Files in Express

In this article, we’ll take a look at how to serve static files in Express.

express.static

To serve static files such as HTML, CSS, JavaScript and images, we can use the built-in express.static middleware function in Express.

express.static(root, [options])
  • root arguement is the directory serving static assets.
  • options For example, use the following code to serve images, CSS files, and JavaScript files in a directory named public:

app.use(express.static(‘public’))

Steps to serve static files

In this example, we’ll serve

1. Set up express project

Following this installation structure, we can create our Node project as bellow:

mkdir my-project
cd my-project
npm init -y

We the create index.js to store our Express server:

touch index.js

Install Express as a dependency:

npm install express --save

2. Structure our files

In this example, we have an index.html file, style.css and an image.

To store these files on the client-side, we create a public directory and include them. Our public folder looks like this:

my-project
|- index.js
|- public
  |- hello.png
  |- index.html
  |- style.css

3. Create an Express server

In this step, we require express and write a simple Hello world.

const express = require("express");
const app = express();
const PORT = 3000;

app.get("/", (req, res) => {
  res.send("Hello World");
});

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

4. Serve static file

We’ll want to point to the folder that will serve our static files.

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

Putting it together

const express = require("express");
const app = express();
const PORT = 3000;

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

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

Now we can add any file we want in the public directory, such as about.html, and we go to “/about.html” and will see the server running.