Serving Static Files in Express
# Serving Static Files in Express
Welcome to Chapter 16! So far, we have been sending plain text or raw HTML strings back to the browser using res.send(). But a real website has beautiful CSS styling, images, and frontend JavaScript files.
If you put an <img src="logo.png"> in your HTML, the browser will make a GET request to your server for /logo.png. If you don't have a route explicitly set up for that exact image, Express will return a 404 error, and your image will be broken. We solve this using Static Files.
---
1. Introduction
A Static File is a file that the server sends to the client exactly as it is, without modifying it. This includes:
-
HTML files (
.html)
-
Stylesheets (
.css)
-
Client-side JavaScript (
.jsfiles meant for the browser)
-
Images (
.png,.jpg,.svg)
Instead of writing a custom app.get() route for every single image and CSS file on your computer, Express provides a built-in middleware function called express.static() to handle it automatically.
---
2. Learning Objectives
By the end of this chapter, you will be able to:
- Understand the difference between static and dynamic files.
-
Use the built-in
express.static()middleware.
-
Configure a
publicfolder to hold your frontend assets.
- Serve CSS files and link them to HTML.
- Serve images and display them in the browser.
---
3. Beginner-Friendly Explanations
The public Folder
By convention, backend developers create a folder named public (or sometimes assets or static) in the root of their project.
You put all your CSS, frontend JS, and images inside this folder. Then, you tell Express: *"Hey, if anyone asks for a file, look inside the 'public' folder first. If you find it, send it to them automatically!"*
This is much easier than writing 50 different routes for 50 different images.
---
4. Syntax Explanation
Here is how you enable static file serving.
```javascript id="ch16-syntax-1" const express = require('express'); const app = express();
// Use the built-in static middleware // We tell it the name of the folder containing our assets app.use(express.static('public'));
app.listen(3000);
javascript id="ch16-code-1" const express = require('express'); const path = require('path'); const app = express();
// Safe, absolute path static serving app.use(express.static(path.join(__dirname, 'public')));
app.listen(3000);
javascript id="ch16-code-2" // If public/index.html exists, visiting http://localhost:3000/ // will automatically display it. app.use(express.static(path.join(__dirname, 'public')));
javascript id="ch16-code-3" // Files in the public folder are now accessed via /assets/... app.use('/assets', express.static(path.join(__dirname, 'public')));
text static-portfolio/ │── server.js └── public/ ├── index.html ├── css/ │ └── main.css └── images/ └── profile.png (put any image here)
html id="ch16-mini-project-html" <!DOCTYPE html> <html> <head> <title>My Portfolio</title> <link rel="stylesheet" href="/css/main.css"> </head> <body> <div class="container"> <img src="/images/profile.png" alt="Profile Picture"> <h1>Hello, I'm a Backend Developer</h1> <p>This entire page is served using Express Static Middleware!</p> </div> </body> </html>
css id="ch16-mini-project-css" body { background: #1a1a1a; color: white; font-family: sans-serif; text-align: center; } .container { margin-top: 50px; } img { width: 150px; border-radius: 50%; border: 3px solid #00ff88; } h1 { color: #00ff88; }
javascript id="ch16-mini-project-js" const express = require('express'); const path = require('path'); const app = express();
// Serve everything inside the public folder app.use(express.static(path.join(__dirname, 'public')));
app.listen(3000, () => { console.log("Static Portfolio running on http://localhost:3000"); });
javascript
app.use(express.static('public'));
app.use(express.static('files'));
``
Express will look in public first, and if it doesn't find the file, it will look in files.
Q: Why doesn't my CSS update when I refresh the page? A: Browsers aggressively cache static files to save bandwidth. If you change your CSS and don't see it, do a "Hard Refresh" (Ctrl + F5 on Windows, Cmd + Shift + R on Mac) to force the browser to download the new file.
---
16. Summary
- Static files are assets sent directly to the client without modification.
-
Store them in a dedicated folder, conventionally named public
.
-
Use app.use(express.static(path.join(__dirname, 'public')))
to serve them.
- Do NOT include the word "public" in your HTML links (e.g., use /css/style.css`).
- Never put sensitive backend code inside the static folder.
---
17. Next Chapter Recommendation
Serving static HTML is great for simple portfolios. But what if you want to show a user their username when they log in? You can't do that with static HTML. We need dynamic HTML! In Chapter 17: Express.js Templating Engines, we will learn how to use EJS to inject JavaScript variables directly into HTML before sending it to the user.