Nearby lessons

6 of 14

🗂️ How to Serve or Render Static Files in Express JS

📌 What are Static Files?

💡 Understanding Static Files in Express.js

Static files are files that don't change when your application is running. These include HTML, CSS, JavaScript, images, and other assets that your web application serves directly to users.

Express provides a built-in middleware function called express.static() to serve these files easily.

⚙️ What is express.static()?

The express.static() middleware serves static files such as HTML, CSS, JS, and images from a specified directory.

It maps URLs directly to files within a folder on the server, reducing manual configuration.

Requested URLMapped File Path
localhost:8080/index.htmlpublic/index.html
localhost:8080/pic.jpgpublic/pic.jpg

When a client requests a file, Express uses express.static() to locate and deliver it directly, without additional routing.

🧱 Step 1: Project Structure

Create a new project folder with the following structure:

📁 project-folder
 ┣ 📁 public
 ┃ ┣ 📄 index.html
 ┃ ┗ 📄 style.css
 ┗ 📄 index.js
        

⚡ index.js (Server File)

This file sets up the Express server and uses express.static() to serve files from the public directory.

Express.js Server
NODE RUNTIME
const express = require('express');
const path = require('path');
const cors = require('cors');
const app = express();

const publicPath = path.join(__dirname, 'public');

app.use(cors());
app.use(express.static(publicPath));

app.listen(8080, "0.0.0.0", () => {
    console.log("Server running at http://localhost:8080");
});
Browser Output
Server logs

⚙️ What is app.use()?

The app.use() function defines middleware that runs for every request, regardless of the HTTP method (GET, POST, etc.).

In this example, app.use(express.static('public')) serves static files automatically when requested by the browser.

🧠 Test Your Knowledge

5 Questions

Progress: 0 / 5
Keep Going!Remove File Extension