Thuta Learning
IntermediateWeb Developmentbeginner

Serving Static Files

Relax. We'll talk through this in plain words — no textbook voice.

Static files are things like HTML, CSS, browser JavaScript, images, and fonts that the server returns as-is instead of generating. In Express, you can serve a static folder as public using the express.static() middleware.

javascript
const express = require('express');
const path = require('path');

const app = express();

app.use(express.static(path.join(__dirname, 'public')));

app.get('/api/message', (req, res) => {
  res.json({ message: 'API and static files can work together.' });
});

app.listen(3000, () => {
  console.log('Static server running at http://localhost:3000');
});

app.use(express.static(...)) lets the browser fetch files in the public folder directly. For example, if you have public/index.html, you'll see it at http://localhost:3000.

You should see
Static server running at http://localhost:3000 Browser shows public/index.html if it exists.

Info

Don't put sensitive files, secret keys, or database backups in the static folder. As the name "public" suggests, it's a place the browser can access.

Easy traps

  • If the public folder path is wrong, files won't be found and you'll get a 404. Using the pattern path.join(__dirname, 'public') helps avoid path issues.

Exercise

You can serve things like frontend build output, landing page assets, uploaded public images, and documentation site files using a static folder.

You'll know it worked when:

Serving Static Files | Thuta Learning