Skip to content

File Uploads and Serving Static Files

Beginning of the lesson

File Uploads and Serving Static Files

Let users send files to your server, and send files back without exhausting memory

Big Idea: Real apps move more than text. Users upload avatars, PDFs, and spreadsheets; your server ships back images, stylesheets, and downloads. Doing this well means three tools working together: express.static to serve assets, multer to receive multipart uploads, and streams to move large files piece by piece instead of loading them whole.
By the end you will be able to:
  • serve a folder of assets with express.static,
  • explain what multipart/form-data is and why express.json() cannot read it,
  • receive single and multiple uploads with multer (disk vs memory storage),
  • send files back with res.sendFile, res.download, and a stream.

1. Serving static files with express.static

A static file is one the server sends back unchanged: an image, a CSS file, a font, a downloadable PDF. You do not want to write a route for every one of them. Express ships a built-in middleware, express.static, that maps a folder on disk to URLs automatically.

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

// Serve every file inside ./public at the site root
app.use(express.static(path.join(__dirname, 'public')));

app.listen(3000);

Now a file at public/logo.png is reachable at http://localhost:3000/logo.png with no route of your own. Express also sets the correct Content-Type, supports caching headers, and answers HTTP range requests for you.

Often you want assets under a URL prefix so they do not collide with your API routes. Pass a mount path as the first argument:

// Mount the same folder under a URL prefix
app.use('/static', express.static('public'));

// public/logo.png  ->  http://localhost:3000/static/logo.png
// public/css/app.css -> http://localhost:3000/static/css/app.css
Safety note: only expose folders meant to be public. Never point express.static at your project root, or you would hand out your source code and node_modules.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers