Static Files in Express.js
Learn how to serve HTML, CSS, JavaScript, images and other static assets using the built-in express.static() middleware in Express.js.
When a user opens a website, the browser needs more than
text from the server. It may also need HTML pages, CSS
stylesheets, JavaScript files, images and fonts.
Express.js provides the express.static()
middleware to make these files available to the browser.
For example, a website developed for CIIT Training Institute may contain a homepage, institute logo, stylesheet and browser-side JavaScript. We can keep these files inside a public directory and configure Express.js to serve them.
1. What Are Static Files?
Static files are files that the server delivers to the client without dynamically generating their contents for each request. They commonly include website assets such as HTML, CSS, JavaScript, images and fonts.
Examples of static files include:
| File Type | Example | Purpose |
|---|---|---|
| HTML | index.html |
Defines the webpage structure. |
| CSS | style.css |
Defines colors, layout and styling. |
| JavaScript | script.js |
Adds browser-side functionality. |
| Images | logo.png |
Displays logos and pictures. |
| Fonts | font.woff2 |
Provides custom typography. |
express.static() to serve
files from a directory. The directory is commonly named
public, but you can choose another name.
2. Why Do We Use Static Files?
A website usually contains multiple resources. Instead of writing a separate route handler for every CSS file, image or JavaScript file, we can configure static middleware to serve files from a directory.
| Requirement | Static File | Result |
|---|---|---|
| Display a webpage | index.html |
Browser displays the HTML page. |
| Apply webpage styling | style.css |
Browser applies the CSS rules. |
| Add button functionality | script.js |
Browser executes the JavaScript. |
| Display an institute logo | images/logo.png |
Browser displays the image. |
3. Understanding express.static()
express.static() is built-in middleware
provided by Express.js. It accepts a directory path and
serves files from that directory when the browser requests
their corresponding URLs.
Basic Syntax
app.use(express.static("public"));
Understanding the Code
| Code | Explanation |
|---|---|
app |
Represents the Express application. |
app.use() |
Registers middleware in the application. |
express.static() |
Creates middleware for serving static files. |
"public" |
Specifies the directory containing the files. |
"public" is resolved from
the Node.js process's current working directory. For a
predictable path relative to the current JavaScript file,
you can use path.join(__dirname, "public")
in a CommonJS project.
4. Project Folder Structure
Before serving static files, create a project folder with
an app.js file and a public
directory. Store the website assets inside that directory.
my-express-app/
│
├── app.js
│
└── public/
├── index.html
├── style.css
├── script.js
└── images/
└── logo.png
In this structure, app.js configures the
Express server, while the public directory
contains the files that the server can serve.
5. How Does Static File Serving Work?
When the browser requests a static file, Express.js checks the configured static directory. If the requested file exists and can be served, Express sends it to the browser.
1. Browser
Requests /style.css.
2. Express Server
Receives the HTTP request.
3. Static Middleware
Looks for the file inside public.
4. Response
Sends the requested file if it is available.
If the requested file is not found, the static middleware allows the request to continue through the remaining middleware and route handlers. If no handler responds, Express normally returns a 404 response.
6. First Program: Serving an HTML File
Let's create a simple Express.js server that serves an HTML page from the public directory.
Step 1: Install Express.js
npm init -y
npm install express
Step 2: Create app.js
const express = require("express");
const app = express();
app.use(express.static("public"));
app.listen(3000, () => {
console.log("Server running at http://localhost:3000");
});
Step 3: Create public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My Express Website</title>
</head>
<body>
<h1>Welcome to CIIT Training Institute</h1>
<p>This page is served using Express.js static middleware.</p>
</body>
</html>
Step 4: Run the Server
node app.js
Expected Terminal Output
Server running at http://localhost:3000
Step 5: Open the Browser
http://localhost:3000/index.html
Expected Browser Output
Welcome to CIIT Training Institute
This page is served using Express.js static middleware.
Explanation:
The static middleware searches the public
directory for index.html and sends the file
to the browser.
7. Serving CSS Files
We can serve CSS files from the same public directory to style our HTML page. The browser requests the CSS file separately using the URL specified in the HTML document.
Step 1: Create public/style.css
body {
font-family: Arial, sans-serif;
background-color: #f0f4f8;
text-align: center;
padding: 40px;
}
h1 {
color: #0d6efd;
}
p {
font-size: 18px;
}
Step 2: Link the CSS File
Add the following link inside the
<head> element of
public/index.html.
<link rel="stylesheet" href="/style.css">
Expected Result
- The webpage background becomes light blue-gray.
- The heading uses blue text.
- The paragraph uses the configured font size.
Because public is configured as the static
directory, the file public/style.css is
available at /style.css.
8. Serving JavaScript Files
Express.js can also deliver JavaScript files that run in the browser. In this example, we add a button and display a message when the user clicks it.
Step 1: Create public/script.js
document.getElementById("myButton")
.addEventListener("click", () => {
alert("Welcome to CIIT Training Institute!");
});
Step 2: Update public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Static Files Example</title>
<link rel="stylesheet" href="/style.css">
</head>
<body>
<h1>Express.js Static Files</h1>
<button id="myButton">Click Me</button>
<script src="/script.js"></script>
</body>
</html>
Expected Result
Open http://localhost:3000/index.html and click
the button. The browser displays the following alert:
Welcome to CIIT Training Institute!
script.js file.
The JavaScript code inside that file executes in the browser,
not on the Express server.
9. Serving Image Files
Images can also be stored inside the public directory.
For example, an institute logo can be stored at
public/images/logo.png.
Folder Structure
public/
├── index.html
├── style.css
├── script.js
└── images/
└── logo.png
Display the Image
Add the following HTML inside the body of
public/index.html.
<img src="/images/logo.png"
alt="CIIT Training Institute Logo"
width="200">
Direct Image URL
http://localhost:3000/images/logo.png
The browser can request the image directly because the
public directory is configured with
express.static().
10. Using a Virtual Path Prefix
Express.js allows us to serve files under a URL prefix. This prefix changes the public URL without requiring us to move the actual files into a different directory.
Example Code
app.use("/static", express.static("public"));
Here, the files inside public are available
through the /static URL prefix.
| Actual File | Browser URL |
|---|---|
public/index.html |
/static/index.html |
public/style.css |
/static/style.css |
public/script.js |
/static/script.js |
public/images/logo.png |
/static/images/logo.png |
Test URL
http://localhost:3000/static/index.html
/static prefix, update the
asset paths in your HTML accordingly. For example, the
stylesheet URL would be /static/style.css.
11. Using an Absolute Directory Path
A relative path such as "public" depends on
the current working directory of the Node.js process.
In a CommonJS project, we can use Node.js's
path module and __dirname to
build a path relative to the current JavaScript file.
Example Code
const express = require("express");
const path = require("node:path");
const app = express();
app.use(
express.static(path.join(__dirname, "public"))
);
app.listen(3000, () => {
console.log("Server running at http://localhost:3000");
});
Understanding the Code
| Code | Explanation |
|---|---|
require("node:path") |
Loads Node.js path utilities. |
__dirname |
Provides the directory of the current CommonJS module. |
path.join() |
Combines path segments into a directory path. |
express.static() |
Serves files from the resolved directory. |
__dirname is not available by default.
13. Practice Task
Create a small Express.js website for CIIT Training Institute. Your application should:
- Serve an HTML homepage from the public directory.
- Apply styling using a separate CSS file.
- Display an institute logo.
- Load a browser-side JavaScript file.
- Serve all assets through a
/staticURL prefix.
http://localhost:3000/static/index.html
12. Important Points
- Static files include HTML, CSS, JavaScript, images and fonts.
-
Use
express.static()to serve files from a directory. -
Use
app.use()to register static middleware. -
The directory name
publicis a convention, not a requirement. -
A virtual path prefix can expose assets under a URL such as
/static. -
Use
path.join(__dirname, "public")for a directory path relative to the current CommonJS file. - Browser-side JavaScript executes in the browser.
- Never place passwords, private keys or sensitive configuration files in a publicly served directory.
Summary
In this lesson, we learned how to serve static files
using Express.js. We configured
express.static() to serve HTML, CSS,
JavaScript and image files from a public directory.
We also learned how to use a virtual path prefix and
resolve a static directory using Node.js path utilities.
Static middleware makes it easier to deliver website
assets without writing a separate route for every file.