Use Middleware (like body-parser, Auth)
📌 What: Middleware functions in Express.js are functions that execute between the time a request is received and a response is sent. They can modify the req or res objects or end the request-response cycle.
🎯 Why: Middleware is useful for handling:
- Parsing: incoming JSON/form data (e.g.
body-parser)
- Authentication: verifying user tokens (e.g. JWT)
- Logging: request info (e.g.
morgan)
- Validation: check incoming inputs
⚙️ How: Use app.use() to register middleware globally, or pass it to a specific route.
// Install middleware
npm install express body-parser jsonwebtoken
// server.js
const express = require('express');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const app = express();
app.use(bodyParser.json()); // Middleware to parse JSON body
// 🔐 Auth Middleware Example
function authMiddleware(req, res, next) {
const token = req.headers.authorization?.split(" ")[1];
if (!token) return res.status(401).json({ error: "No token provided" });
try {
const decoded = jwt.verify(token, "SECRET_KEY");
req.user = decoded;
next(); // go to next middleware or route
} catch (err) {
res.status(401).json({ error: "Invalid token" });
}
}
// 🌐 Route with auth middleware
app.get("/profile", authMiddleware, (req, res) => {
res.json({ message: "Welcome, user!", user: req.user });
});
app.listen(3000, () => {
console.log("🚀 Server running on http://localhost:3000");
});
🕐 When: Use middleware:
app.use(express.json()) at the start to parse request bodies.
- For protected routes with authentication.
- For logging, input validation, error handling.
💡 Tip: You can create your own custom middleware and stack them in any order. Use next() to pass control to the next function in line.