Basic

Serving HTML pages

Text is not a page. Learn to serve real HTML files so users get styled, structured content instead of plain strings.

About 2 min of reading

Data Flow

The browser requests a file, express.static looks it up in the public folder, and returns it with the correct content type.
1 Browser requests /css/style.css
↓
2 express.static checks the public folder
↓
3 The file is found on disk
↓
4 Express reads its bytes
↓
5 The file is sent with type text/css
↓
6 The browser applies the styles
Why this works
When you have a choice

Static vs dynamic

Two kinds of content live on a server:

  • **Static*: a fixed file that never changes, like a logo or a stylesheet.
  • **Dynamic*: HTML generated on the fly by code, like a user's profile page.

express.static handles static files fast. Dynamic routes handle the rest. Most apps use both. As the project grows, dynamic HTML is usually built with a templating engine like EJS instead of writing strings.

Examples

Sending a file

Create a folder public with a file index.html. Then serve it:

const path = require('path');

app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

Now your browser receives a full HTML document:

<!doctype html>
<html>
  <head><title>My App</title></head>
  <body>
    <h1>Welcome</h1>
    <p>This is a real page.</p>
  </body>
</html>

res.sendFile is the standard way to hand a static file to the browser. The page now has headings, paragraphs, and real structure.

The public folder

Static assets, HTML, CSS, and images, live in a public folder. Express can serve the whole folder at once:

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

After this one line, any file in public is available by its path:

  • public/css/style.css → /css/style.css
  • public/images/logo.png → /images/logo.png

This is how you attach a stylesheet to every page. Add <link rel="stylesheet" href="/css/style.css"> to your HTML.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Routes and URLs
Previous Lesson
Routes and URLs
Next Lesson
Dynamic pages with EJS
Dynamic pages with EJS →