Serving Files

At its core, HTTP is a file transfer protocol.


In earlier lessons, you may have used the node-static package, or the live-server VSCode plugin to serve your HTML, JS, CSS, images, etc...

node-static, and live-server are standalone static file servers built in NodeJS

They're useful for local development but not great for production deployments

static file server in Express


LAB: static file server

const express = require('express')
const app = express()
const port = process.env.PORT || 5000


app.listen(port, () => console.log(`Example app listeningport ${port}!`))
  "scripts": {
    "start": "node app.js"


The good news: your web server can now serve static files to its clients!

The bad news: your web clients can now see any files they like in your project

(including your server source code and configuration files, which may include secrets like passwords)

LAB: Hack Your Own Server

open a web browser and visit http://localhost:5000/package.json

package.json should probably be more secret than that :-)

Solution: public directory

To keep server-side code and configuration files secret, most web apps have a public directory containing static files

This is one major difference between static sites and web apps -- since some of your code runs on your server, and some runs on your client's browser, your project directory structure needs to segregate client-side files from server-side files

Now you can put HTML, CSS, PNG, and .js files inside /public where your clients can fetch them as needed

Note that the URL path /index.html maps directly to the filesystem path static-server/public/index.html


A little historical note...

Now open a web browser and visit http://localhost:5000/ and you will see the contents of index.html ("Hello in HTML") even though your request did not contain the words "index" or "html", just the path /


Viewing Headers

TIP: open the browser DevTools and click on the Headers sub-tab to see Content-Type and other headers:


404 Not Found and other status codes

open a web browser and visit http://localhost:5000/oops.html

if there is an error loading the file (in this case, there is simply no file by that name),

the server must send the correct status code

Note: even though there is an error, the server still returns a body and content-type for display to the user.

In this case, we just see Express' boring default error page, but it's possible to get very creative with web site error pages.

Lab: Create a 404 page

Go back to your "static-server" directory, and let's make a custom 404 page!

 Previous Next