Serving Static Files

Static files are files that are not dynamic and aren't rendered with a template engine. These are files that should be served as-is, without modification. Some examples of static files are HTML, CSS, and JavaScript files that should be sent directly to the browser. Images such as JPGs and PNGs are also static.

It would be really unfortunate if we had to define a route and use res.sendFile for every static file in our application. Fortunately, using vite, our files can be loaded automatically, just by including them in a public directory.

If we were not using vite, Express makes it really easy by giving us a way to define a folder in which to put all of our static files.

import * as Path from 'node:path'
import express from 'express'
const server = express()
// the full path to our static folder, which we've called 'public'
const publicFolderPath = Path.resolve('./public')
server.use(express.static(publicFolderPath))

Our public folder structure might look something like this:

public
├──images
│  ├──logo.png
│  └──puppy.jpg
├──styles
│  └──main.css
├──scripts
│  └──tiles.js
└──index.html

This would create paths on our web application like:

  • http://localhost:3000/images/logo.png
  • http://localhost:3000/styles/main.css
  • http://localhost:3000/scripts/tiles.js

Notice how public is not part of the URL even though the images, styles and scripts folders are inside public. To reference these files from your HTML files, you can use an absolute path, /images/logo.png. (A leading / means the 'root' path or base directory.)