Express.js Masterclass
The Professional Backend Framework01.Home02.Introduction03.Express vs Native Node04.Express Generator05.Request Object (req)06.Response Object (res)07.Advanced Routing08.URL Params & Query09.Body Parsing10.Template Engines (EJS)11.Serving Static Files12.Middleware Architecture13.Must-Have Middleware14.File Uploads (Multer)15.Custom Error Handling16.Cookies & Sessions17.User Auth (Passport)18.Database Integration19.Data Validation20.Socket.io in Express21.Security & Helmet
Middleware Architecture
Express is essentially a series of **middleware** function calls. Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle.
What Middleware Can Do:
- Execute any code.
- Make changes to the request and the response objects.
- End the request-response cycle.
- Call the next middleware function in the stack.
The Lifecycle
app.use((req, res, next) => {
console.log('1. Middleware ran');
next(); // Passes control to next handler
});
app.get('/', (req, res) => {
console.log('2. Route handler ran');
res.send('Done'); // Ends the cycle
});Configuring Middleware Execution
If you don't call next(), the request will hang and the client will timeout. The only alternative to calling next() is to send a response back using res.send(), res.json(), etc.
Modular Design: Because Express uses this onion-like architecture, you can easily plug in security, logging, and data parsing tools without cluttering your main logic.
Synchronous vs Asynchronous Middleware
Modern Express supports async middleware functions. This is perfect for checking a database or calling an external API before a request reaches the route.
app.use(async (req, res, next) => {
const user = await User.findById(req.session.userId);
req.user = user;
next();
});