Serve HTML
Serve real web pages from your server
⏱ Est. ~10 min
01 · Read
So far your server has returned plain text and JSON. But when you visit real websites, you see styled pages with headings, images, layouts — not raw text.
That's because real web servers serve HTML files. HTML is the language browsers understand and use to display rich, formatted content.
Instead of writing HTML inside JavaScript code (which gets messy fast), we'll put HTML files in a special folder and tell Express to serve them automatically. This is called serving static files — files that don't change per request, sent as-is.
Key points
- Static files are served as-is, with no processing
- The public/ folder is a convention for files accessible to browsers
- Express can serve an entire folder of static files in one line of code
- This is how real websites serve CSS, images, and HTML pages
02 · Real-machine exercise
First, create a public directory inside your project folder. Your static files (HTML, CSS, images) will live here.
mkdir public
03 · Real-machine exercise
Create an index.html file inside the public folder. You can use a text editor — save it as public/index.html inside your project directory. This will be your server's home page.
<!DOCTYPE html>
<html>
<head>
<title>My First Server</title>
<style>
body { font-family: sans-serif; max-width: 600px; margin: 50px auto; }
h1 { color: #333; }
</style>
</head>
<body>
<h1>Welcome to My Server</h1>
<p>This page is being served by Node.js and Express.</p>
<p>I built this myself.</p>
</body>
</html>04 · Quiz
Why do we put HTML files in a public/ folder instead of writing them in JavaScript code?
- JavaScript can't contain HTML strings
- It keeps things organized — HTML files are served as-is, no processing needed
- The public/ folder is faster because it uses a different server
- Browsers can only read folders called 'public'
05 · Real-machine exercise
Now tell Express to serve files from the public folder. Open app.js and add this line after the const app = express(); line, and before any app.get() routes. This one line makes every file in the public/ folder accessible through your server.
app.use(express.static('public'));06 · Real-machine exercise
Stop your server (Ctrl+C), restart it, then visit http://localhost:3000 in your browser. Instead of plain "Hello, World!" text, you should now see a styled HTML page with a heading and paragraphs. That's your index.html being served!
node app.js
http://localhost:3000
07 · Fill in the blank
To serve static files from a folder called 'public', add this middleware: app.use(express._____('public'))
Other lessons in this chapter
⚠ The full interactive experience needs JavaScript. Please enable it and reload.
※ This is an independent Traditional Chinese teaching project — not an official Anthropic product. Claude™ is a trademark of Anthropic, PBC.