Hello Dev Community! 👋
It is officially Day 44 of my daily coding run toward mastering the MERN stack! Up until yesterday, my Express.js server was strictly acting as a JSON API engine, returning raw object arrays. Today, I took a massive leap into full-stack orchestration by learning how to serve Static HTML pages, CSS sheets, and media assets directly from my backend server!
Following Prashant Sir's (Complete Coding) backend track, today I mastered how a backend framework handles public file routing efficiently.
🧠Key Learnings From Node.js Lecture 12 (Static File Delivery)
In production, your backend needs a clean way to hand over front-end templates without writing complex custom file-reading loops. Here is how I configured my system today:
1. The Power of express.static() Middleware
I learned that Express provides a built-in middleware called express.static(). It allows us to designate a specific directory (usually named public or assets) as a safe, accessible zone for client browsers.
2. Relative Path Mapping with path.join()
To ensure my server can find files correctly across different operating systems (Windows, Linux, Mac), I integrated Node's native path module along with the global variable __dirname:
javascript
const express = require("express");
const path = require("path");
const app = express();
const PORT = 8000;
// Built-in middleware to expose static assets cleanly onto the network layer
app.use(express.static(path.join(__dirname, "public")));
// Serving a complete static landing asset when hitting the root route
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "public", "index.html"));
});
app.listen(PORT, () => {
console.log(`Server live and rendering assets on http://localhost:${PORT}`);
});
Top comments (0)