← Back to Node.js Course | Chapter 7: Express.js Basics | Lesson 5 of 7

Static files

express.static serves files from a folder, such as images, CSS and client-side JavaScript.

In this page:

  1. Static files
Syntax
javascript
app.use(express.static('public'));

Static files

app.use(express.static("public")) maps files in the public folder to URLs, so public/logo.png becomes /logo.png. You can add a URL prefix as the first argument. Place it before dynamic routes so files are found first.

Note: Use path.join(__dirname, "public") for a reliable path.

Example: Static files

bash
const express = require("express");
const path = require("path");
const app = express();
app.use(express.static(path.join(__dirname, "public")));
app.use("/assets", express.static(path.join(__dirname, "assets")));
app.listen(3000);
// public/index.html  ->  GET /index.html
// assets/logo.png    ->  GET /assets/logo.png

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Using a path relative to the wrong working directory
  2. Exposing sensitive folders
  3. Not setting cache headers in production
Chapter Summary
  • express.static serves a folder
  • Files map to URLs
  • Add a prefix if needed
  • Use absolute paths
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.