Built-In Middleware with Code Examples
Built-in middleware is already provided by Express. You don't need to create it — you just use it directly.
Common Built-In Middleware
express.static()
➤ Serves static files like CSS, JS, images.
➤ Example: Serves files from a folder (public
).
express.urlencoded()
➤ Parses incoming form data (application/x-www-form-urlencoded
).
➤ Helps you access form data via req.body
.
Basic Code
import express from "express";
const app = express();
Form Data Undefined
app.post("/submit", (req, resp) => {
console.log("user login details are :", req.body); // undefined without middleware
resp.send("Submit Page");
});
Use built-in middleware before routes:
app.use(express.urlencoded({ extended: false }));
This allows Express to read data from the form (like email
& password
).
Use express.static()
To serve static CSS file:
- Create folder:
public
- Add file:
public/style.css
- In HTML:
<link rel="stylesheet" href="/style.css" />
In index.js:
app.use(express.static("public"));
Now Express will automatically serve CSS and other static files from public/
.
Folder Structure:
project/
├── public/
│ └── style.css
├── view/
│ └── home.html
└── server.js