Logic in Action: Express Router & Middleware Patterns
When you first start with Express, `app.get()` is enough. But as your application scales, you encounter the "spaghetti code" problem. Middleware and Routers are not just features; they are the architectural backbone of any professional Node.js API.
1. The Middleware Chain: An Assembly Line
Think of an HTTP request as a car frame on an assembly line. Each middleware function is a workstation. One station attaches wheels (parses JSON), another checks the paint (authentication), and another logs the progress (logging).
// 1. Parse Data
app.use(express.json());
// 2. Log Request
app.use(morgan('dev'));
// 3. Authenticate (Custom Middleware)
app.use((req, res, next) => {
if(req.headers.auth) next();
else res.status(401).send("Forbidden");
});If any station (middleware) detects a flaw, it can pull the car off the line (send a response) and stop the process. If everything is fine, it hits the `next()` button to move to the next station.
2. Modularizing with express.Router
A `Router` is essentially a mini-app. It creates an isolated instance of middleware and routes. This is critical for Separation of Concerns.
✔️ Good Practice
// users.js
const router = express.Router();
router.get('/', getAllUsers);
router.get('/:id', getUser);
module.exports = router;
// app.js
app.use('/users', userRouter);Clean, modular, and easy to test.
❌ Bad Practice
// app.js
app.get('/users', ...);
app.get('/users/:id', ...);
app.get('/products', ...);
app.get('/auth', ...);
// 1000 lines later...Monolithic file, hard to maintain.
3. The Special Case: Error Handling
Express detects error-handling middleware by the number of arguments. It must have 4 arguments: `(err, req, res, next)`.
If you pass an argument to `next()`, like `next(new Error('Boom'))`, Express skips all normal middleware and jumps straight to the next Error Handling middleware defined.
Key Takeaway: Use Global Middleware for things that apply to *every* request (like logging and body parsing). Use Routers to group related logic (like Users or Products). Always handle errors centrally to avoid crashing your server.